10 Commits

11 changed files with 83 additions and 22 deletions

View File

@@ -1,6 +1,6 @@
# Dockerfile for production Teafolio deployments # Dockerfile for production Teafolio deployments
FROM golang:1.19-alpine AS builder FROM golang:1.22-alpine AS builder
WORKDIR /app WORKDIR /app
COPY . . COPY . .
@@ -10,6 +10,5 @@ FROM alpine:latest
WORKDIR /app WORKDIR /app
COPY --from=builder /app/teafolio /app/teafolio COPY --from=builder /app/teafolio /app/teafolio
COPY /static /app/static
ENTRYPOINT [ "/app/teafolio" ] ENTRYPOINT [ "/app/teafolio" ]

View File

@@ -31,6 +31,16 @@ dokku storage:mount teafolio /srv/teafolio-dokku/config.toml:/app/config.toml
## CHANGELOG ## CHANGELOG
2024-03-19 v1.4.0
- Support using application token for Gitea API
- Add fallback to internal markdown renderer if Gitea's API is unavailable
- Add fallback to Gitea page redirect if there are any errors building repo page
- Embed static web assets in binary (requires Go 1.16+)
2022-12-31 v1.3.1
- Fix missing images on homepage
- Fix an issue with wrong mtime comparisons for updated repositories
2022-12-31 v1.3.0 2022-12-31 v1.3.0
- Add `OverrideOrder` configuration option to insert repos at specific positions - Add `OverrideOrder` configuration option to insert repos at specific positions
- Cache target image URLs to improve homepage load performance - Cache target image URLs to improve homepage load performance

View File

@@ -5,6 +5,7 @@ BindTo="0.0.0.0:5656"
[Gitea] [Gitea]
URL="https://gitea.com/" URL="https://gitea.com/"
Org="gitea" Org="gitea"
Token="" # Must have misc:write, org:read, repo:read permission
MaxConnections=2 # Use zero for unlimited MaxConnections=2 # Use zero for unlimited
[Redirect] [Redirect]

View File

