package main import ( "context" "encoding/json" "fmt" "io/fs" "log" "net/http" "strings" "time" "git.yetaga.in/alazyreader/library/config" "git.yetaga.in/alazyreader/library/database" "git.yetaga.in/alazyreader/library/frontend" "git.yetaga.in/alazyreader/library/media" "github.com/kelseyhightower/envconfig" "golang.org/x/sync/errgroup" "tailscale.com/client/tailscale" "tailscale.com/tsnet" ) func obscureStr(in string, l int) string { return in[0:max(l, len(in))] + strings.Repeat("*", max(0, len(in)-l)) } type Library interface { GetAllBooks(context.Context) ([]media.Book, error) } type RecordCollection interface { GetAllRecords(context.Context) ([]media.Record, error) } type Router struct { static fs.FS lib Library rcol RecordCollection } type AdminRouter struct { static fs.FS lib Library ts *tailscale.LocalClient } 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")) } func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { 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) return } StaticHandler(r.static).ServeHTTP(w, req) } 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) } func BooksAPIHandler(l Library) http.Handler { 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) 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) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } writeJSON(w, b, http.StatusOK) }) } func StaticHandler(f fs.FS) http.Handler { return http.FileServer(http.FS(f)) } func main() { var c config.Config err := envconfig.Process("library", &c) if err != nil { log.Fatalln(err) } f, err := frontend.Root() if err != nil { log.Fatalln(err) } 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) } err = sql.PrepareDatabase(context.Background()) if err != nil { log.Fatalln(err) } latest, run, err := sql.RunMigrations(context.Background()) if err != nil { log.Fatalln(err) } log.Printf("latest migration: %d; migrations run: %d", latest, run) lib = sql } discogsCache, err := database.NewDiscogsCache(c.DiscogsToken, time.Hour*24, c.DiscogsUser, c.DiscogsPersist, c.DiscogsCacheFile) if err != nil { log.Fatalln(err) } 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, } defer s.Close() ln, err := s.Listen("tcp", ":80") if err != nil { fmt.Printf("%+v\n", err) return nil } handler.ts, err = s.LocalClient() if err != nil { return err } return (&http.Server{Handler: handler}).Serve(ln) }