library/cmd/serve/main.go

192 lines
4.5 KiB
Go
Raw Normal View History

2021-06-26 18:08:35 +00:00
package main
import (
2021-07-02 22:13:58 +00:00
"context"
"encoding/json"
2023-12-31 01:27:24 +00:00
"fmt"
2021-06-26 18:08:35 +00:00
"io/fs"
2021-07-02 22:13:58 +00:00
"log"
2021-06-26 18:08:35 +00:00
"net/http"
2021-08-08 20:56:45 +00:00
"strings"
2022-03-13 22:04:09 +00:00
"time"
2021-06-26 18:08:35 +00:00
2021-07-03 00:46:58 +00:00
"git.yetaga.in/alazyreader/library/config"
2021-07-02 22:13:58 +00:00
"git.yetaga.in/alazyreader/library/database"
2021-06-26 18:08:35 +00:00
"git.yetaga.in/alazyreader/library/frontend"
2022-03-05 15:58:15 +00:00
"git.yetaga.in/alazyreader/library/media"
2021-07-02 22:47:14 +00:00
"github.com/kelseyhightower/envconfig"
2023-12-31 01:27:24 +00:00
"golang.org/x/sync/errgroup"
"tailscale.com/client/tailscale"
"tailscale.com/tsnet"
2021-06-26 18:08:35 +00:00
)
2022-03-13 22:04:09 +00:00
func obscureStr(in string, l int) string {
return in[0:max(l, len(in))] + strings.Repeat("*", max(0, len(in)-l))
}
2021-07-02 22:13:58 +00:00
type Library interface {
2022-03-05 15:58:15 +00:00
GetAllBooks(context.Context) ([]media.Book, error)
2021-07-02 22:13:58 +00:00
}
2022-03-13 22:04:09 +00:00
type RecordCollection interface {
GetAllRecords(context.Context) ([]media.Record, error)
}
2021-07-02 22:13:58 +00:00
type Router struct {
static fs.FS
lib Library
2022-03-13 22:04:09 +00:00
rcol RecordCollection
}
2023-12-31 01:27:24 +00:00
type AdminRouter struct {
static fs.FS
lib Library
ts *tailscale.LocalClient
}
2022-03-13 22:04:09 +00:00
func writeJSON(w http.ResponseWriter, b []byte, status int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
w.Write(b)
w.Write([]byte("\n"))
2021-07-02 22:13:58 +00:00
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
2022-03-13 22:04:09 +00:00
if req.URL.Path == "/api/records" {
RecordsAPIHandler(r.rcol).ServeHTTP(w, req)
return
}
if req.URL.Path == "/api/books" {
BooksAPIHandler(r.lib).ServeHTTP(w, req)
2021-07-02 22:13:58 +00:00
return
}
StaticHandler(r.static).ServeHTTP(w, req)
}
2023-12-31 01:27:24 +00:00
func (r *AdminRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
whois, _ := r.ts.WhoIs(req.Context(), req.RemoteAddr)
w.Write([]byte(fmt.Sprintf("%+v", whois.UserProfile.DisplayName)))
// StaticHandler(r.static).ServeHTTP(w, req)
}
2022-03-13 22:04:09 +00:00
func BooksAPIHandler(l Library) http.Handler {
2021-07-02 22:13:58 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
books, err := l.GetAllBooks(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := json.Marshal(books)
2022-03-13 22:04:09 +00:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, b, http.StatusOK)
})
}
func RecordsAPIHandler(l RecordCollection) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
books, err := l.GetAllRecords(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := json.Marshal(books)
2021-07-02 22:13:58 +00:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2022-03-13 22:04:09 +00:00
writeJSON(w, b, http.StatusOK)
2021-07-02 22:13:58 +00:00
})
}
func StaticHandler(f fs.FS) http.Handler {
return http.FileServer(http.FS(f))
}
2021-06-26 18:08:35 +00:00
func main() {
2021-07-03 00:46:58 +00:00
var c config.Config
2021-07-02 22:47:14 +00:00
err := envconfig.Process("library", &c)
if err != nil {
log.Fatalln(err)
}
2021-07-02 22:13:58 +00:00
f, err := frontend.Root()
if err != nil {
log.Fatalln(err)
}
2023-12-31 01:27:24 +00:00
var lib Library
if c.DBType == "memory" {
lib = &database.Memory{}
} else if c.DBType == "sql" {
if c.DBUser == "" || c.DBPass == "" || c.DBHost == "" || c.DBPort == "" || c.DBName == "" {
if c.DBPass != "" {
c.DBPass = obscureStr(c.DBPass, 3)
}
if c.DiscogsToken != "" {
c.DiscogsToken = obscureStr(c.DiscogsToken, 3)
}
log.Fatalf("vars: %+v", c)
}
sql, err := database.NewMySQLConnection(c.DBUser, c.DBPass, c.DBHost, c.DBPort, c.DBName)
if err != nil {
log.Fatalln(err)
2022-03-13 22:04:09 +00:00
}
2023-12-31 01:27:24 +00:00
err = sql.PrepareDatabase(context.Background())
if err != nil {
log.Fatalln(err)
}
latest, run, err := sql.RunMigrations(context.Background())
if err != nil {
log.Fatalln(err)
2021-08-08 20:56:45 +00:00
}
2023-12-31 01:27:24 +00:00
log.Printf("latest migration: %d; migrations run: %d", latest, run)
lib = sql
2021-07-02 22:47:14 +00:00
}
2023-12-31 01:27:24 +00:00
discogsCache, err := database.NewDiscogsCache(c.DiscogsToken, time.Hour*24, c.DiscogsUser, c.DiscogsPersist, c.DiscogsCacheFile)
2021-07-02 22:13:58 +00:00
if err != nil {
log.Fatalln(err)
}
2023-12-31 01:27:24 +00:00
errGroup := errgroup.Group{}
errGroup.Go(func() error {
return publicListener(8080, &Router{
static: f,
lib: lib,
rcol: discogsCache,
})
})
errGroup.Go(func() error {
f, _ := frontend.AdminRoot()
return tailscaleListener("library-admin", &AdminRouter{
static: f,
lib: lib,
})
})
log.Println(errGroup.Wait())
}
func publicListener(port int, handler http.Handler) error {
log.Printf("Listening on http://0.0.0.0:%d/", port)
return http.ListenAndServe(fmt.Sprintf(":%d", port), handler)
}
func tailscaleListener(hostname string, handler *AdminRouter) error {
s := &tsnet.Server{
Dir: ".config/" + hostname,
Hostname: hostname,
2021-07-02 22:13:58 +00:00
}
2023-12-31 01:27:24 +00:00
defer s.Close()
ln, err := s.Listen("tcp", ":80")
2021-07-02 22:13:58 +00:00
if err != nil {
2023-12-31 01:27:24 +00:00
fmt.Printf("%+v\n", err)
return nil
2021-07-02 22:13:58 +00:00
}
2023-12-31 01:27:24 +00:00
handler.ts, err = s.LocalClient()
2022-03-13 22:04:09 +00:00
if err != nil {
2023-12-31 01:27:24 +00:00
return err
2021-07-02 22:13:58 +00:00
}
2023-12-31 01:27:24 +00:00
return (&http.Server{Handler: handler}).Serve(ln)
2021-06-26 18:08:35 +00:00
}