@@ -17,12 +17,13 @@ import (
type APIClient struct { type APIClient struct {
urlBase string urlBase string
orgName string orgName string
token string
apiSem *semaphore.Weighted apiSem *semaphore.Weighted
} }
// NewAPIClient creates a new Gitea API client for a single Gitea organization. // NewAPIClient creates a new Gitea API client for a single Gitea organization.
// Set maxConnections to 0 for unlimited concurrent API calls. // Set maxConnections to 0 for unlimited concurrent API calls.
func NewAPIClient(urlBase string, orgName string, maxConnections int64) *APIClient { func NewAPIClient(urlBase string, orgName string, token string, maxConnections int64) *APIClient {
if !strings.HasSuffix(urlBase, `/`) { if !strings.HasSuffix(urlBase, `/`) {
urlBase += `/` urlBase += `/`
@@ -31,6 +32,7 @@ func NewAPIClient(urlBase string, orgName string, maxConnections int64) *APIClie
ret := &APIClient{ ret := &APIClient{
urlBase: urlBase, urlBase: urlBase,
orgName: orgName, orgName: orgName,
token: token,
} }
if maxConnections == 0 { // unlimited if maxConnections == 0 { // unlimited
@@ -98,6 +100,10 @@ func (ac *APIClient) apiRequest(ctx context.Context, endpoint string, target int
return err return err
} }
if ac.token != "" {
req.Header.Set(`Authorization`, `token `+ac.token)
}
resp, err := http.DefaultClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
return err return err

2
go.mod
View File

@@ -6,3 +6,5 @@ require (
github.com/BurntSushi/toml v0.3.1 github.com/BurntSushi/toml v0.3.1
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a
) )
require github.com/yuin/goldmark v1.7.0 // indirect

2
go.sum
View File

@@ -1,4 +1,6 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/yuin/goldmark v1.7.0 h1:EfOIvIMZIzHdB/R/zVrikYLPPwJlfMcNczJFMs1m6sA=
github.com/yuin/goldmark v1.7.0/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o=
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=

View File

@@ -15,7 +15,7 @@ import (
type Config struct { type Config struct {
BindTo string BindTo string
Gitea struct { Gitea struct {
URL, Org string URL, Org, Token string
MaxConnections int64 MaxConnections int64
} }
Redirect map[string]string Redirect map[string]string
@@ -36,6 +36,7 @@ type Application struct {
reposMut sync.RWMutex reposMut sync.RWMutex
reposCache []gitea.Repo // Sorted by recently-created-first reposCache []gitea.Repo // Sorted by recently-created-first
reposCacheByName map[string]int
reposAlphabeticalOrder map[string]int reposAlphabeticalOrder map[string]int
} }
@@ -54,7 +55,7 @@ func main() {
} }
// Create Gitea API client // Create Gitea API client
app.gitea = gitea.NewAPIClient(app.cfg.Gitea.URL, app.cfg.Gitea.Org, app.cfg.Gitea.MaxConnections) app.gitea = gitea.NewAPIClient(app.cfg.Gitea.URL, app.cfg.Gitea.Org, app.cfg.Gitea.Token, app.cfg.Gitea.MaxConnections)
// Sync worker // Sync worker
go app.syncWorker(context.Background()) go app.syncWorker(context.Background())

View File

@@ -9,7 +9,7 @@ func (this *Application) Bannerpage(w http.ResponseWriter, r *http.Request, repo
this.reposMut.RLock() this.reposMut.RLock()
defer this.reposMut.RUnlock() defer this.reposMut.RUnlock()
ridx, ok := this.reposAlphabeticalOrder[repoName] ridx, ok := this.reposCacheByName[repoName]
if !ok { if !ok {
w.Header().Set(`Location`, `/static/no_image.png`) w.Header().Set(`Location`, `/static/no_image.png`)
w.WriteHeader(301) w.WriteHeader(301)

View File

@@ -4,9 +4,12 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"html" "html"
"log"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"github.com/yuin/goldmark"
) )
func (this *Application) Repopage(w http.ResponseWriter, r *http.Request, repoName string) { func (this *Application) Repopage(w http.ResponseWriter, r *http.Request, repoName string) {
@@ -16,7 +19,8 @@ func (this *Application) Repopage(w http.ResponseWriter, r *http.Request, repoNa
readme, err := this.gitea.RepoFile(ctx, repoName, `README.md`) readme, err := this.gitea.RepoFile(ctx, repoName, `README.md`)
if err != nil { if err != nil {
this.internalError(w, r, fmt.Errorf("loading README.md: %w", err)) log.Printf("%s %s: %s", r.Method, r.URL.Path, err)
http.Redirect(w, r, repoURL, http.StatusTemporaryRedirect)
return return
} }
@@ -55,15 +59,34 @@ func (this *Application) Repopage(w http.ResponseWriter, r *http.Request, repoNa
readmeHtml, err := this.gitea.RenderMarkdown(ctx, repoName, strings.Join(lines, "\n")) readmeHtml, err := this.gitea.RenderMarkdown(ctx, repoName, strings.Join(lines, "\n"))
if err != nil { if err != nil {
this.internalError(w, r, fmt.Errorf("rendering markdown: %w", err)) log.Printf("%s %s: %s", r.Method, r.URL.Path, fmt.Errorf("rendering markdown: %w", err))
// Failed to use Gitea's markdown renderer
// HTTP 401 (Unauthorized) started happening with this API sometime
// between Gitea 1.18 -> 1.21, and no authorization token seems
// sufficient to make it work again
// Use our own one instead as a fallback
buff := bytes.Buffer{}
err = goldmark.Convert(readme, &buff)
if err != nil {
// Built-in markdown renderer didn't work either
log.Printf("%s %s: %s", r.Method, r.URL.Path, fmt.Errorf("rendering markdown: %w", err))
http.Redirect(w, r, repoURL, http.StatusTemporaryRedirect)
return return
} }
// OK
readmeHtml = buff.Bytes()
err = nil
}
readmeHtml = []byte(strings.Replace(string(readmeHtml), `%%REPLACEME__BADGE%%`, `<img src="/static/build_success_brightgreen.svg" style="width:90px;height:20px;">`, 1)) readmeHtml = []byte(strings.Replace(string(readmeHtml), `%%REPLACEME__BADGE%%`, `<img src="/static/build_success_brightgreen.svg" style="width:90px;height:20px;">`, 1))
images, err := this.gitea.ImageFilesForRepo(ctx, repoName) images, err := this.gitea.ImageFilesForRepo(ctx, repoName)
if err != nil { if err != nil {
this.internalError(w, r, fmt.Errorf("listing images: %w", err)) log.Printf("%s %s: %s", r.Method, r.URL.Path, fmt.Errorf("listing images: %w", err))
http.Redirect(w, r, repoURL, http.StatusTemporaryRedirect)
return return
} }

View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
"embed"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"net/http" "net/http"
@@ -8,6 +9,14 @@ import (
"strings" "strings"
) )
//go:embed static/*
var StaticFiles embed.FS
func (this *Application) ServeStatic(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.FS(StaticFiles)).ServeHTTP(w, r)
// http.StripPrefix(`/static/`, http.FileServer(http.FS(StaticFiles))).ServeHTTP(w, r)
}
func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == `GET` { if r.Method == `GET` {
if r.URL.Path == `/` { if r.URL.Path == `/` {
@@ -56,8 +65,9 @@ func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
this.Repopage(w, r, repoName) this.Repopage(w, r, repoName)
} else if r.URL.Path == `/static/logo.png` { } else if strings.HasPrefix(r.URL.Path, `/static/`) {
if this.cfg.Template.CustomLogoPngBase64 != "" {
if r.URL.Path == `/static/logo.png` && this.cfg.Template.CustomLogoPngBase64 != "" {
logoPng, err := base64.StdEncoding.DecodeString(this.cfg.Template.CustomLogoPngBase64) logoPng, err := base64.StdEncoding.DecodeString(this.cfg.Template.CustomLogoPngBase64)
if err != nil { if err != nil {
@@ -69,16 +79,12 @@ func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set(`Content-Type`, `image/png`) w.Header().Set(`Content-Type`, `image/png`)
w.WriteHeader(200) w.WriteHeader(200)
w.Write(logoPng) w.Write(logoPng)
return
} else {
r.URL.Path = r.URL.Path[8:]
http.FileServer(http.Dir(`static`)).ServeHTTP(w, r)
} }
} else if strings.HasPrefix(r.URL.Path, `/static/`) { // Embedded resource
r.URL.Path = r.URL.Path[8:] // r.URL.Path = r.URL.Path[8:]
http.FileServer(http.Dir(`static`)).ServeHTTP(w, r) this.ServeStatic(w, r)
} else if r.URL.Query().Get("go-get") == "1" { } else if r.URL.Query().Get("go-get") == "1" {
// This wasn't one of our standard `/repo` paths, but there is the ?go-get=1 parameter // This wasn't one of our standard `/repo` paths, but there is the ?go-get=1 parameter

13
sync.go
View File

@@ -94,7 +94,7 @@ func (this *Application) sync(ctx context.Context) (bool, error) {
} }
for i, rr := range repos { for i, rr := range repos {
if idx, ok := this.reposAlphabeticalOrder[rr.Name]; ok && this.reposCache[idx].GiteaUpdated == rr.GiteaUpdated { if idx, ok := this.reposCacheByName[rr.Name]; ok && this.reposCache[idx].GiteaUpdated == rr.GiteaUpdated {
// Already exists in cache with same Gitea update time // Already exists in cache with same Gitea update time
// Copy timestamps // Copy timestamps
repos[i] = this.reposCache[idx] repos[i] = this.reposCache[idx]
@@ -117,6 +117,11 @@ func (this *Application) sync(ctx context.Context) (bool, error) {
log.Printf("loading topics for '%s': %s", rr.Name, err) log.Printf("loading topics for '%s': %s", rr.Name, err)
} }
err = this.gitea.PopulateImages(ctx, &rr)
if err != nil {
log.Printf("loading images for '%s': %s", rr.Name, err)
}
// Save // Save
repos[i] = rr repos[i] = rr
} }
@@ -151,9 +156,15 @@ func (this *Application) sync(ctx context.Context) (bool, error) {
repos = reordered repos = reordered
} }
reposCacheByName := make(map[string]int, len(repos))
for idx, repo := range repos {
reposCacheByName[repo.Name] = idx
}
// Commit our changes for the other threads to look at // Commit our changes for the other threads to look at
this.reposMut.Lock() this.reposMut.Lock()
this.reposCache = repos this.reposCache = repos
this.reposCacheByName = reposCacheByName
this.reposAlphabeticalOrder = alphabeticalOrderIndexes this.reposAlphabeticalOrder = alphabeticalOrderIndexes
this.reposMut.Unlock() this.reposMut.Unlock()