Commit da1f3af
Antonio Mika
·
2026-10-10 22:14:55 -0400 EDT
parent cc428a5
refactor(apps): give each app its own config
73 files changed,
+681,
-777
+1,
-1
| ... | ... | @@ -9,7 +9,7 @@ import ( | |
| 9 | 9 | ) | |
| 10 | 10 | ||
| 11 | 11 | func main() { | |
| 12 | - | cfg := feeds.NewConfigSite("feeds-fetch") | |
| 12 | + | cfg := feeds.NewConfig("feeds-fetch") | |
| 13 | 13 | dbh := feeds.NewDB(postgres.NewDB(cfg.DbURL, cfg.Logger)) | |
| 14 | 14 | defer func() { | |
| 15 | 15 | _ = dbh.Close() |
+1,
-1
| ... | ... | @@ -26,7 +26,7 @@ func main() { | |
| 26 | 26 | defer func() { | |
| 27 | 27 | _ = pubsub.Close() | |
| 28 | 28 | }() | |
| 29 | - | cfg := pgs.NewPgsConfig(logger, nil, nil, drain) | |
| 29 | + | cfg := pgs.NewConfig(logger, nil, nil, drain) | |
| 30 | 30 | proxy := newProxyServe(cfg.Logger) | |
| 31 | 31 | httpCache, cache := pgs.NewPgsHttpCache(cfg, proxy) | |
| 32 | 32 | cacher := &cachedHttp{ |
+1,
-1
| ... | ... | @@ -29,7 +29,7 @@ func main() { | |
| 29 | 29 | defer func() { | |
| 30 | 30 | _ = pubsub.Close() | |
| 31 | 31 | }() | |
| 32 | - | cfg := pgs.NewPgsConfig(logger, dbpool, st, pubsub) | |
| 32 | + | cfg := pgs.NewConfig(logger, dbpool, st, pubsub) | |
| 33 | 33 | killCh := make(chan error) | |
| 34 | 34 | pgs.StartSshServer(cfg, killCh) | |
| 35 | 35 | } |
+1,
-1
| ... | ... | @@ -27,7 +27,7 @@ func main() { | |
| 27 | 27 | defer func() { | |
| 28 | 28 | _ = pubsub.Close() | |
| 29 | 29 | }() | |
| 30 | - | cfg := pgs.NewPgsConfig(logger, dbpool, st, pubsub) | |
| 30 | + | cfg := pgs.NewConfig(logger, dbpool, st, pubsub) | |
| 31 | 31 | killCh := make(chan error) | |
| 32 | 32 | ||
| 33 | 33 | // first time user experience flow |
+1,
-1
| ... | ... | @@ -29,6 +29,6 @@ func main() { | |
| 29 | 29 | defer func() { | |
| 30 | 30 | _ = pubsub.Close() | |
| 31 | 31 | }() | |
| 32 | - | cfg := pgs.NewPgsConfig(logger, dbpool, st, pubsub) | |
| 32 | + | cfg := pgs.NewConfig(logger, dbpool, st, pubsub) | |
| 33 | 33 | pgs.StartApiServer(cfg) | |
| 34 | 34 | } |
+1,
-4
| ... | ... | @@ -59,10 +59,7 @@ func updateDates(tx *sql.Tx, postID string, date *time.Time) error { | |
| 59 | 59 | func main() { | |
| 60 | 60 | logger := slog.Default() | |
| 61 | 61 | ||
| 62 | - | picoCfg := shared.NewConfigSite() | |
| 63 | - | picoCfg.Logger = logger | |
| 64 | - | picoCfg.DbURL = os.Getenv("DATABASE_URL") | |
| 65 | - | picoDb := postgres.NewDB(picoCfg.DbURL, picoCfg.Logger) | |
| 62 | + | picoDb := postgres.NewDB(os.Getenv("DATABASE_URL"), logger) | |
| 66 | 63 | ||
| 67 | 64 | logger.Info("fetching all posts") | |
| 68 | 65 | posts, err := findPosts(picoDb.Db) |
+1,
-5
| ... | ... | @@ -6,7 +6,6 @@ import ( | |
| 6 | 6 | "os" | |
| 7 | 7 | ||
| 8 | 8 | "github.com/picosh/pico/pkg/db/postgres" | |
| 9 | - | "github.com/picosh/pico/pkg/shared" | |
| 10 | 9 | ) | |
| 11 | 10 | ||
| 12 | 11 | func bail(err error) { |
| ... | ... | @@ -18,10 +17,7 @@ func bail(err error) { | |
| 18 | 17 | func main() { | |
| 19 | 18 | logger := slog.Default() | |
| 20 | 19 | ||
| 21 | - | picoCfg := shared.NewConfigSite() | |
| 22 | - | picoCfg.Logger = logger | |
| 23 | - | picoCfg.DbURL = os.Getenv("DATABASE_URL") | |
| 24 | - | picoDb := postgres.NewDB(picoCfg.DbURL, picoCfg.Logger) | |
| 20 | + | picoDb := postgres.NewDB(os.Getenv("DATABASE_URL"), logger) | |
| 25 | 21 | ||
| 26 | 22 | posts, err := picoDb.FindPosts() | |
| 27 | 23 | bail(err) |
+3,
-13
| ... | ... | @@ -10,7 +10,6 @@ import ( | |
| 10 | 10 | "github.com/jmoiron/sqlx" | |
| 11 | 11 | "github.com/picosh/pico/pkg/db" | |
| 12 | 12 | "github.com/picosh/pico/pkg/db/postgres" | |
| 13 | - | "github.com/picosh/pico/pkg/shared" | |
| 14 | 13 | ) | |
| 15 | 14 | ||
| 16 | 15 | func findPosts(dbpool *sqlx.DB) ([]*db.Post, error) { |
| ... | ... | @@ -102,20 +101,11 @@ type ConflictData struct { | |
| 102 | 101 | func main() { | |
| 103 | 102 | logger := slog.Default() | |
| 104 | 103 | ||
| 105 | - | listsCfg := shared.NewConfigSite() | |
| 106 | - | listsCfg.Logger = logger | |
| 107 | - | listsCfg.DbURL = os.Getenv("LISTS_DB_URL") | |
| 108 | - | listsDb := postgres.NewDB(listsCfg.DbURL, listsCfg.Logger) | |
| 104 | + | listsDb := postgres.NewDB(os.Getenv("LISTS_DB_URL"), logger) | |
| 109 | 105 | ||
| 110 | - | proseCfg := shared.NewConfigSite() | |
| 111 | - | proseCfg.DbURL = os.Getenv("PROSE_DB_URL") | |
| 112 | - | proseCfg.Logger = logger | |
| 113 | - | proseDb := postgres.NewDB(proseCfg.DbURL, proseCfg.Logger) | |
| 106 | + | proseDb := postgres.NewDB(os.Getenv("PROSE_DB_URL"), logger) | |
| 114 | 107 | ||
| 115 | - | picoCfg := shared.NewConfigSite() | |
| 116 | - | picoCfg.Logger = logger | |
| 117 | - | picoCfg.DbURL = os.Getenv("PICO_DB_URL") | |
| 118 | - | picoDb := postgres.NewDB(picoCfg.DbURL, picoCfg.Logger) | |
| 108 | + | picoDb := postgres.NewDB(os.Getenv("PICO_DB_URL"), logger) | |
| 119 | 109 | ||
| 120 | 110 | ctx := context.Background() | |
| 121 | 111 | tx, err := picoDb.Db.BeginTx(ctx, nil) |
+1,
-4
| ... | ... | @@ -10,10 +10,7 @@ import ( | |
| 10 | 10 | ||
| 11 | 11 | func main() { | |
| 12 | 12 | logger := slog.Default() | |
| 13 | - | picoCfg := shared.NewConfigSite() | |
| 14 | - | picoCfg.Logger = logger | |
| 15 | - | picoCfg.DbURL = os.Getenv("DATABASE_URL") | |
| 16 | - | picoDb := postgres.NewDB(picoCfg.DbURL, picoCfg.Logger) | |
| 13 | + | picoDb := postgres.NewDB(os.Getenv("DATABASE_URL"), logger) | |
| 17 | 14 | ||
| 18 | 15 | logger.Info("fetching all posts") | |
| 19 | 16 | posts, err := picoDb.FindPosts() |
| ... | ... | @@ -51,10 +51,7 @@ func findPosts(dbpool *sqlx.DB) ([]*db.Post, error) { | |
| 51 | 51 | func main() { | |
| 52 | 52 | logger := slog.Default() | |
| 53 | 53 | ||
| 54 | - | picoCfg := shared.NewConfigSite() | |
| 55 | - | picoCfg.Logger = logger | |
| 56 | - | picoCfg.DbURL = os.Getenv("DATABASE_URL") | |
| 57 | - | picoDb := postgres.NewDB(picoCfg.DbURL, picoCfg.Logger) | |
| 54 | + | picoDb := postgres.NewDB(os.Getenv("DATABASE_URL"), logger) | |
| 58 | 55 | ||
| 59 | 56 | logger.Info("fetching all posts") | |
| 60 | 57 | posts, err := findPosts(picoDb.Db) |
+4,
-17
| ... | ... | @@ -39,7 +39,7 @@ type oauth2Server struct { | |
| 39 | 39 | ResponseTypesSupported []string `json:"response_types_supported"` | |
| 40 | 40 | } | |
| 41 | 41 | ||
| 42 | - | func generateURL(cfg *shared.ConfigSite, path string, space string) string { | |
| 42 | + | func generateURL(cfg *Config, path string, space string) string { | |
| 43 | 43 | query := "" | |
| 44 | 44 | ||
| 45 | 45 | if space != "" { |
| ... | ... | @@ -50,7 +50,7 @@ func generateURL(cfg *shared.ConfigSite, path string, space string) string { | |
| 50 | 50 | } | |
| 51 | 51 | ||
| 52 | 52 | type ApiConfig struct { | |
| 53 | - | Cfg *shared.ConfigSite | |
| 53 | + | Cfg *Config | |
| 54 | 54 | Dbpool db.DB | |
| 55 | 55 | } | |
| 56 | 56 |
| ... | ... | @@ -919,18 +919,7 @@ func authMux(apiConfig *ApiConfig) *http.ServeMux { | |
| 919 | 919 | } | |
| 920 | 920 | ||
| 921 | 921 | func StartApiServer() { | |
| 922 | - | debug := shared.GetEnv("AUTH_DEBUG", "0") | |
| 923 | - | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 924 | - | ||
| 925 | - | cfg := &shared.ConfigSite{ | |
| 926 | - | DbURL: shared.GetEnv("DATABASE_URL", ""), | |
| 927 | - | Debug: debug == "1", | |
| 928 | - | Issuer: shared.GetEnv("AUTH_ISSUER", "pico.sh"), | |
| 929 | - | Domain: shared.GetEnv("AUTH_DOMAIN", "http://0.0.0.0:3000"), | |
| 930 | - | Port: shared.GetEnv("AUTH_WEB_PORT", "3000"), | |
| 931 | - | Secret: shared.GetEnv("PICO_SECRET", ""), | |
| 932 | - | SecretWebhook: shared.GetEnv("PICO_SECRET_WEBHOOK", ""), | |
| 933 | - | } | |
| 922 | + | cfg := NewConfig() | |
| 934 | 923 | ||
| 935 | 924 | if cfg.SecretWebhook == "" { | |
| 936 | 925 | panic("must provide PICO_SECRET_WEBHOOK environment variable") |
| ... | ... | @@ -940,9 +929,7 @@ func StartApiServer() { | |
| 940 | 929 | panic("must provide PICO_SECRET environment variable") | |
| 941 | 930 | } | |
| 942 | 931 | ||
| 943 | - | logger := shared.CreateLogger("auth-web", withPipe) | |
| 944 | - | ||
| 945 | - | cfg.Logger = logger | |
| 932 | + | logger := cfg.Logger | |
| 946 | 933 | ||
| 947 | 934 | db := postgres.NewDB(cfg.DbURL, logger) | |
| 948 | 935 | defer func() { |
+1,
-1
| ... | ... | @@ -279,7 +279,7 @@ func mkpath(path string) string { | |
| 279 | 279 | ||
| 280 | 280 | func setupTest() *ApiConfig { | |
| 281 | 281 | logger := shared.CreateLogger("auth-test", false) | |
| 282 | - | cfg := &shared.ConfigSite{ | |
| 282 | + | cfg := &Config{ | |
| 283 | 283 | Issuer: "auth.pico.test", | |
| 284 | 284 | Domain: "http://0.0.0.0:3000", | |
| 285 | 285 | Port: "3000", |
+35,
-0
| ... | ... | @@ -0,0 +1,35 @@ | |
| 1 | + | package auth | |
| 2 | + | ||
| 3 | + | import ( | |
| 4 | + | "log/slog" | |
| 5 | + | "strings" | |
| 6 | + | ||
| 7 | + | "github.com/picosh/pico/pkg/shared" | |
| 8 | + | ) | |
| 9 | + | ||
| 10 | + | type Config struct { | |
| 11 | + | Debug bool | |
| 12 | + | DbURL string | |
| 13 | + | Issuer string | |
| 14 | + | Domain string | |
| 15 | + | Port string | |
| 16 | + | Secret string | |
| 17 | + | SecretWebhook string | |
| 18 | + | Logger *slog.Logger | |
| 19 | + | } | |
| 20 | + | ||
| 21 | + | func NewConfig() *Config { | |
| 22 | + | debug := shared.GetEnv("AUTH_DEBUG", "0") | |
| 23 | + | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 24 | + | ||
| 25 | + | return &Config{ | |
| 26 | + | DbURL: shared.GetEnv("DATABASE_URL", ""), | |
| 27 | + | Debug: debug == "1", | |
| 28 | + | Issuer: shared.GetEnv("AUTH_ISSUER", "pico.sh"), | |
| 29 | + | Domain: shared.GetEnv("AUTH_DOMAIN", "http://0.0.0.0:3000"), | |
| 30 | + | Port: shared.GetEnv("AUTH_WEB_PORT", "3000"), | |
| 31 | + | Secret: shared.GetEnv("PICO_SECRET", ""), | |
| 32 | + | SecretWebhook: shared.GetEnv("PICO_SECRET_WEBHOOK", ""), | |
| 33 | + | Logger: shared.CreateLogger("auth-web", withPipe), | |
| 34 | + | } | |
| 35 | + | } |
+10,
-9
| ... | ... | @@ -98,23 +98,24 @@ func (web *webRouter) unsubHandler(w http.ResponseWriter, r *http.Request) { | |
| 98 | 98 | } | |
| 99 | 99 | ||
| 100 | 100 | type webRouter struct { | |
| 101 | - | cfg *shared.ConfigSite | |
| 101 | + | cfg *Config | |
| 102 | 102 | db DB | |
| 103 | 103 | } | |
| 104 | 104 | ||
| 105 | 105 | func (web *webRouter) mux() *http.ServeMux { | |
| 106 | 106 | cfg := web.cfg | |
| 107 | + | files := cfg.Static() | |
| 107 | 108 | mux := http.NewServeMux() | |
| 108 | - | mux.HandleFunc("GET /{$}", router.CreatePageHandler(cfg, "html/marketing.page.tmpl")) | |
| 109 | + | mux.HandleFunc("GET /{$}", files.Page("html/marketing.page.tmpl")) | |
| 109 | 110 | mux.HandleFunc("GET /keep-alive/{id...}", web.keepAliveHandler) | |
| 110 | 111 | mux.HandleFunc("GET /unsub/{id...}", web.unsubHandler) | |
| 111 | 112 | mux.Handle("GET /_metrics", promhttp.Handler()) | |
| 112 | - | mux.HandleFunc("GET /main.css", router.ServeFile(cfg, "main.css", "text/css")) | |
| 113 | - | mux.HandleFunc("GET /card.png", router.ServeFile(cfg, "card.png", "image/png")) | |
| 114 | - | mux.HandleFunc("GET /favicon-16x16.png", router.ServeFile(cfg, "favicon-16x16.png", "image/png")) | |
| 115 | - | mux.HandleFunc("GET /apple-touch-icon.png", router.ServeFile(cfg, "apple-touch-icon.png", "image/png")) | |
| 116 | - | mux.HandleFunc("GET /favicon.ico", router.ServeFile(cfg, "favicon.ico", "image/x-icon")) | |
| 117 | - | mux.HandleFunc("GET /robots.txt", router.ServeFile(cfg, "robots.txt", "text/plain")) | |
| 113 | + | mux.HandleFunc("GET /main.css", files.File("main.css", "text/css")) | |
| 114 | + | mux.HandleFunc("GET /card.png", files.File("card.png", "image/png")) | |
| 115 | + | mux.HandleFunc("GET /favicon-16x16.png", files.File("favicon-16x16.png", "image/png")) | |
| 116 | + | mux.HandleFunc("GET /apple-touch-icon.png", files.File("apple-touch-icon.png", "image/png")) | |
| 117 | + | mux.HandleFunc("GET /favicon.ico", files.File("favicon.ico", "image/x-icon")) | |
| 118 | + | mux.HandleFunc("GET /robots.txt", files.File("robots.txt", "text/plain")) | |
| 118 | 119 | if cfg.Debug { | |
| 119 | 120 | router.CreatePProfRoutesMux(mux) | |
| 120 | 121 | } |
| ... | ... | @@ -122,7 +123,7 @@ func (web *webRouter) mux() *http.ServeMux { | |
| 122 | 123 | } | |
| 123 | 124 | ||
| 124 | 125 | func StartApiServer() { | |
| 125 | - | cfg := NewConfigSite("feeds-web") | |
| 126 | + | cfg := NewConfig("feeds-web") | |
| 126 | 127 | db := NewDB(postgres.NewDB(cfg.DbURL, cfg.Logger)) | |
| 127 | 128 | defer func() { | |
| 128 | 129 | _ = db.Close() |
+1,
-1
| ... | ... | @@ -12,7 +12,7 @@ import ( | |
| 12 | 12 | ||
| 13 | 13 | func TestRoutes(t *testing.T) { | |
| 14 | 14 | t.Chdir("../../..") | |
| 15 | - | cfg := NewConfigSite("feeds-test") | |
| 15 | + | cfg := NewConfig("feeds-test") | |
| 16 | 16 | cfg.Logger = slog.New(slog.DiscardHandler) | |
| 17 | 17 | web := &webRouter{cfg: cfg, db: stub.NewPostsDB(cfg.Logger, &db.User{ID: "user-1"})} | |
| 18 | 18 | mux := web.mux() |
+1,
-1
| ... | ... | @@ -11,7 +11,7 @@ import ( | |
| 11 | 11 | "github.com/picosh/pico/pkg/shared" | |
| 12 | 12 | ) | |
| 13 | 13 | ||
| 14 | - | func Middleware(dbpool DB, cfg *shared.ConfigSite) pssh.SSHServerMiddleware { | |
| 14 | + | func Middleware(dbpool DB, cfg *Config) pssh.SSHServerMiddleware { | |
| 15 | 15 | return func(next pssh.SSHServerHandler) pssh.SSHServerHandler { | |
| 16 | 16 | return func(sesh *pssh.SSHServerConnSession) error { | |
| 17 | 17 | args := sesh.Command() |
+36,
-3
| ... | ... | @@ -1,12 +1,31 @@ | |
| 1 | 1 | package feeds | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | + | "html/template" | |
| 5 | + | "log/slog" | |
| 6 | + | "path/filepath" | |
| 4 | 7 | "strings" | |
| 5 | 8 | ||
| 6 | 9 | "github.com/picosh/pico/pkg/shared" | |
| 10 | + | "github.com/picosh/pico/pkg/shared/router" | |
| 7 | 11 | ) | |
| 8 | 12 | ||
| 9 | - | func NewConfigSite(service string) *shared.ConfigSite { | |
| 13 | + | // staticDir holds feeds' templates and public files. | |
| 14 | + | const staticDir = "pkg/apps/feeds" | |
| 15 | + | ||
| 16 | + | type Config struct { | |
| 17 | + | Debug bool | |
| 18 | + | SendgridKey string | |
| 19 | + | Domain string | |
| 20 | + | Port string | |
| 21 | + | Protocol string | |
| 22 | + | DbURL string | |
| 23 | + | Space string | |
| 24 | + | AllowedExt []string | |
| 25 | + | Logger *slog.Logger | |
| 26 | + | } | |
| 27 | + | ||
| 28 | + | func NewConfig(service string) *Config { | |
| 10 | 29 | debug := shared.GetEnv("FEEDS_DEBUG", "0") | |
| 11 | 30 | domain := shared.GetEnv("FEEDS_DOMAIN", "feeds.pico.sh") | |
| 12 | 31 | port := shared.GetEnv("FEEDS_WEB_PORT", "3000") |
| ... | ... | @@ -15,7 +34,7 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 15 | 34 | sendgridKey := shared.GetEnv("SENDGRID_API_KEY", "") | |
| 16 | 35 | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 17 | 36 | ||
| 18 | - | return &shared.ConfigSite{ | |
| 37 | + | return &Config{ | |
| 19 | 38 | Debug: debug == "1", | |
| 20 | 39 | SendgridKey: sendgridKey, | |
| 21 | 40 | Domain: domain, |
| ... | ... | @@ -24,7 +43,21 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 24 | 43 | DbURL: dbURL, | |
| 25 | 44 | Space: "feeds", | |
| 26 | 45 | AllowedExt: []string{".txt", ".lxt"}, | |
| 27 | - | HiddenPosts: []string{}, | |
| 28 | 46 | Logger: shared.CreateLogger(service, withPipe), | |
| 29 | 47 | } | |
| 30 | 48 | } | |
| 49 | + | ||
| 50 | + | func (c *Config) StaticPath(fname string) string { | |
| 51 | + | return filepath.Join(staticDir, fname) | |
| 52 | + | } | |
| 53 | + | ||
| 54 | + | func (c *Config) Static() router.Static { | |
| 55 | + | return router.Static{ | |
| 56 | + | Dir: staticDir, | |
| 57 | + | Logger: c.Logger, | |
| 58 | + | Site: shared.SitePageData{ | |
| 59 | + | Domain: template.URL(c.Domain), | |
| 60 | + | HomeURL: template.URL("//" + c.Domain), | |
| 61 | + | }, | |
| 62 | + | } | |
| 63 | + | } |
+2,
-2
| ... | ... | @@ -128,14 +128,14 @@ func isValidItem(logger *slog.Logger, item *gofeed.Item, feedItems []*db.FeedIte | |
| 128 | 128 | } | |
| 129 | 129 | ||
| 130 | 130 | type Fetcher struct { | |
| 131 | - | cfg *shared.ConfigSite | |
| 131 | + | cfg *Config | |
| 132 | 132 | db DB | |
| 133 | 133 | auth sasl.Client | |
| 134 | 134 | gron *gronx.Gronx | |
| 135 | 135 | host string | |
| 136 | 136 | } | |
| 137 | 137 | ||
| 138 | - | func NewFetcher(dbpool DB, cfg *shared.ConfigSite) *Fetcher { | |
| 138 | + | func NewFetcher(dbpool DB, cfg *Config) *Fetcher { | |
| 139 | 139 | host := os.Getenv("PICO_SMTP_HOST") | |
| 140 | 140 | smtPass := os.Getenv("PICO_SMTP_PASS") | |
| 141 | 141 | emailLogin := os.Getenv("PICO_SMTP_USER") |
+1,
-1
| ... | ... | @@ -23,7 +23,7 @@ func StartSshServer() { | |
| 23 | 23 | host := shared.GetEnv("FEEDS_HOST", "0.0.0.0") | |
| 24 | 24 | port := shared.GetEnv("FEEDS_SSH_PORT", "2222") | |
| 25 | 25 | promPort := shared.GetEnv("FEEDS_PROM_PORT", "9222") | |
| 26 | - | cfg := NewConfigSite(appName) | |
| 26 | + | cfg := NewConfig(appName) | |
| 27 | 27 | logger := cfg.Logger | |
| 28 | 28 | ||
| 29 | 29 | ctx, cancel := context.WithCancel(context.Background()) |
+3,
-3
| ... | ... | @@ -19,7 +19,7 @@ import ( | |
| 19 | 19 | ||
| 20 | 20 | // UploadHandler stores every file as a feed. | |
| 21 | 21 | type UploadHandler struct { | |
| 22 | - | Cfg *shared.ConfigSite | |
| 22 | + | Cfg *Config | |
| 23 | 23 | DB DB | |
| 24 | 24 | } | |
| 25 | 25 |
| ... | ... | @@ -29,7 +29,7 @@ var ( | |
| 29 | 29 | _ sendutils.FileRenamer = (*UploadHandler)(nil) | |
| 30 | 30 | ) | |
| 31 | 31 | ||
| 32 | - | func NewUploadHandler(cfg *shared.ConfigSite, dbpool DB) *UploadHandler { | |
| 32 | + | func NewUploadHandler(cfg *Config, dbpool DB) *UploadHandler { | |
| 33 | 33 | return &UploadHandler{Cfg: cfg, DB: dbpool} | |
| 34 | 34 | } | |
| 35 | 35 |
| ... | ... | @@ -100,7 +100,7 @@ func (h *UploadHandler) Write(s *pssh.SSHServerConnSession, entry *sendutils.Fil | |
| 100 | 100 | return "", err | |
| 101 | 101 | } | |
| 102 | 102 | logger.Info("saved feed", "new", cur == nil, "changed", changed) | |
| 103 | - | return h.Cfg.FullPostURL(shared.NewCreateURL(h.Cfg), user.Name, post.Slug), nil | |
| 103 | + | return shared.NewCreateURL(h.Cfg.Protocol, h.Cfg.Domain).FullPostURL(user.Name, post.Slug), nil | |
| 104 | 104 | } | |
| 105 | 105 | ||
| 106 | 106 | // Rename moves a feed to a new filename in place, keeping its digest state. |
+1,
-1
| ... | ... | @@ -26,7 +26,7 @@ func TestWriteKeepsDigestState(t *testing.T) { | |
| 26 | 26 | user := &db.User{ID: "user-1", Name: "tester"} | |
| 27 | 27 | pssh.SetUser(session, user) | |
| 28 | 28 | posts := stub.NewPostsDB(logger, user) | |
| 29 | - | cfg := NewConfigSite("feeds-test") | |
| 29 | + | cfg := NewConfig("feeds-test") | |
| 30 | 30 | h := NewUploadHandler(cfg, posts) | |
| 31 | 31 | write := func(text string, mtime int64) { | |
| 32 | 32 | t.Helper() |
+27,
-26
| ... | ... | @@ -72,7 +72,7 @@ type HeaderTxt struct { | |
| 72 | 72 | } | |
| 73 | 73 | ||
| 74 | 74 | func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 75 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 75 | + | username := router.GetUsernameFromRequest(r) | |
| 76 | 76 | dbpool := web.db | |
| 77 | 77 | blogger := web.cfg.Logger | |
| 78 | 78 | logger := blogger.With("user", username) |
| ... | ... | @@ -95,7 +95,7 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 95 | 95 | ||
| 96 | 96 | posts := pager.Data | |
| 97 | 97 | ||
| 98 | - | ts, err := router.RenderTemplate(cfg, []string{ | |
| 98 | + | ts, err := router.RenderTemplate(staticDir, []string{ | |
| 99 | 99 | cfg.StaticPath("html/blog.page.tmpl"), | |
| 100 | 100 | }) | |
| 101 | 101 |
| ... | ... | @@ -110,12 +110,12 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 110 | 110 | Bio: "", | |
| 111 | 111 | } | |
| 112 | 112 | ||
| 113 | - | curl := shared.CreateURLFromRequest(cfg, r) | |
| 113 | + | curl := shared.CreateURLFromRequest(cfg.Protocol, cfg.Domain, r) | |
| 114 | 114 | postCollection := make([]PostItemData, 0, len(posts)) | |
| 115 | 115 | for _, post := range posts { | |
| 116 | 116 | p := PostItemData{ | |
| 117 | - | URL: template.URL(cfg.FullPostURL(curl, post.Username, post.Slug)), | |
| 118 | - | BlogURL: template.URL(cfg.FullBlogURL(curl, post.Username)), | |
| 117 | + | URL: template.URL(curl.FullPostURL(post.Username, post.Slug)), | |
| 118 | + | BlogURL: template.URL(curl.FullBlogURL(post.Username)), | |
| 119 | 119 | Title: post.Filename, | |
| 120 | 120 | PublishAt: post.PublishAt.Format(time.DateOnly), | |
| 121 | 121 | PublishAtISO: post.PublishAt.Format(time.RFC3339), |
| ... | ... | @@ -126,10 +126,10 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 126 | 126 | } | |
| 127 | 127 | ||
| 128 | 128 | data := BlogPageData{ | |
| 129 | - | Site: *cfg.GetSiteData(), | |
| 129 | + | Site: cfg.SiteData(), | |
| 130 | 130 | PageTitle: headerTxt.Title, | |
| 131 | - | URL: template.URL(cfg.FullBlogURL(curl, username)), | |
| 132 | - | RSSURL: template.URL(cfg.RssBlogURL(curl, username, "")), | |
| 131 | + | URL: template.URL(curl.FullBlogURL(username)), | |
| 132 | + | RSSURL: template.URL(curl.RssBlogURL(username, "")), | |
| 133 | 133 | Header: headerTxt, | |
| 134 | 134 | Username: username, | |
| 135 | 135 | Posts: postCollection, |
| ... | ... | @@ -155,7 +155,7 @@ func GetBlogName(username string) string { | |
| 155 | 155 | } | |
| 156 | 156 | ||
| 157 | 157 | func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 158 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 158 | + | username := router.GetUsernameFromRequest(r) | |
| 159 | 159 | cfg := web.cfg | |
| 160 | 160 | slug, _ := url.PathUnescape(r.PathValue("slug")) | |
| 161 | 161 |
| ... | ... | @@ -201,7 +201,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 201 | 201 | } | |
| 202 | 202 | ||
| 203 | 203 | data = PostPageData{ | |
| 204 | - | Site: *cfg.GetSiteData(), | |
| 204 | + | Site: cfg.SiteData(), | |
| 205 | 205 | PageTitle: post.Filename, | |
| 206 | 206 | URL: template.URL(cfg.PostURL(post.Username, post.Slug)), | |
| 207 | 207 | RawURL: template.URL(cfg.RawPostURL(post.Username, post.Slug)), |
| ... | ... | @@ -220,7 +220,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 220 | 220 | } else { | |
| 221 | 221 | logger.Info("paste not found") | |
| 222 | 222 | data = PostPageData{ | |
| 223 | - | Site: *cfg.GetSiteData(), | |
| 223 | + | Site: cfg.SiteData(), | |
| 224 | 224 | PageTitle: "Paste not found", | |
| 225 | 225 | Description: "Paste not found", | |
| 226 | 226 | Title: "Paste not found", |
| ... | ... | @@ -235,7 +235,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 235 | 235 | } | |
| 236 | 236 | } | |
| 237 | 237 | ||
| 238 | - | ts, err := router.RenderTemplate(cfg, []string{ | |
| 238 | + | ts, err := router.RenderTemplate(staticDir, []string{ | |
| 239 | 239 | cfg.StaticPath("html/post.page.tmpl"), | |
| 240 | 240 | }) | |
| 241 | 241 |
| ... | ... | @@ -252,7 +252,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 252 | 252 | } | |
| 253 | 253 | ||
| 254 | 254 | func (web *webRouter) postHandlerRaw(w http.ResponseWriter, r *http.Request) { | |
| 255 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 255 | + | username := router.GetUsernameFromRequest(r) | |
| 256 | 256 | cfg := web.cfg | |
| 257 | 257 | slug, _ := url.PathUnescape(r.PathValue("slug")) | |
| 258 | 258 |
| ... | ... | @@ -285,20 +285,21 @@ func (web *webRouter) postHandlerRaw(w http.ResponseWriter, r *http.Request) { | |
| 285 | 285 | } | |
| 286 | 286 | ||
| 287 | 287 | type webRouter struct { | |
| 288 | - | cfg *shared.ConfigSite | |
| 288 | + | cfg *Config | |
| 289 | 289 | db DB | |
| 290 | 290 | } | |
| 291 | 291 | ||
| 292 | 292 | func (web *webRouter) static(mux *http.ServeMux) { | |
| 293 | 293 | cfg := web.cfg | |
| 294 | - | mux.HandleFunc("GET /main.css", router.ServeFile(cfg, "main.css", "text/css")) | |
| 295 | - | mux.HandleFunc("GET /smol.css", router.ServeFile(cfg, "smol.css", "text/css")) | |
| 296 | - | mux.HandleFunc("GET /syntax.css", router.ServeFile(cfg, "syntax.css", "text/css")) | |
| 297 | - | mux.HandleFunc("GET /card.png", router.ServeFile(cfg, "card.png", "image/png")) | |
| 298 | - | mux.HandleFunc("GET /favicon-16x16.png", router.ServeFile(cfg, "favicon-16x16.png", "image/png")) | |
| 299 | - | mux.HandleFunc("GET /apple-touch-icon.png", router.ServeFile(cfg, "apple-touch-icon.png", "image/png")) | |
| 300 | - | mux.HandleFunc("GET /favicon.ico", router.ServeFile(cfg, "favicon.ico", "image/x-icon")) | |
| 301 | - | mux.HandleFunc("GET /robots.txt", router.ServeFile(cfg, "robots.txt", "text/plain")) | |
| 294 | + | files := cfg.Static() | |
| 295 | + | mux.HandleFunc("GET /main.css", files.File("main.css", "text/css")) | |
| 296 | + | mux.HandleFunc("GET /smol.css", files.File("smol.css", "text/css")) | |
| 297 | + | mux.HandleFunc("GET /syntax.css", files.File("syntax.css", "text/css")) | |
| 298 | + | mux.HandleFunc("GET /card.png", files.File("card.png", "image/png")) | |
| 299 | + | mux.HandleFunc("GET /favicon-16x16.png", files.File("favicon-16x16.png", "image/png")) | |
| 300 | + | mux.HandleFunc("GET /apple-touch-icon.png", files.File("apple-touch-icon.png", "image/png")) | |
| 301 | + | mux.HandleFunc("GET /favicon.ico", files.File("favicon.ico", "image/x-icon")) | |
| 302 | + | mux.HandleFunc("GET /robots.txt", files.File("robots.txt", "text/plain")) | |
| 302 | 303 | if cfg.Debug { | |
| 303 | 304 | router.CreatePProfRoutesMux(mux) | |
| 304 | 305 | } |
| ... | ... | @@ -307,8 +308,8 @@ func (web *webRouter) static(mux *http.ServeMux) { | |
| 307 | 308 | // mainMux serves the marketing site and users' pastes below /{user}. | |
| 308 | 309 | func (web *webRouter) mainMux() *http.ServeMux { | |
| 309 | 310 | mux := http.NewServeMux() | |
| 310 | - | mux.HandleFunc("GET /{$}", router.CreatePageHandler(web.cfg, "html/marketing.page.tmpl")) | |
| 311 | - | mux.HandleFunc("GET /check", router.CheckHandler(web.cfg, web.db)) | |
| 311 | + | mux.HandleFunc("GET /{$}", web.cfg.Static().Page("html/marketing.page.tmpl")) | |
| 312 | + | mux.HandleFunc("GET /check", router.CheckHandler(web.cfg.Domain, web.cfg.Space, web.db)) | |
| 312 | 313 | mux.Handle("GET /_metrics", promhttp.Handler()) | |
| 313 | 314 | web.static(mux) | |
| 314 | 315 | mux.HandleFunc("GET /{user}", web.blogHandler) |
| ... | ... | @@ -352,7 +353,7 @@ func (web *webRouter) rawRoute(w http.ResponseWriter, r *http.Request) { | |
| 352 | 353 | } | |
| 353 | 354 | ||
| 354 | 355 | func StartApiServer() { | |
| 355 | - | cfg := NewConfigSite("pastes-web") | |
| 356 | + | cfg := NewConfig("pastes-web") | |
| 356 | 357 | db := NewDB(postgres.NewDB(cfg.DbURL, cfg.Logger)) | |
| 357 | 358 | defer func() { | |
| 358 | 359 | _ = db.Close() |
| ... | ... | @@ -362,7 +363,7 @@ func StartApiServer() { | |
| 362 | 363 | go CronDeleteExpiredPosts(cfg, db) | |
| 363 | 364 | ||
| 364 | 365 | web := &webRouter{cfg: cfg, db: db} | |
| 365 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 366 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 366 | 367 | ||
| 367 | 368 | portStr := fmt.Sprintf(":%s", cfg.Port) | |
| 368 | 369 | logger.Info( |
+4,
-4
| ... | ... | @@ -35,7 +35,7 @@ func (m *pasteDB) FindPostWithSlug(slug string, _ string, _ string) (*db.Post, e | |
| 35 | 35 | func TestLargePasteEscapesHTML(t *testing.T) { | |
| 36 | 36 | t.Chdir("../../..") | |
| 37 | 37 | logger := slog.New(slog.DiscardHandler) | |
| 38 | - | cfg := &shared.ConfigSite{ | |
| 38 | + | cfg := &Config{ | |
| 39 | 39 | Domain: "pastes.test", Protocol: "https", Space: "pastes", Logger: logger, | |
| 40 | 40 | } | |
| 41 | 41 | now := time.Now() |
| ... | ... | @@ -48,7 +48,7 @@ func TestLargePasteEscapesHTML(t *testing.T) { | |
| 48 | 48 | }, | |
| 49 | 49 | } | |
| 50 | 50 | web := &webRouter{cfg: cfg, db: dbpool} | |
| 51 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 51 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 52 | 52 | ||
| 53 | 53 | page := httptest.NewRecorder() | |
| 54 | 54 | handler.ServeHTTP(page, httptest.NewRequest(http.MethodGet, "https://tester.pastes.test/test.html", nil)) |
| ... | ... | @@ -73,7 +73,7 @@ func TestLargePasteEscapesHTML(t *testing.T) { | |
| 73 | 73 | func TestRoutes(t *testing.T) { | |
| 74 | 74 | t.Chdir("../../..") | |
| 75 | 75 | logger := slog.New(slog.DiscardHandler) | |
| 76 | - | cfg := &shared.ConfigSite{ | |
| 76 | + | cfg := &Config{ | |
| 77 | 77 | Domain: "pastes.test", Protocol: "https", Space: "pastes", Logger: logger, | |
| 78 | 78 | } | |
| 79 | 79 | now := time.Now() |
| ... | ... | @@ -85,7 +85,7 @@ func TestRoutes(t *testing.T) { | |
| 85 | 85 | }, | |
| 86 | 86 | } | |
| 87 | 87 | web := &webRouter{cfg: cfg, db: dbpool} | |
| 88 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 88 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 89 | 89 | ||
| 90 | 90 | for _, tt := range []struct { | |
| 91 | 91 | url string |
+49,
-2
| ... | ... | @@ -1,12 +1,32 @@ | |
| 1 | 1 | package pastes | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | + | "fmt" | |
| 5 | + | "html/template" | |
| 6 | + | "log/slog" | |
| 7 | + | "net/url" | |
| 8 | + | "path/filepath" | |
| 4 | 9 | "strings" | |
| 5 | 10 | ||
| 6 | 11 | "github.com/picosh/pico/pkg/shared" | |
| 12 | + | "github.com/picosh/pico/pkg/shared/router" | |
| 7 | 13 | ) | |
| 8 | 14 | ||
| 9 | - | func NewConfigSite(service string) *shared.ConfigSite { | |
| 15 | + | // staticDir holds pastes' templates and public files. | |
| 16 | + | const staticDir = "pkg/apps/pastes" | |
| 17 | + | ||
| 18 | + | type Config struct { | |
| 19 | + | Debug bool | |
| 20 | + | Domain string | |
| 21 | + | Port string | |
| 22 | + | Protocol string | |
| 23 | + | DbURL string | |
| 24 | + | Space string | |
| 25 | + | MaxAssetSize int64 | |
| 26 | + | Logger *slog.Logger | |
| 27 | + | } | |
| 28 | + | ||
| 29 | + | func NewConfig(service string) *Config { | |
| 10 | 30 | debug := shared.GetEnv("PASTES_DEBUG", "0") | |
| 11 | 31 | domain := shared.GetEnv("PASTES_DOMAIN", "pastes.sh") | |
| 12 | 32 | port := shared.GetEnv("PASTES_WEB_PORT", "3000") |
| ... | ... | @@ -14,7 +34,7 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 14 | 34 | protocol := shared.GetEnv("PASTES_PROTOCOL", "https") | |
| 15 | 35 | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 16 | 36 | ||
| 17 | - | return &shared.ConfigSite{ | |
| 37 | + | return &Config{ | |
| 18 | 38 | Debug: debug == "1", | |
| 19 | 39 | Domain: domain, | |
| 20 | 40 | Port: port, |
| ... | ... | @@ -25,3 +45,30 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 25 | 45 | MaxAssetSize: int64(3 * shared.MB), | |
| 26 | 46 | } | |
| 27 | 47 | } | |
| 48 | + | ||
| 49 | + | func (c *Config) StaticPath(fname string) string { | |
| 50 | + | return filepath.Join(staticDir, fname) | |
| 51 | + | } | |
| 52 | + | ||
| 53 | + | func (c *Config) SiteData() shared.SitePageData { | |
| 54 | + | return shared.SitePageData{ | |
| 55 | + | Domain: template.URL(c.Domain), | |
| 56 | + | HomeURL: template.URL("//" + c.Domain), | |
| 57 | + | } | |
| 58 | + | } | |
| 59 | + | ||
| 60 | + | func (c *Config) Static() router.Static { | |
| 61 | + | return router.Static{Dir: staticDir, Logger: c.Logger, Site: c.SiteData()} | |
| 62 | + | } | |
| 63 | + | ||
| 64 | + | func (c *Config) BlogURL(username string) string { | |
| 65 | + | return fmt.Sprintf("%s://%s.%s", c.Protocol, username, c.Domain) | |
| 66 | + | } | |
| 67 | + | ||
| 68 | + | func (c *Config) PostURL(username, slug string) string { | |
| 69 | + | return fmt.Sprintf("%s://%s.%s/%s", c.Protocol, username, c.Domain, url.PathEscape(slug)) | |
| 70 | + | } | |
| 71 | + | ||
| 72 | + | func (c *Config) RawPostURL(username, slug string) string { | |
| 73 | + | return fmt.Sprintf("%s://%s.%s/raw/%s", c.Protocol, username, c.Domain, url.PathEscape(slug)) | |
| 74 | + | } |
+2,
-4
| ... | ... | @@ -2,11 +2,9 @@ package pastes | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | 4 | "time" | |
| 5 | - | ||
| 6 | - | "github.com/picosh/pico/pkg/shared" | |
| 7 | 5 | ) | |
| 8 | 6 | ||
| 9 | - | func deleteExpiredPosts(cfg *shared.ConfigSite, dbpool DB) error { | |
| 7 | + | func deleteExpiredPosts(cfg *Config, dbpool DB) error { | |
| 10 | 8 | cfg.Logger.Info("checking for expired posts") | |
| 11 | 9 | posts, err := dbpool.FindExpiredPosts(cfg.Space) | |
| 12 | 10 | if err != nil { |
| ... | ... | @@ -27,7 +25,7 @@ func deleteExpiredPosts(cfg *shared.ConfigSite, dbpool DB) error { | |
| 27 | 25 | return nil | |
| 28 | 26 | } | |
| 29 | 27 | ||
| 30 | - | func CronDeleteExpiredPosts(cfg *shared.ConfigSite, dbpool DB) { | |
| 28 | + | func CronDeleteExpiredPosts(cfg *Config, dbpool DB) { | |
| 31 | 29 | for { | |
| 32 | 30 | err := deleteExpiredPosts(cfg, dbpool) | |
| 33 | 31 | if err != nil { |
+1,
-1
| ... | ... | @@ -24,7 +24,7 @@ func StartSshServer() { | |
| 24 | 24 | host := shared.GetEnv("PASTES_HOST", "0.0.0.0") | |
| 25 | 25 | port := shared.GetEnv("PASTES_SSH_PORT", "2222") | |
| 26 | 26 | promPort := shared.GetEnv("PASTES_PROM_PORT", "9222") | |
| 27 | - | cfg := NewConfigSite(appName) | |
| 27 | + | cfg := NewConfig(appName) | |
| 28 | 28 | logger := cfg.Logger | |
| 29 | 29 | ||
| 30 | 30 | ctx, cancel := context.WithCancel(context.Background()) |
+4,
-24
| ... | ... | @@ -19,29 +19,9 @@ import ( | |
| 19 | 19 | ||
| 20 | 20 | var DEFAULT_EXPIRES_AT = 90 | |
| 21 | 21 | ||
| 22 | - | func checkAccess(dbpool DB, userID string) error { | |
| 23 | - | ffPlus, plusErr := dbpool.FindFeature(userID, "plus") | |
| 24 | - | if plusErr == nil && ffPlus.IsValid() { | |
| 25 | - | return nil | |
| 26 | - | } | |
| 27 | - | ||
| 28 | - | ffPastes, pastesErr := dbpool.FindFeature(userID, "pastes") | |
| 29 | - | if pastesErr == nil { | |
| 30 | - | if ffPastes.IsValid() { | |
| 31 | - | return nil | |
| 32 | - | } | |
| 33 | - | return fmt.Errorf("ERROR: your pastes access has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 34 | - | } | |
| 35 | - | ||
| 36 | - | if plusErr == nil { | |
| 37 | - | return fmt.Errorf("ERROR: your pico+ has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 38 | - | } | |
| 39 | - | return fmt.Errorf("ERROR: uploading to pastes requires an invitation or pico+: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 40 | - | } | |
| 41 | - | ||
| 42 | 22 | // UploadHandler stores every file as a paste. | |
| 43 | 23 | type UploadHandler struct { | |
| 44 | - | Cfg *shared.ConfigSite | |
| 24 | + | Cfg *Config | |
| 45 | 25 | DB DB | |
| 46 | 26 | } | |
| 47 | 27 |
| ... | ... | @@ -51,7 +31,7 @@ var ( | |
| 51 | 31 | _ sendutils.FileRenamer = (*UploadHandler)(nil) | |
| 52 | 32 | ) | |
| 53 | 33 | ||
| 54 | - | func NewUploadHandler(cfg *shared.ConfigSite, dbpool DB) *UploadHandler { | |
| 34 | + | func NewUploadHandler(cfg *Config, dbpool DB) *UploadHandler { | |
| 55 | 35 | return &UploadHandler{Cfg: cfg, DB: dbpool} | |
| 56 | 36 | } | |
| 57 | 37 |
| ... | ... | @@ -71,7 +51,7 @@ func (h *UploadHandler) Validate(s *pssh.SSHServerConnSession) error { | |
| 71 | 51 | if err != nil { | |
| 72 | 52 | return err | |
| 73 | 53 | } | |
| 74 | - | if err := checkAccess(h.DB, user.ID); err != nil { | |
| 54 | + | if _, err := db.FindAccess(h.DB, user.ID, "pastes"); err != nil { | |
| 75 | 55 | return err | |
| 76 | 56 | } | |
| 77 | 57 | h.GetLogger(s).Info("attempting to upload files", "user", user.Name, "space", h.Cfg.Space) |
| ... | ... | @@ -132,7 +112,7 @@ func (h *UploadHandler) Write(s *pssh.SSHServerConnSession, entry *sendutils.Fil | |
| 132 | 112 | return "", err | |
| 133 | 113 | } | |
| 134 | 114 | logger.Info("saved paste", "new", cur == nil, "changed", changed) | |
| 135 | - | return h.Cfg.FullPostURL(shared.NewCreateURL(h.Cfg), user.Name, post.Slug), nil | |
| 115 | + | return shared.NewCreateURL(h.Cfg.Protocol, h.Cfg.Domain).FullPostURL(user.Name, post.Slug), nil | |
| 136 | 116 | } | |
| 137 | 117 | ||
| 138 | 118 | // Rename moves a paste to a new filename in place, keeping its settings. |
+2,
-3
| ... | ... | @@ -15,7 +15,6 @@ import ( | |
| 15 | 15 | "github.com/picosh/pico/pkg/db/stub" | |
| 16 | 16 | "github.com/picosh/pico/pkg/pssh" | |
| 17 | 17 | sendutils "github.com/picosh/pico/pkg/send/utils" | |
| 18 | - | "github.com/picosh/pico/pkg/shared" | |
| 19 | 18 | "golang.org/x/crypto/ssh" | |
| 20 | 19 | ) | |
| 21 | 20 |
| ... | ... | @@ -43,7 +42,7 @@ func (m *mockFeatureDB) setFeature(userID, name string, expiresAt time.Time) { | |
| 43 | 42 | } | |
| 44 | 43 | ||
| 45 | 44 | func TestUploadHandlerValidate(t *testing.T) { | |
| 46 | - | cfg := NewConfigSite("pastes-test") | |
| 45 | + | cfg := NewConfig("pastes-test") | |
| 47 | 46 | userID := "user-1" | |
| 48 | 47 | future := time.Now().Add(24 * time.Hour) | |
| 49 | 48 | past := time.Now().Add(-24 * time.Hour) |
| ... | ... | @@ -198,7 +197,7 @@ func TestWriteReadError(t *testing.T) { | |
| 198 | 197 | user := &db.User{ID: "user-1", Name: "tester"} | |
| 199 | 198 | pssh.SetUser(session, user) | |
| 200 | 199 | posts := stub.NewPostsDB(logger, user) | |
| 201 | - | handler := NewUploadHandler(&shared.ConfigSite{Space: "pastes", MaxAssetSize: 1024}, posts) | |
| 200 | + | handler := NewUploadHandler(&Config{Space: "pastes", MaxAssetSize: 1024}, posts) | |
| 202 | 201 | reader := io.MultiReader(strings.NewReader(tt.text), iotest.ErrReader(tt.err)) | |
| 203 | 202 | ||
| 204 | 203 | message, err := handler.Write(session, &sendutils.FileEntry{Filepath: "/test.txt", Reader: reader}) |
+1,
-1
| ... | ... | @@ -36,7 +36,7 @@ func TestPrivateProjectDeniesWebAccess(t *testing.T) { | |
| 36 | 36 | defer func() { | |
| 37 | 37 | _ = pubsub.Close() | |
| 38 | 38 | }() | |
| 39 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 39 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 40 | 40 | cfg.Domain = "pgs.test" | |
| 41 | 41 | router := NewWebRouter(cfg) | |
| 42 | 42 | router.ServeHTTP(responseRecorder, request) |
+3,
-3
| ... | ... | @@ -6,7 +6,7 @@ import ( | |
| 6 | 6 | "github.com/picosh/pico/pkg/shared/router" | |
| 7 | 7 | ) | |
| 8 | 8 | ||
| 9 | - | func handleAutoForm(w http.ResponseWriter, r *http.Request, cfg *PgsConfig) { | |
| 9 | + | func handleAutoForm(w http.ResponseWriter, r *http.Request, cfg *Config) { | |
| 10 | 10 | formName := r.PathValue("fname") | |
| 11 | 11 | if r.Method != http.MethodPost { | |
| 12 | 12 | http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| ... | ... | @@ -65,7 +65,7 @@ type FormData struct { | |
| 65 | 65 | Error string | |
| 66 | 66 | } | |
| 67 | 67 | ||
| 68 | - | func serveAutoFormSubmitted(w http.ResponseWriter, r *http.Request, cfg *PgsConfig) { | |
| 68 | + | func serveAutoFormSubmitted(w http.ResponseWriter, r *http.Request, cfg *Config) { | |
| 69 | 69 | errorMsg := r.URL.Query().Get("error") | |
| 70 | 70 | data := loginFormData{ | |
| 71 | 71 | Error: errorMsg, |
| ... | ... | @@ -73,7 +73,7 @@ func serveAutoFormSubmitted(w http.ResponseWriter, r *http.Request, cfg *PgsConf | |
| 73 | 73 | ||
| 74 | 74 | w.WriteHeader(http.StatusUnprocessableEntity) | |
| 75 | 75 | ||
| 76 | - | ts, err := renderTemplate(cfg, []string{cfg.StaticPath("html/auto_form.page.tmpl")}) | |
| 76 | + | ts, err := router.RenderTemplate(staticDir, []string{cfg.StaticPath("html/auto_form.page.tmpl")}) | |
| 77 | 77 | if err != nil { | |
| 78 | 78 | cfg.Logger.Error("could not render auto form template", "err", err.Error()) | |
| 79 | 79 | http.Error(w, "Server error", http.StatusInternalServerError) |
+1,
-1
| ... | ... | @@ -54,7 +54,7 @@ type Cmd struct { | |
| 54 | 54 | Write bool | |
| 55 | 55 | Width int | |
| 56 | 56 | Height int | |
| 57 | - | Cfg *PgsConfig | |
| 57 | + | Cfg *Config | |
| 58 | 58 | } | |
| 59 | 59 | ||
| 60 | 60 | func (c *Cmd) output(out string) { |
+2,
-2
| ... | ... | @@ -34,7 +34,7 @@ func TestCliPurges(t *testing.T) { | |
| 34 | 34 | if err != nil { | |
| 35 | 35 | t.Fatal(err) | |
| 36 | 36 | } | |
| 37 | - | cfg := NewPgsConfig(logger, dbpool, st, discardPubsub{}) | |
| 37 | + | cfg := NewConfig(logger, dbpool, st, discardPubsub{}) | |
| 38 | 38 | cmd := &Cmd{User: user, Session: &fakeCmdSession{}, Log: logger, Store: st, Dbpool: dbpool, Write: true, Cfg: cfg} | |
| 39 | 39 | ||
| 40 | 40 | tests := []struct { |
| ... | ... | @@ -88,7 +88,7 @@ func TestRmProjectAssetsRemovesDirs(t *testing.T) { | |
| 88 | 88 | t.Fatal(err) | |
| 89 | 89 | } | |
| 90 | 90 | ||
| 91 | - | cfg := NewPgsConfig(logger, dbpool, st, discardPubsub{}) | |
| 91 | + | cfg := NewConfig(logger, dbpool, st, discardPubsub{}) | |
| 92 | 92 | cmd := &Cmd{User: user, Session: &fakeCmdSession{}, Log: logger, Store: st, Dbpool: dbpool, Write: true, Cfg: cfg} | |
| 93 | 93 | if err := cmd.RmProjectAssets("test"); err != nil { | |
| 94 | 94 | t.Fatal(err) |
+19,
-6
| ... | ... | @@ -2,6 +2,7 @@ package pgs | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | 4 | "fmt" | |
| 5 | + | "html/template" | |
| 5 | 6 | "log/slog" | |
| 6 | 7 | "path/filepath" | |
| 7 | 8 | "strconv" |
| ... | ... | @@ -9,10 +10,11 @@ import ( | |
| 9 | 10 | ||
| 10 | 11 | pgsdb "github.com/picosh/pico/pkg/apps/pgs/db" | |
| 11 | 12 | "github.com/picosh/pico/pkg/shared" | |
| 13 | + | "github.com/picosh/pico/pkg/shared/router" | |
| 12 | 14 | "github.com/picosh/pico/pkg/storage" | |
| 13 | 15 | ) | |
| 14 | 16 | ||
| 15 | - | type PgsConfig struct { | |
| 17 | + | type Config struct { | |
| 16 | 18 | CacheTTL time.Duration | |
| 17 | 19 | CacheMaxItems int | |
| 18 | 20 | CacheMaxBodySize int64 |
| ... | ... | @@ -38,7 +40,7 @@ type PgsConfig struct { | |
| 38 | 40 | Pubsub PicoPubsub | |
| 39 | 41 | } | |
| 40 | 42 | ||
| 41 | - | func (c *PgsConfig) AssetURL(username, projectName, fpath string) string { | |
| 43 | + | func (c *Config) AssetURL(username, projectName, fpath string) string { | |
| 42 | 44 | if username == projectName { | |
| 43 | 45 | return fmt.Sprintf( | |
| 44 | 46 | "%s://%s.%s/%s", |
| ... | ... | @@ -59,8 +61,19 @@ func (c *PgsConfig) AssetURL(username, projectName, fpath string) string { | |
| 59 | 61 | ) | |
| 60 | 62 | } | |
| 61 | 63 | ||
| 62 | - | func (c *PgsConfig) StaticPath(fname string) string { | |
| 63 | - | return filepath.Join("pkg", "apps", "pgs", fname) | |
| 64 | + | // staticDir holds pgs's templates and public files. | |
| 65 | + | const staticDir = "pkg/apps/pgs" | |
| 66 | + | ||
| 67 | + | func (c *Config) StaticPath(fname string) string { | |
| 68 | + | return filepath.Join(staticDir, fname) | |
| 69 | + | } | |
| 70 | + | ||
| 71 | + | func (c *Config) Static() router.Static { | |
| 72 | + | return router.Static{ | |
| 73 | + | Dir: staticDir, | |
| 74 | + | Logger: c.Logger, | |
| 75 | + | Site: shared.SitePageData{Domain: template.URL(c.Domain), HomeURL: "/"}, | |
| 76 | + | } | |
| 64 | 77 | } | |
| 65 | 78 | ||
| 66 | 79 | var maxSize = uint64(50 * shared.MB) |
| ... | ... | @@ -73,7 +86,7 @@ var cacheMaxBodySize = int64(0) | |
| 73 | 86 | // Needs to be small for caching files like _headers and _redirects. | |
| 74 | 87 | var maxSpecialFileSize = int64(5 * shared.KB) | |
| 75 | 88 | ||
| 76 | - | func NewPgsConfig(logger *slog.Logger, dbpool pgsdb.PgsDB, st storage.StorageServe, pubsub PicoPubsub) *PgsConfig { | |
| 89 | + | func NewConfig(logger *slog.Logger, dbpool pgsdb.PgsDB, st storage.StorageServe, pubsub PicoPubsub) *Config { | |
| 77 | 90 | domain := shared.GetEnv("PGS_DOMAIN", "pgs.sh") | |
| 78 | 91 | port := shared.GetEnv("PGS_WEB_PORT", "3000") | |
| 79 | 92 | protocol := shared.GetEnv("PGS_PROTOCOL", "https") |
| ... | ... | @@ -94,7 +107,7 @@ func NewPgsConfig(logger *slog.Logger, dbpool pgsdb.PgsDB, st storage.StorageSer | |
| 94 | 107 | sshHost := shared.GetEnv("PGS_SSH_HOST", "0.0.0.0") | |
| 95 | 108 | sshPort := shared.GetEnv("PGS_SSH_PORT", "2222") | |
| 96 | 109 | ||
| 97 | - | cfg := PgsConfig{ | |
| 110 | + | cfg := Config{ | |
| 98 | 111 | CacheTTL: cacheTTL, | |
| 99 | 112 | CacheMaxItems: cacheMaxItems, | |
| 100 | 113 | CacheMaxBodySize: cacheMaxBody, |
+1,
-1
| ... | ... | @@ -11,7 +11,7 @@ import ( | |
| 11 | 11 | ||
| 12 | 12 | const binRetentionDays = 14 | |
| 13 | 13 | ||
| 14 | - | func BinCron(cfg *PgsConfig) { | |
| 14 | + | func BinCron(cfg *Config) { | |
| 15 | 15 | logger := cfg.Logger | |
| 16 | 16 | storage := cfg.Storage | |
| 17 | 17 | db := cfg.DB |
+7,
-33
| ... | ... | @@ -1,43 +1,17 @@ | |
| 1 | 1 | package pgs | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | - | "fmt" | |
| 5 | - | "strings" | |
| 6 | - | ||
| 7 | 4 | pgsdb "github.com/picosh/pico/pkg/apps/pgs/db" | |
| 8 | 5 | "github.com/picosh/pico/pkg/db" | |
| 9 | 6 | ) | |
| 10 | 7 | ||
| 11 | - | func setFeatureLimits(ff *db.FeatureFlag, cfg *PgsConfig) { | |
| 12 | - | ff.Data.StorageMax = ff.FindStorageMax(cfg.MaxSize) | |
| 13 | - | ff.Data.FileMax = ff.FindFileMax(cfg.MaxAssetSize) | |
| 14 | - | ff.Data.SpecialFileMax = ff.FindSpecialFileMax(cfg.MaxSpecialFileSize) | |
| 15 | - | } | |
| 16 | - | ||
| 17 | - | func findFeatureFlag(dbpool pgsdb.PgsDB, cfg *PgsConfig, userID string) (*db.FeatureFlag, error) { | |
| 18 | - | ff, err := dbpool.FindFeature(userID, "plus") | |
| 19 | - | if err == nil { | |
| 20 | - | if ff.IsValid() { | |
| 21 | - | setFeatureLimits(ff, cfg) | |
| 22 | - | return ff, nil | |
| 23 | - | } | |
| 24 | - | err = fmt.Errorf("ERROR: your pico+ has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 25 | - | } | |
| 26 | - | ||
| 27 | - | ffPgs, pgsErr := dbpool.FindFeature(userID, "pgs") | |
| 28 | - | if pgsErr == nil { | |
| 29 | - | if ffPgs.IsValid() { | |
| 30 | - | setFeatureLimits(ffPgs, cfg) | |
| 31 | - | return ffPgs, nil | |
| 32 | - | } | |
| 33 | - | pgsErr = fmt.Errorf("ERROR: your pgs access has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 34 | - | } | |
| 35 | - | ||
| 36 | - | if err != nil && strings.Contains(err.Error(), "expired") { | |
| 8 | + | // findFeatureFlag returns the flag that lets a user upload to pgs, with | |
| 9 | + | // pgs's limits filled in. | |
| 10 | + | func findFeatureFlag(dbpool pgsdb.PgsDB, cfg *Config, userID string) (*db.FeatureFlag, error) { | |
| 11 | + | ff, err := db.FindAccess(dbpool, userID, "pgs") | |
| 12 | + | if err != nil { | |
| 37 | 13 | return nil, err | |
| 38 | 14 | } | |
| 39 | - | if pgsErr != nil && strings.Contains(pgsErr.Error(), "expired") { | |
| 40 | - | return nil, pgsErr | |
| 41 | - | } | |
| 42 | - | return nil, fmt.Errorf("ERROR: uploading to pgs requires an invitation or pico+: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 15 | + | ff.SetLimits(cfg.MaxSize, cfg.MaxAssetSize, cfg.MaxSpecialFileSize) | |
| 16 | + | return ff, nil | |
| 43 | 17 | } |
+3,
-3
| ... | ... | @@ -26,7 +26,7 @@ type loginFormData struct { | |
| 26 | 26 | } | |
| 27 | 27 | ||
| 28 | 28 | // serveLoginFormWithConfig renders and serves the login form using templates. | |
| 29 | - | func serveLoginFormWithConfig(w http.ResponseWriter, r *http.Request, project *db.Project, cfg *PgsConfig, logger *slog.Logger) { | |
| 29 | + | func serveLoginFormWithConfig(w http.ResponseWriter, r *http.Request, project *db.Project, cfg *Config, logger *slog.Logger) { | |
| 30 | 30 | // Determine error message from query params | |
| 31 | 31 | errorMsg := "" | |
| 32 | 32 | if r.URL.Query().Get("error") == "invalid" { |
| ... | ... | @@ -40,7 +40,7 @@ func serveLoginFormWithConfig(w http.ResponseWriter, r *http.Request, project *d | |
| 40 | 40 | ||
| 41 | 41 | w.WriteHeader(http.StatusForbidden) | |
| 42 | 42 | ||
| 43 | - | ts, err := renderTemplate(cfg, []string{cfg.StaticPath("html/login.page.tmpl")}) | |
| 43 | + | ts, err := router.RenderTemplate(staticDir, []string{cfg.StaticPath("html/login.page.tmpl")}) | |
| 44 | 44 | if err != nil { | |
| 45 | 45 | logger.Error("could not render login template", "err", err.Error()) | |
| 46 | 46 | http.Error(w, "Server error", http.StatusInternalServerError) |
| ... | ... | @@ -55,7 +55,7 @@ func serveLoginFormWithConfig(w http.ResponseWriter, r *http.Request, project *d | |
| 55 | 55 | } | |
| 56 | 56 | ||
| 57 | 57 | // handleLogin processes the login form submission. | |
| 58 | - | func handleLogin(w http.ResponseWriter, r *http.Request, cfg *PgsConfig) { | |
| 58 | + | func handleLogin(w http.ResponseWriter, r *http.Request, cfg *Config) { | |
| 59 | 59 | if r.Method != http.MethodPost { | |
| 60 | 60 | http.Error(w, "method not allowed", http.StatusMethodNotAllowed) | |
| 61 | 61 | return |
+1,
-1
| ... | ... | @@ -57,7 +57,7 @@ func newRsyncEnv(t *testing.T, st storage.StorageServe) *rsyncEnv { | |
| 57 | 57 | bucket := storagetest.Bucket(t, st, shared.GetAssetBucketName(dbpool.Users[0].ID)) | |
| 58 | 58 | ||
| 59 | 59 | t.Setenv("PGS_SSH_PORT", "0") | |
| 60 | - | cfg := NewPgsConfig(logger, dbpool, st, discardPubsub{}) | |
| 60 | + | cfg := NewConfig(logger, dbpool, st, discardPubsub{}) | |
| 61 | 61 | cfg.Domain = "pgs.sh" | |
| 62 | 62 | cfg.WebProtocol = "https" | |
| 63 | 63 | done := make(chan error) |
+2,
-2
| ... | ... | @@ -17,7 +17,7 @@ import ( | |
| 17 | 17 | "github.com/picosh/pico/pkg/tunkit" | |
| 18 | 18 | ) | |
| 19 | 19 | ||
| 20 | - | func createSshServer(cfg *PgsConfig, ctx context.Context, cacheClearingQueue chan string) (*pssh.SSHServer, error) { | |
| 20 | + | func createSshServer(cfg *Config, ctx context.Context, cacheClearingQueue chan string) (*pssh.SSHServer, error) { | |
| 21 | 21 | host := shared.GetEnv("PGS_HOST", "0.0.0.0") | |
| 22 | 22 | port := shared.GetEnv("PGS_SSH_PORT", "2222") | |
| 23 | 23 | promPort := shared.GetEnv("PGS_PROM_PORT", "9222") |
| ... | ... | @@ -67,7 +67,7 @@ func createSshServer(cfg *PgsConfig, ctx context.Context, cacheClearingQueue cha | |
| 67 | 67 | return server, err | |
| 68 | 68 | } | |
| 69 | 69 | ||
| 70 | - | func StartSshServer(cfg *PgsConfig, killCh chan error) { | |
| 70 | + | func StartSshServer(cfg *Config, killCh chan error) { | |
| 71 | 71 | ctx, cancel := context.WithCancel(context.Background()) | |
| 72 | 72 | defer cancel() | |
| 73 | 73 |
+5,
-5
| ... | ... | @@ -24,7 +24,7 @@ import ( | |
| 24 | 24 | "golang.org/x/crypto/ssh" | |
| 25 | 25 | ) | |
| 26 | 26 | ||
| 27 | - | func StartSshServerForTesting(cfg *PgsConfig, killCh chan error, readyCh chan *pssh.SSHServer) { | |
| 27 | + | func StartSshServerForTesting(cfg *Config, killCh chan error, readyCh chan *pssh.SSHServer) { | |
| 28 | 28 | ctx, cancel := context.WithCancel(context.Background()) | |
| 29 | 29 | defer func() { | |
| 30 | 30 | // Cancel is deferred to avoid being called in error path |
| ... | ... | @@ -87,7 +87,7 @@ func TestSshServerSftp(t *testing.T) { | |
| 87 | 87 | // Use dynamic port for tests to avoid port conflicts | |
| 88 | 88 | _ = os.Setenv("PGS_SSH_PORT", "0") | |
| 89 | 89 | ||
| 90 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 90 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 91 | 91 | done := make(chan error) | |
| 92 | 92 | readyCh := make(chan *pssh.SSHServer) | |
| 93 | 93 | prometheus.DefaultRegisterer = prometheus.NewRegistry() |
| ... | ... | @@ -190,7 +190,7 @@ func TestSshServerRsync(t *testing.T) { | |
| 190 | 190 | // Use dynamic port for tests to avoid port conflicts | |
| 191 | 191 | _ = os.Setenv("PGS_SSH_PORT", "0") | |
| 192 | 192 | ||
| 193 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 193 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 194 | 194 | done := make(chan error) | |
| 195 | 195 | readyCh := make(chan *pssh.SSHServer) | |
| 196 | 196 | prometheus.DefaultRegisterer = prometheus.NewRegistry() |
| ... | ... | @@ -442,7 +442,7 @@ func GenerateUser() UserSSH { | |
| 442 | 442 | } | |
| 443 | 443 | } | |
| 444 | 444 | ||
| 445 | - | func WriteFileWithSftp(cfg *PgsConfig, conn *ssh.Client) (*os.FileInfo, error) { | |
| 445 | + | func WriteFileWithSftp(cfg *Config, conn *ssh.Client) (*os.FileInfo, error) { | |
| 446 | 446 | // open an SFTP session over an existing ssh connection. | |
| 447 | 447 | client, err := sftp.NewClient(conn) | |
| 448 | 448 | if err != nil { |
| ... | ... | @@ -475,7 +475,7 @@ func WriteFileWithSftp(cfg *PgsConfig, conn *ssh.Client) (*os.FileInfo, error) { | |
| 475 | 475 | return &fi, nil | |
| 476 | 476 | } | |
| 477 | 477 | ||
| 478 | - | func WriteFilesMultProjectsWithSftp(cfg *PgsConfig, conn *ssh.Client) (*os.FileInfo, error) { | |
| 478 | + | func WriteFilesMultProjectsWithSftp(cfg *Config, conn *ssh.Client) (*os.FileInfo, error) { | |
| 479 | 479 | // open an SFTP session over an existing ssh connection. | |
| 480 | 480 | client, err := sftp.NewClient(conn) | |
| 481 | 481 | if err != nil { |
+2,
-4
| ... | ... | @@ -1,7 +1,6 @@ | |
| 1 | 1 | package pgs | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | - | "context" | |
| 5 | 4 | "net/http" | |
| 6 | 5 | "strings" | |
| 7 | 6 | "time" |
| ... | ... | @@ -29,8 +28,7 @@ func tunnelPerm(proj *db.Project) bool { | |
| 29 | 28 | } | |
| 30 | 29 | ||
| 31 | 30 | func (web *TunnelWebRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| 32 | - | ctx := r.Context() | |
| 33 | - | ctx = context.WithValue(ctx, router.CtxSubdomainKey{}, web.subdomain) | |
| 31 | + | ctx := router.WithSubdomain(r.Context(), web.subdomain) | |
| 34 | 32 | web.UserRouter.ServeHTTP(w, r.WithContext(ctx)) | |
| 35 | 33 | } | |
| 36 | 34 |
| ... | ... | @@ -45,7 +43,7 @@ func getInfoFromUser(user string) (string, string) { | |
| 45 | 43 | return "", user | |
| 46 | 44 | } | |
| 47 | 45 | ||
| 48 | - | func CreateHttpHandler(cfg *PgsConfig) CtxHttpBridge { | |
| 46 | + | func CreateHttpHandler(cfg *Config) CtxHttpBridge { | |
| 49 | 47 | return func(ctx *pssh.SSHServerConnSession) http.Handler { | |
| 50 | 48 | logger := cfg.Logger | |
| 51 | 49 | asUser, subdomain := getInfoFromUser(ctx.User()) |
+3,
-3
| ... | ... | @@ -65,11 +65,11 @@ type FileData struct { | |
| 65 | 65 | } | |
| 66 | 66 | ||
| 67 | 67 | type UploadAssetHandler struct { | |
| 68 | - | Cfg *PgsConfig | |
| 68 | + | Cfg *Config | |
| 69 | 69 | CacheClearingQueue chan string | |
| 70 | 70 | } | |
| 71 | 71 | ||
| 72 | - | func NewUploadAssetHandler(cfg *PgsConfig, ch chan string, ctx context.Context) *UploadAssetHandler { | |
| 72 | + | func NewUploadAssetHandler(cfg *Config, ch chan string, ctx context.Context) *UploadAssetHandler { | |
| 73 | 73 | go runCacheQueue(cfg, ctx) | |
| 74 | 74 | return &UploadAssetHandler{ | |
| 75 | 75 | Cfg: cfg, |
| ... | ... | @@ -513,7 +513,7 @@ func (h *UploadAssetHandler) writeAsset(s *pssh.SSHServerConnSession, reader io. | |
| 513 | 513 | // One message arrives per file that is written/deleted during uploads. | |
| 514 | 514 | // Repeated messages for the same site are grouped so that we only flush once | |
| 515 | 515 | // per site per 5 seconds. | |
| 516 | - | func runCacheQueue(cfg *PgsConfig, ctx context.Context) { | |
| 516 | + | func runCacheQueue(cfg *Config, ctx context.Context) { | |
| 517 | 517 | var pendingFlushes sync.Map | |
| 518 | 518 | tick := time.NewTicker(5 * time.Second) | |
| 519 | 519 | defer tick.Stop() |
+5,
-5
| ... | ... | @@ -59,7 +59,7 @@ func TestRsyncDeleteDirectory(t *testing.T) { | |
| 59 | 59 | _ = os.Setenv("PGS_SSH_PORT", "0") | |
| 60 | 60 | _ = os.Setenv("PGS_PROM_PORT", "0") | |
| 61 | 61 | ||
| 62 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 62 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 63 | 63 | done := make(chan error) | |
| 64 | 64 | readyCh := make(chan *pssh.SSHServer) | |
| 65 | 65 | prometheus.DefaultRegisterer = prometheus.NewRegistry() |
| ... | ... | @@ -250,7 +250,7 @@ func TestRsyncDeleteNestedEmptyDirectories(t *testing.T) { | |
| 250 | 250 | _ = os.Setenv("PGS_SSH_PORT", "0") | |
| 251 | 251 | _ = os.Setenv("PGS_PROM_PORT", "0") | |
| 252 | 252 | ||
| 253 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 253 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 254 | 254 | done := make(chan error) | |
| 255 | 255 | readyCh := make(chan *pssh.SSHServer) | |
| 256 | 256 | prometheus.DefaultRegisterer = prometheus.NewRegistry() |
| ... | ... | @@ -389,7 +389,7 @@ func setupPgsTestServer(t *testing.T, dbpool *pgsdb.MemoryDB) (string, func()) { | |
| 389 | 389 | _ = os.Setenv("PGS_SSH_PORT", "0") | |
| 390 | 390 | _ = os.Setenv("PGS_PROM_PORT", "0") | |
| 391 | 391 | ||
| 392 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 392 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 393 | 393 | done := make(chan error) | |
| 394 | 394 | readyCh := make(chan *pssh.SSHServer) | |
| 395 | 395 | prometheus.DefaultRegisterer = prometheus.NewRegistry() |
| ... | ... | @@ -550,7 +550,7 @@ func TestNoPlusFlagBlocksUpload(t *testing.T) { | |
| 550 | 550 | ||
| 551 | 551 | func TestFindFeatureFlag(t *testing.T) { | |
| 552 | 552 | logger := slog.Default() | |
| 553 | - | cfg := &PgsConfig{ | |
| 553 | + | cfg := &Config{ | |
| 554 | 554 | MaxSize: uint64(100 * shared.MB), | |
| 555 | 555 | MaxAssetSize: int64(10 * shared.MB), | |
| 556 | 556 | MaxSpecialFileSize: int64(5 * shared.KB), |
| ... | ... | @@ -723,7 +723,7 @@ func TestSftpDirectories(t *testing.T) { | |
| 723 | 723 | t.Fatal(err) | |
| 724 | 724 | } | |
| 725 | 725 | _ = os.Setenv("PGS_SSH_PORT", "0") | |
| 726 | - | cfg := NewPgsConfig(logger, dbpool, st, discardPubsub{}) | |
| 726 | + | cfg := NewConfig(logger, dbpool, st, discardPubsub{}) | |
| 727 | 727 | done := make(chan error) | |
| 728 | 728 | defer close(done) | |
| 729 | 729 | readyCh := make(chan *pssh.SSHServer) |
+13,
-101
| ... | ... | @@ -5,10 +5,8 @@ import ( | |
| 5 | 5 | "context" | |
| 6 | 6 | "errors" | |
| 7 | 7 | "fmt" | |
| 8 | - | "html/template" | |
| 9 | 8 | "log/slog" | |
| 10 | 9 | "net/http" | |
| 11 | - | "os" | |
| 12 | 10 | "path/filepath" | |
| 13 | 11 | "regexp" | |
| 14 | 12 | "strings" |
| ... | ... | @@ -109,7 +107,7 @@ func (p *PromCacheMetrics) AddUpstreamRequest() { | |
| 109 | 107 | p.UpstreamReq.Add(1) | |
| 110 | 108 | } | |
| 111 | 109 | ||
| 112 | - | func NewPgsHttpCache(cfg *PgsConfig, upstream http.Handler) (*httpcache.HttpCache, *SiteCache) { | |
| 110 | + | func NewPgsHttpCache(cfg *Config, upstream http.Handler) (*httpcache.HttpCache, *SiteCache) { | |
| 113 | 111 | ttl := cfg.CacheTTL | |
| 114 | 112 | metrics := NewPromCacheMetrics(cfg.Logger, prometheus.DefaultRegisterer) | |
| 115 | 113 | cache := NewSiteCache(cfg.CacheMaxItems, ttl, metrics.EvictCacheItem) |
| ... | ... | @@ -135,7 +133,7 @@ func NewPgsHttpCache(cfg *PgsConfig, upstream http.Handler) (*httpcache.HttpCach | |
| 135 | 133 | return httpCache, cache | |
| 136 | 134 | } | |
| 137 | 135 | ||
| 138 | - | func StartApiServer(cfg *PgsConfig) { | |
| 136 | + | func StartApiServer(cfg *Config) { | |
| 139 | 137 | ctx := context.Background() | |
| 140 | 138 | ||
| 141 | 139 | router := NewWebRouter(cfg) |
| ... | ... | @@ -158,7 +156,7 @@ func StartApiServer(cfg *PgsConfig) { | |
| 158 | 156 | type HasPerm = func(proj *db.Project) bool | |
| 159 | 157 | ||
| 160 | 158 | type WebRouter struct { | |
| 161 | - | Cfg *PgsConfig | |
| 159 | + | Cfg *Config | |
| 162 | 160 | RootRouter *http.ServeMux | |
| 163 | 161 | UserRouter *http.ServeMux | |
| 164 | 162 | RedirectsCache *expirable.LRU[string, []*RedirectRule] |
| ... | ... | @@ -178,11 +176,11 @@ func (s *siteInfo) hasPicoPlus() bool { | |
| 178 | 176 | return s.plus != nil && s.plus.ExpiresAt.After(time.Now()) | |
| 179 | 177 | } | |
| 180 | 178 | ||
| 181 | - | func NewWebRouter(cfg *PgsConfig) *WebRouter { | |
| 179 | + | func NewWebRouter(cfg *Config) *WebRouter { | |
| 182 | 180 | return newWebRouter(cfg) | |
| 183 | 181 | } | |
| 184 | 182 | ||
| 185 | - | func newWebRouter(cfg *PgsConfig) *WebRouter { | |
| 183 | + | func newWebRouter(cfg *Config) *WebRouter { | |
| 186 | 184 | router := &WebRouter{ | |
| 187 | 185 | Cfg: cfg, | |
| 188 | 186 | RedirectsCache: expirable.NewLRU[string, []*RedirectRule](2048, nil, shared.CacheTimeout), |
| ... | ... | @@ -194,23 +192,12 @@ func newWebRouter(cfg *PgsConfig) *WebRouter { | |
| 194 | 192 | } | |
| 195 | 193 | ||
| 196 | 194 | func (web *WebRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| 197 | - | subdomain := router.GetSubdomainFromRequest(r, web.Cfg.Domain, web.Cfg.TxtPrefix) | |
| 198 | 195 | if web.RootRouter == nil || web.UserRouter == nil { | |
| 199 | 196 | web.Cfg.Logger.Error("routers not initialized") | |
| 200 | 197 | http.Error(w, "routers not initialized", http.StatusInternalServerError) | |
| 201 | 198 | return | |
| 202 | 199 | } | |
| 203 | - | ||
| 204 | - | var mux *http.ServeMux | |
| 205 | - | if subdomain == "" { | |
| 206 | - | mux = web.RootRouter | |
| 207 | - | } else { | |
| 208 | - | mux = web.UserRouter | |
| 209 | - | } | |
| 210 | - | ||
| 211 | - | ctx := r.Context() | |
| 212 | - | ctx = context.WithValue(ctx, router.CtxSubdomainKey{}, subdomain) | |
| 213 | - | mux.ServeHTTP(w, r.WithContext(ctx)) | |
| 200 | + | router.NewHostRouter(web.Cfg.Domain, web.Cfg.TxtPrefix, web.RootRouter, web.UserRouter).ServeHTTP(w, r) | |
| 214 | 201 | } | |
| 215 | 202 | ||
| 216 | 203 | // clearSiteCache drops what is cached about a site: its database records and |
| ... | ... | @@ -272,14 +259,15 @@ func (web *WebRouter) initRouters() { | |
| 272 | 259 | w.Header().Set("cache-control", "no-store") | |
| 273 | 260 | promhttp.Handler().ServeHTTP(w, r) | |
| 274 | 261 | }) | |
| 275 | - | rootRouter.Handle("GET /main.css", web.serveFile("main.css", "text/css")) | |
| 276 | - | rootRouter.Handle("GET /favicon-16x16.png", web.serveFile("favicon-16x16.png", "image/png")) | |
| 277 | - | rootRouter.Handle("GET /favicon.ico", web.serveFile("favicon.ico", "image/x-icon")) | |
| 278 | - | rootRouter.Handle("GET /robots.txt", web.serveFile("robots.txt", "text/plain")) | |
| 262 | + | files := web.Cfg.Static() | |
| 263 | + | rootRouter.Handle("GET /main.css", files.File("main.css", "text/css")) | |
| 264 | + | rootRouter.Handle("GET /favicon-16x16.png", files.File("favicon-16x16.png", "image/png")) | |
| 265 | + | rootRouter.Handle("GET /favicon.ico", files.File("favicon.ico", "image/x-icon")) | |
| 266 | + | rootRouter.Handle("GET /robots.txt", files.File("robots.txt", "text/plain")) | |
| 279 | 267 | ||
| 280 | 268 | rootRouter.Handle("GET /rss/updated", web.createRssHandler("updated_at")) | |
| 281 | 269 | rootRouter.Handle("GET /rss", web.createRssHandler("created_at")) | |
| 282 | - | rootRouter.Handle("GET /{$}", web.createPageHandler("html/marketing.page.tmpl")) | |
| 270 | + | rootRouter.Handle("GET /{$}", files.Page("html/marketing.page.tmpl")) | |
| 283 | 271 | web.RootRouter = rootRouter | |
| 284 | 272 | ||
| 285 | 273 | // subdomain or custom domains |
| ... | ... | @@ -291,82 +279,6 @@ func (web *WebRouter) initRouters() { | |
| 291 | 279 | web.UserRouter = userRouter | |
| 292 | 280 | } | |
| 293 | 281 | ||
| 294 | - | func (web *WebRouter) serveFile(file string, contentType string) http.HandlerFunc { | |
| 295 | - | return func(w http.ResponseWriter, r *http.Request) { | |
| 296 | - | logger := web.Cfg.Logger | |
| 297 | - | cfg := web.Cfg | |
| 298 | - | ||
| 299 | - | contents, err := os.ReadFile(cfg.StaticPath(fmt.Sprintf("public/%s", file))) | |
| 300 | - | if err != nil { | |
| 301 | - | logger.Error( | |
| 302 | - | "could not read file", | |
| 303 | - | "fname", file, | |
| 304 | - | "err", err.Error(), | |
| 305 | - | ) | |
| 306 | - | http.Error(w, "file not found", 404) | |
| 307 | - | } | |
| 308 | - | ||
| 309 | - | w.Header().Add("Content-Type", contentType) | |
| 310 | - | ||
| 311 | - | _, err = w.Write(contents) | |
| 312 | - | if err != nil { | |
| 313 | - | logger.Error( | |
| 314 | - | "could not write http response", | |
| 315 | - | "file", file, | |
| 316 | - | "err", err.Error(), | |
| 317 | - | ) | |
| 318 | - | } | |
| 319 | - | } | |
| 320 | - | } | |
| 321 | - | ||
| 322 | - | func renderTemplate(cfg *PgsConfig, templates []string) (*template.Template, error) { | |
| 323 | - | files := make([]string, len(templates)) | |
| 324 | - | copy(files, templates) | |
| 325 | - | files = append( | |
| 326 | - | files, | |
| 327 | - | cfg.StaticPath("html/footer.partial.tmpl"), | |
| 328 | - | cfg.StaticPath("html/marketing-footer.partial.tmpl"), | |
| 329 | - | cfg.StaticPath("html/base.layout.tmpl"), | |
| 330 | - | ) | |
| 331 | - | ||
| 332 | - | ts, err := template.New("base").ParseFiles(files...) | |
| 333 | - | if err != nil { | |
| 334 | - | return nil, err | |
| 335 | - | } | |
| 336 | - | return ts, nil | |
| 337 | - | } | |
| 338 | - | ||
| 339 | - | func (web *WebRouter) createPageHandler(fname string) http.HandlerFunc { | |
| 340 | - | return func(w http.ResponseWriter, r *http.Request) { | |
| 341 | - | logger := web.Cfg.Logger | |
| 342 | - | cfg := web.Cfg | |
| 343 | - | ts, err := renderTemplate(cfg, []string{cfg.StaticPath(fname)}) | |
| 344 | - | ||
| 345 | - | if err != nil { | |
| 346 | - | logger.Error( | |
| 347 | - | "could not render template", | |
| 348 | - | "fname", fname, | |
| 349 | - | "err", err.Error(), | |
| 350 | - | ) | |
| 351 | - | http.Error(w, err.Error(), http.StatusInternalServerError) | |
| 352 | - | return | |
| 353 | - | } | |
| 354 | - | ||
| 355 | - | data := shared.PageData{ | |
| 356 | - | Site: shared.SitePageData{Domain: template.URL(cfg.Domain), HomeURL: "/"}, | |
| 357 | - | } | |
| 358 | - | err = ts.Execute(w, data) | |
| 359 | - | if err != nil { | |
| 360 | - | logger.Error( | |
| 361 | - | "could not execute template", | |
| 362 | - | "fname", fname, | |
| 363 | - | "err", err.Error(), | |
| 364 | - | ) | |
| 365 | - | http.Error(w, err.Error(), http.StatusInternalServerError) | |
| 366 | - | } | |
| 367 | - | } | |
| 368 | - | } | |
| 369 | - | ||
| 370 | 282 | func (web *WebRouter) checkHandler(w http.ResponseWriter, r *http.Request) { | |
| 371 | 283 | dbpool := web.Cfg.DB | |
| 372 | 284 | cfg := web.Cfg |
| ... | ... | @@ -430,7 +342,7 @@ func (web *WebRouter) checkHandler(w http.ResponseWriter, r *http.Request) { | |
| 430 | 342 | // CacheMgmt applies the purges published on the cache-drain pipe. onPurge, | |
| 431 | 343 | // when set, clears whatever else is cached about the site; it runs first so | |
| 432 | 344 | // the http cache isn't refilled from stale records. | |
| 433 | - | func CacheMgmt(ctx context.Context, cfg *PgsConfig, cache *SiteCache, onPurge func(site string)) { | |
| 345 | + | func CacheMgmt(ctx context.Context, cfg *Config, cache *SiteCache, onPurge func(site string)) { | |
| 434 | 346 | cfg.Logger.Info("cache mgmt initiated") | |
| 435 | 347 | for { | |
| 436 | 348 | scanner := bufio.NewScanner(cfg.Pubsub) |
+2,
-2
| ... | ... | @@ -105,13 +105,13 @@ func CreateSubCacheDrain(ctx context.Context, logger *slog.Logger) *pipe.Reconne | |
| 105 | 105 | // cached assets for a given subdomain are grouped under a single key (which is | |
| 106 | 106 | // separate from the "GET-https-example.com-/path" key used for serving files | |
| 107 | 107 | // from the cache). | |
| 108 | - | func purgeCache(cfg *PgsConfig, writer io.Writer, surrogate string) error { | |
| 108 | + | func purgeCache(cfg *Config, writer io.Writer, surrogate string) error { | |
| 109 | 109 | cfg.Logger.Info("purging cache", "surrogate", surrogate) | |
| 110 | 110 | _, err := writer.Write([]byte(surrogate + "\n")) | |
| 111 | 111 | return err | |
| 112 | 112 | } | |
| 113 | 113 | ||
| 114 | - | func purgeAllCache(cfg *PgsConfig, writer io.Writer) error { | |
| 114 | + | func purgeAllCache(cfg *Config, writer io.Writer) error { | |
| 115 | 115 | return purgeCache(cfg, writer, "*") | |
| 116 | 116 | } | |
| 117 | 117 |
+6,
-6
| ... | ... | @@ -461,7 +461,7 @@ func TestApiBasic(t *testing.T) { | |
| 461 | 461 | defer func() { | |
| 462 | 462 | _ = pubsub.Close() | |
| 463 | 463 | }() | |
| 464 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 464 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 465 | 465 | cfg.Domain = "pgs.test" | |
| 466 | 466 | router := NewWebRouter(cfg) | |
| 467 | 467 | router.ServeHTTP(responseRecorder, request) |
| ... | ... | @@ -543,7 +543,7 @@ func TestApiHttpPassNotCached(t *testing.T) { | |
| 543 | 543 | defer func() { | |
| 544 | 544 | _ = pubsub.Close() | |
| 545 | 545 | }() | |
| 546 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 546 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 547 | 547 | cfg.Domain = "pgs.test" | |
| 548 | 548 | router := NewWebRouter(cfg) | |
| 549 | 549 |
| ... | ... | @@ -662,7 +662,7 @@ func TestDirectoryListing(t *testing.T) { | |
| 662 | 662 | defer func() { | |
| 663 | 663 | _ = pubsub.Close() | |
| 664 | 664 | }() | |
| 665 | - | cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 665 | + | cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 666 | 666 | cfg.Domain = "pgs.test" | |
| 667 | 667 | router := NewWebRouter(cfg) | |
| 668 | 668 | router.ServeHTTP(responseRecorder, request) |
| ... | ... | @@ -754,7 +754,7 @@ func TestDirectoryListing(t *testing.T) { | |
| 754 | 754 | // defer func() { | |
| 755 | 755 | // _ = pubsub.Close() | |
| 756 | 756 | // }() | |
| 757 | - | // cfg := NewPgsConfig(logger, dbpool, st, pubsub) | |
| 757 | + | // cfg := NewConfig(logger, dbpool, st, pubsub) | |
| 758 | 758 | // cfg.Domain = "pgs.test" | |
| 759 | 759 | // router := NewWebRouter(cfg) | |
| 760 | 760 | // router.ServeHTTP(responseRecorder, request) |
| ... | ... | @@ -795,7 +795,7 @@ func TestRulesCacheClearedByUploadPurge(t *testing.T) { | |
| 795 | 795 | if err != nil { | |
| 796 | 796 | t.Fatal(err) | |
| 797 | 797 | } | |
| 798 | - | cfg := NewPgsConfig(logger, dbpool, st, discardPubsub{}) | |
| 798 | + | cfg := NewConfig(logger, dbpool, st, discardPubsub{}) | |
| 799 | 799 | cfg.Domain = "pgs.test" | |
| 800 | 800 | router := newWebRouter(cfg) | |
| 801 | 801 |
| ... | ... | @@ -853,7 +853,7 @@ func TestSiteCache(t *testing.T) { | |
| 853 | 853 | if err != nil { | |
| 854 | 854 | t.Fatal(err) | |
| 855 | 855 | } | |
| 856 | - | cfg := NewPgsConfig(logger, dbpool, st, discardPubsub{}) | |
| 856 | + | cfg := NewConfig(logger, dbpool, st, discardPubsub{}) | |
| 857 | 857 | cfg.Domain = "pgs.test" | |
| 858 | 858 | router := newWebRouter(cfg) | |
| 859 | 859 |
+10,
-2
| ... | ... | @@ -1,17 +1,25 @@ | |
| 1 | 1 | package pico | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | + | "log/slog" | |
| 4 | 5 | "strings" | |
| 5 | 6 | ||
| 6 | 7 | "github.com/picosh/pico/pkg/shared" | |
| 7 | 8 | ) | |
| 8 | 9 | ||
| 9 | - | func NewConfigSite(service string) *shared.ConfigSite { | |
| 10 | + | type Config struct { | |
| 11 | + | DbURL string | |
| 12 | + | Space string | |
| 13 | + | TunsSecret string | |
| 14 | + | Logger *slog.Logger | |
| 15 | + | } | |
| 16 | + | ||
| 17 | + | func NewConfig(service string) *Config { | |
| 10 | 18 | dbURL := shared.GetEnv("DATABASE_URL", "") | |
| 11 | 19 | tuns := shared.GetEnv("TUNS_CONSOLE_SECRET", "") | |
| 12 | 20 | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 13 | 21 | ||
| 14 | - | return &shared.ConfigSite{ | |
| 22 | + | return &Config{ | |
| 15 | 23 | DbURL: dbURL, | |
| 16 | 24 | Space: "pico", | |
| 17 | 25 | Logger: shared.CreateLogger(service, withPipe), |
+2,
-2
| ... | ... | @@ -20,10 +20,10 @@ import ( | |
| 20 | 20 | ||
| 21 | 21 | type UploadHandler struct { | |
| 22 | 22 | DBPool db.DB | |
| 23 | - | Cfg *shared.ConfigSite | |
| 23 | + | Cfg *Config | |
| 24 | 24 | } | |
| 25 | 25 | ||
| 26 | - | func NewUploadHandler(dbpool db.DB, cfg *shared.ConfigSite) *UploadHandler { | |
| 26 | + | func NewUploadHandler(dbpool db.DB, cfg *Config) *UploadHandler { | |
| 27 | 27 | return &UploadHandler{ | |
| 28 | 28 | DBPool: dbpool, | |
| 29 | 29 | Cfg: cfg, |
+6,
-6
| ... | ... | @@ -43,7 +43,7 @@ func StartSshServer() { | |
| 43 | 43 | host := shared.GetEnv("PICO_HOST", "0.0.0.0") | |
| 44 | 44 | port := shared.GetEnv("PICO_SSH_PORT", "2222") | |
| 45 | 45 | promPort := shared.GetEnv("PICO_PROM_PORT", "9222") | |
| 46 | - | cfg := NewConfigSite(appName) | |
| 46 | + | cfg := NewConfig(appName) | |
| 47 | 47 | logger := cfg.Logger | |
| 48 | 48 | ||
| 49 | 49 | ctx, cancel := context.WithCancel(context.Background()) |
| ... | ... | @@ -99,11 +99,11 @@ func StartSshServer() { | |
| 99 | 99 | func(next pssh.SSHServerHandler) pssh.SSHServerHandler { | |
| 100 | 100 | return func(sesh *pssh.SSHServerConnSession) error { | |
| 101 | 101 | shrd := &tui.SharedModel{ | |
| 102 | - | Session: sesh, | |
| 103 | - | Cfg: cfg, | |
| 104 | - | Dbpool: handler.DBPool, | |
| 105 | - | PgsDB: pgsDB, | |
| 106 | - | Logger: pssh.GetLogger(sesh), | |
| 102 | + | Session: sesh, | |
| 103 | + | TunsSecret: cfg.TunsSecret, | |
| 104 | + | Dbpool: handler.DBPool, | |
| 105 | + | PgsDB: pgsDB, | |
| 106 | + | Logger: pssh.GetLogger(sesh), | |
| 107 | 107 | } | |
| 108 | 108 | return pssh.PtyMdw(createTui(shrd), 200*time.Millisecond)(next)(sesh) | |
| 109 | 109 | } |
+12,
-11
| ... | ... | @@ -397,7 +397,7 @@ func (web *webRouter) handlePipe() http.HandlerFunc { | |
| 397 | 397 | } | |
| 398 | 398 | } | |
| 399 | 399 | ||
| 400 | - | func rssHandler(cfg *shared.ConfigSite, dbpool DB) http.HandlerFunc { | |
| 400 | + | func rssHandler(cfg *Config, dbpool DB) http.HandlerFunc { | |
| 401 | 401 | return func(w http.ResponseWriter, r *http.Request) { | |
| 402 | 402 | apiToken, _ := url.PathUnescape(r.PathValue("token")) | |
| 403 | 403 | user, err := dbpool.FindUserByToken(apiToken) |
| ... | ... | @@ -435,17 +435,18 @@ func rssHandler(cfg *shared.ConfigSite, dbpool DB) http.HandlerFunc { | |
| 435 | 435 | } | |
| 436 | 436 | ||
| 437 | 437 | type webRouter struct { | |
| 438 | - | cfg *shared.ConfigSite | |
| 438 | + | cfg *Config | |
| 439 | 439 | db DB | |
| 440 | 440 | } | |
| 441 | 441 | ||
| 442 | 442 | func (web *webRouter) static(mux *http.ServeMux) { | |
| 443 | 443 | cfg := web.cfg | |
| 444 | - | mux.HandleFunc("GET /favicon-16x16.png", router.ServeFile(cfg, "favicon-16x16.png", "image/png")) | |
| 445 | - | mux.HandleFunc("GET /apple-touch-icon.png", router.ServeFile(cfg, "apple-touch-icon.png", "image/png")) | |
| 446 | - | mux.HandleFunc("GET /favicon.ico", router.ServeFile(cfg, "favicon.ico", "image/x-icon")) | |
| 447 | - | mux.HandleFunc("GET /robots.txt", router.ServeFile(cfg, "robots.txt", "text/plain")) | |
| 448 | - | mux.HandleFunc("GET /anim.js", router.ServeFile(cfg, "anim.js", "text/javascript")) | |
| 444 | + | files := cfg.Static() | |
| 445 | + | mux.HandleFunc("GET /favicon-16x16.png", files.File("favicon-16x16.png", "image/png")) | |
| 446 | + | mux.HandleFunc("GET /apple-touch-icon.png", files.File("apple-touch-icon.png", "image/png")) | |
| 447 | + | mux.HandleFunc("GET /favicon.ico", files.File("favicon.ico", "image/x-icon")) | |
| 448 | + | mux.HandleFunc("GET /robots.txt", files.File("robots.txt", "text/plain")) | |
| 449 | + | mux.HandleFunc("GET /anim.js", files.File("anim.js", "text/javascript")) | |
| 449 | 450 | if cfg.Debug { | |
| 450 | 451 | router.CreatePProfRoutesMux(mux) | |
| 451 | 452 | } |
| ... | ... | @@ -453,8 +454,8 @@ func (web *webRouter) static(mux *http.ServeMux) { | |
| 453 | 454 | ||
| 454 | 455 | func (web *webRouter) mainMux() *http.ServeMux { | |
| 455 | 456 | mux := http.NewServeMux() | |
| 456 | - | mux.HandleFunc("GET /{$}", router.CreatePageHandler(web.cfg, "html/marketing.page.tmpl")) | |
| 457 | - | mux.HandleFunc("GET /check", router.CheckHandler(web.cfg, web.db)) | |
| 457 | + | mux.HandleFunc("GET /{$}", web.cfg.Static().Page("html/marketing.page.tmpl")) | |
| 458 | + | mux.HandleFunc("GET /check", router.CheckHandler(web.cfg.Domain, web.cfg.Space, web.db)) | |
| 458 | 459 | mux.HandleFunc("GET /rss/{token...}", rssHandler(web.cfg, web.db)) | |
| 459 | 460 | mux.Handle("GET /_metrics", promhttp.Handler()) | |
| 460 | 461 |
| ... | ... | @@ -479,7 +480,7 @@ func (web *webRouter) sitesMux() *http.ServeMux { | |
| 479 | 480 | } | |
| 480 | 481 | ||
| 481 | 482 | func StartApiServer() { | |
| 482 | - | cfg := NewConfigSite("pipe-web") | |
| 483 | + | cfg := NewConfig("pipe-web") | |
| 483 | 484 | db := NewDB(postgres.NewDB(cfg.DbURL, cfg.Logger)) | |
| 484 | 485 | defer func() { | |
| 485 | 486 | _ = db.Close() |
| ... | ... | @@ -512,7 +513,7 @@ func StartApiServer() { | |
| 512 | 513 | }() | |
| 513 | 514 | ||
| 514 | 515 | web := &webRouter{cfg: cfg, db: db} | |
| 515 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 516 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 516 | 517 | ||
| 517 | 518 | portStr := fmt.Sprintf(":%s", cfg.Port) | |
| 518 | 519 | logger.Info( |
+2,
-2
| ... | ... | @@ -12,10 +12,10 @@ import ( | |
| 12 | 12 | func TestRoutes(t *testing.T) { | |
| 13 | 13 | t.Chdir("../../..") | |
| 14 | 14 | t.Setenv("PICO_PIPE_ENABLED", "false") | |
| 15 | - | cfg := NewConfigSite("pipe-test") | |
| 15 | + | cfg := NewConfig("pipe-test") | |
| 16 | 16 | cfg.Logger = slog.New(slog.DiscardHandler) | |
| 17 | 17 | web := &webRouter{cfg: cfg, db: NewTestDB(cfg.Logger)} | |
| 18 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 18 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 19 | 19 | ||
| 20 | 20 | site := "https://tester." + cfg.Domain | |
| 21 | 21 | main := "https://" + cfg.Domain |
+3,
-4
| ... | ... | @@ -21,7 +21,6 @@ import ( | |
| 21 | 21 | "github.com/picosh/pico/pkg/db" | |
| 22 | 22 | "github.com/picosh/pico/pkg/pssh" | |
| 23 | 23 | psub "github.com/picosh/pico/pkg/pubsub" | |
| 24 | - | "github.com/picosh/pico/pkg/shared" | |
| 25 | 24 | gossh "golang.org/x/crypto/ssh" | |
| 26 | 25 | ) | |
| 27 | 26 |
| ... | ... | @@ -188,7 +187,7 @@ type CliHandler struct { | |
| 188 | 187 | DBPool DB | |
| 189 | 188 | Logger *slog.Logger | |
| 190 | 189 | PubSub psub.PubSub | |
| 191 | - | Cfg *shared.ConfigSite | |
| 190 | + | Cfg *Config | |
| 192 | 191 | Waiters *syncmap.Map[string, []string] | |
| 193 | 192 | Access *syncmap.Map[string, []string] | |
| 194 | 193 | } |
| ... | ... | @@ -207,7 +206,7 @@ type CliCmd struct { | |
| 207 | 206 | user *db.User | |
| 208 | 207 | } | |
| 209 | 208 | ||
| 210 | - | func help(cfg *shared.ConfigSite, sesh *pssh.SSHServerConnSession) { | |
| 209 | + | func help(cfg *Config, sesh *pssh.SSHServerConnSession) { | |
| 211 | 210 | data := fmt.Sprintf(`Command: ssh %s <command> [args...] | |
| 212 | 211 | ||
| 213 | 212 | The simplest authenticated pubsub system. Send messages through |
| ... | ... | @@ -1153,7 +1152,7 @@ func (handler *CliHandler) pipe(cmd *CliCmd, topic string, clientID string) erro | |
| 1153 | 1152 | return nil | |
| 1154 | 1153 | } | |
| 1155 | 1154 | ||
| 1156 | - | func toSshCmd(cfg *shared.ConfigSite) string { | |
| 1155 | + | func toSshCmd(cfg *Config) string { | |
| 1157 | 1156 | port := "" | |
| 1158 | 1157 | if cfg.PortOverride != "22" { | |
| 1159 | 1158 | port = fmt.Sprintf("-p %s ", cfg.PortOverride) |
+31,
-2
| ... | ... | @@ -1,19 +1,37 @@ | |
| 1 | 1 | package pipe | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | + | "html/template" | |
| 5 | + | "log/slog" | |
| 4 | 6 | "strings" | |
| 5 | 7 | ||
| 6 | 8 | "github.com/picosh/pico/pkg/shared" | |
| 9 | + | "github.com/picosh/pico/pkg/shared/router" | |
| 7 | 10 | ) | |
| 8 | 11 | ||
| 9 | - | func NewConfigSite(service string) *shared.ConfigSite { | |
| 12 | + | // staticDir holds pipe's templates and public files. | |
| 13 | + | const staticDir = "pkg/apps/pipe" | |
| 14 | + | ||
| 15 | + | type Config struct { | |
| 16 | + | Debug bool | |
| 17 | + | Domain string | |
| 18 | + | Port string | |
| 19 | + | // PortOverride is the ssh port users connect to, when it isn't 22. | |
| 20 | + | PortOverride string | |
| 21 | + | Protocol string | |
| 22 | + | DbURL string | |
| 23 | + | Space string | |
| 24 | + | Logger *slog.Logger | |
| 25 | + | } | |
| 26 | + | ||
| 27 | + | func NewConfig(service string) *Config { | |
| 10 | 28 | domain := shared.GetEnv("PIPE_DOMAIN", "pipe.pico.sh") | |
| 11 | 29 | port := shared.GetEnv("PIPE_WEB_PORT", "3000") | |
| 12 | 30 | dbURL := shared.GetEnv("DATABASE_URL", "") | |
| 13 | 31 | protocol := shared.GetEnv("PIPE_PROTOCOL", "https") | |
| 14 | 32 | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 15 | 33 | ||
| 16 | - | return &shared.ConfigSite{ | |
| 34 | + | return &Config{ | |
| 17 | 35 | Domain: domain, | |
| 18 | 36 | Port: port, | |
| 19 | 37 | Protocol: protocol, |
| ... | ... | @@ -22,3 +40,14 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 22 | 40 | Space: "pipe", | |
| 23 | 41 | } | |
| 24 | 42 | } | |
| 43 | + | ||
| 44 | + | func (c *Config) Static() router.Static { | |
| 45 | + | return router.Static{ | |
| 46 | + | Dir: staticDir, | |
| 47 | + | Logger: c.Logger, | |
| 48 | + | Site: shared.SitePageData{ | |
| 49 | + | Domain: template.URL(c.Domain), | |
| 50 | + | HomeURL: template.URL("//" + c.Domain), | |
| 51 | + | }, | |
| 52 | + | } | |
| 53 | + | } |
+1,
-1
| ... | ... | @@ -21,7 +21,7 @@ func StartSshServer() { | |
| 21 | 21 | port := shared.GetEnv("PIPE_SSH_PORT", "2222") | |
| 22 | 22 | portOverride := shared.GetEnv("PIPE_SSH_PORT_OVERRIDE", port) | |
| 23 | 23 | promPort := shared.GetEnv("PIPE_PROM_PORT", "9222") | |
| 24 | - | cfg := NewConfigSite(appName) | |
| 24 | + | cfg := NewConfig(appName) | |
| 25 | 25 | logger := cfg.Logger | |
| 26 | 26 | ||
| 27 | 27 | ctx, cancel := context.WithCancel(context.Background()) |
+66,
-22
| ... | ... | @@ -8,6 +8,7 @@ import ( | |
| 8 | 8 | "fmt" | |
| 9 | 9 | "io" | |
| 10 | 10 | "log/slog" | |
| 11 | + | "net" | |
| 11 | 12 | "os" | |
| 12 | 13 | "strings" | |
| 13 | 14 | "sync" |
| ... | ... | @@ -237,7 +238,7 @@ func (t *TestDB) FindPipeMonitorHistory(monitorID string, from, to time.Time) ([ | |
| 237 | 238 | } | |
| 238 | 239 | ||
| 239 | 240 | type TestSSHServer struct { | |
| 240 | - | Cfg *shared.ConfigSite | |
| 241 | + | Cfg *Config | |
| 241 | 242 | DBPool *TestDB | |
| 242 | 243 | PipeHandler *CliHandler | |
| 243 | 244 | Cancel context.CancelFunc |
| ... | ... | @@ -254,7 +255,7 @@ func NewTestSSHServer(t *testing.T) *TestSSHServer { | |
| 254 | 255 | ||
| 255 | 256 | dbpool := NewTestDB(logger) | |
| 256 | 257 | ||
| 257 | - | cfg := &shared.ConfigSite{ | |
| 258 | + | cfg := &Config{ | |
| 258 | 259 | Domain: "pipe.test", | |
| 259 | 260 | Port: "2225", | |
| 260 | 261 | PortOverride: "2225", |
| ... | ... | @@ -316,7 +317,7 @@ func NewTestSSHServer(t *testing.T) *TestSSHServer { | |
| 316 | 317 | } | |
| 317 | 318 | }() | |
| 318 | 319 | ||
| 319 | - | time.Sleep(100 * time.Millisecond) | |
| 320 | + | waitForPort(t, cfg.Port, true) | |
| 320 | 321 | ||
| 321 | 322 | return &TestSSHServer{ | |
| 322 | 323 | Cfg: cfg, |
| ... | ... | @@ -328,7 +329,50 @@ func NewTestSSHServer(t *testing.T) *TestSSHServer { | |
| 328 | 329 | ||
| 329 | 330 | func (s *TestSSHServer) Shutdown() { | |
| 330 | 331 | s.Cancel() | |
| 331 | - | time.Sleep(10 * time.Millisecond) | |
| 332 | + | waitForPort(nil, s.Cfg.Port, false) | |
| 333 | + | } | |
| 334 | + | ||
| 335 | + | // waitForPort waits until the test server's port accepts connections, or | |
| 336 | + | // until it stops accepting them so the next test can listen on it. | |
| 337 | + | func waitForPort(t *testing.T, port string, open bool) { | |
| 338 | + | deadline := time.Now().Add(5 * time.Second) | |
| 339 | + | for time.Now().Before(deadline) { | |
| 340 | + | conn, err := net.DialTimeout("tcp", "localhost:"+port, 100*time.Millisecond) | |
| 341 | + | if err == nil { | |
| 342 | + | _ = conn.Close() | |
| 343 | + | } | |
| 344 | + | if (err == nil) == open { | |
| 345 | + | return | |
| 346 | + | } | |
| 347 | + | time.Sleep(5 * time.Millisecond) | |
| 348 | + | } | |
| 349 | + | if t != nil { | |
| 350 | + | t.Fatalf("port %s open = %v, want %v", port, !open, open) | |
| 351 | + | } | |
| 352 | + | } | |
| 353 | + | ||
| 354 | + | // waitForClients waits until n subscribers and pipes have joined their | |
| 355 | + | // topics, so a message published next reaches them. | |
| 356 | + | func (s *TestSSHServer) waitForClients(t *testing.T, n int) { | |
| 357 | + | t.Helper() | |
| 358 | + | ps := s.PipeHandler.PubSub.(*psub.Multicast) | |
| 359 | + | deadline := time.Now().Add(5 * time.Second) | |
| 360 | + | for { | |
| 361 | + | joined := 0 | |
| 362 | + | for range ps.GetSubs() { | |
| 363 | + | joined++ | |
| 364 | + | } | |
| 365 | + | for range ps.GetPipes() { | |
| 366 | + | joined++ | |
| 367 | + | } | |
| 368 | + | if joined >= n { | |
| 369 | + | return | |
| 370 | + | } | |
| 371 | + | if time.Now().After(deadline) { | |
| 372 | + | t.Fatalf("%d of %d subscribers and pipes joined", joined, n) | |
| 373 | + | } | |
| 374 | + | time.Sleep(5 * time.Millisecond) | |
| 375 | + | } | |
| 332 | 376 | } | |
| 333 | 377 | ||
| 334 | 378 | type UserSSH struct { |
| ... | ... | @@ -539,7 +583,7 @@ func TestPubSub_BasicFlow(t *testing.T) { | |
| 539 | 583 | t.Fatalf("failed to start sub: %v", err) | |
| 540 | 584 | } | |
| 541 | 585 | ||
| 542 | - | time.Sleep(100 * time.Millisecond) | |
| 586 | + | server.waitForClients(t, 1) | |
| 543 | 587 | ||
| 544 | 588 | testMessage := "hello from pub" | |
| 545 | 589 | _, err = user.RunCommandWithStdin(pubClient, "pub testtopic -c", testMessage) |
| ... | ... | @@ -595,7 +639,7 @@ func TestPubSub_PublicTopic(t *testing.T) { | |
| 595 | 639 | t.Fatalf("failed to start sub: %v", err) | |
| 596 | 640 | } | |
| 597 | 641 | ||
| 598 | - | time.Sleep(100 * time.Millisecond) | |
| 642 | + | server.waitForClients(t, 1) | |
| 599 | 643 | ||
| 600 | 644 | testMessage := "public message" | |
| 601 | 645 | _, err = alice.RunCommandWithStdin(pubClient, "pub publictopic -p -c", testMessage) |
| ... | ... | @@ -656,7 +700,7 @@ func TestPipe_Bidirectional(t *testing.T) { | |
| 656 | 700 | t.Fatalf("failed to start alice pipe: %v", err) | |
| 657 | 701 | } | |
| 658 | 702 | ||
| 659 | - | time.Sleep(100 * time.Millisecond) | |
| 703 | + | server.waitForClients(t, 1) | |
| 660 | 704 | ||
| 661 | 705 | bobSession, err := bobClient.NewSession() | |
| 662 | 706 | if err != nil { |
| ... | ... | @@ -678,7 +722,7 @@ func TestPipe_Bidirectional(t *testing.T) { | |
| 678 | 722 | t.Fatalf("failed to start bob pipe: %v", err) | |
| 679 | 723 | } | |
| 680 | 724 | ||
| 681 | - | time.Sleep(100 * time.Millisecond) | |
| 725 | + | server.waitForClients(t, 2) | |
| 682 | 726 | ||
| 683 | 727 | aliceMsg := "hello from alice\n" | |
| 684 | 728 | _, err = aliceStdin.Write([]byte(aliceMsg)) |
| ... | ... | @@ -798,7 +842,7 @@ func TestAccessControl_AllowedUserViaFullPath(t *testing.T) { | |
| 798 | 842 | t.Fatalf("failed to start alice sub: %v", err) | |
| 799 | 843 | } | |
| 800 | 844 | ||
| 801 | - | time.Sleep(100 * time.Millisecond) | |
| 845 | + | server.waitForClients(t, 1) | |
| 802 | 846 | ||
| 803 | 847 | bobClient, err := bob.NewClient() | |
| 804 | 848 | if err != nil { |
| ... | ... | @@ -908,7 +952,7 @@ func TestPubSub_BlockingWaitsForSubscriber(t *testing.T) { | |
| 908 | 952 | t.Fatalf("failed to start sub: %v", err) | |
| 909 | 953 | } | |
| 910 | 954 | ||
| 911 | - | time.Sleep(100 * time.Millisecond) | |
| 955 | + | server.waitForClients(t, 1) | |
| 912 | 956 | ||
| 913 | 957 | // Now send the message | |
| 914 | 958 | testMessage := "blocking message" |
| ... | ... | @@ -1036,7 +1080,7 @@ func TestSub_WaitsForPublisher(t *testing.T) { | |
| 1036 | 1080 | } | |
| 1037 | 1081 | ||
| 1038 | 1082 | // Subscriber is now waiting - give it a moment | |
| 1039 | - | time.Sleep(100 * time.Millisecond) | |
| 1083 | + | server.waitForClients(t, 1) | |
| 1040 | 1084 | ||
| 1041 | 1085 | // Now publish - subscriber should receive it | |
| 1042 | 1086 | testMessage := "delayed publish" |
| ... | ... | @@ -1097,7 +1141,7 @@ func TestSub_KeepAliveReceivesMultipleMessages(t *testing.T) { | |
| 1097 | 1141 | t.Fatalf("failed to start sub: %v", err) | |
| 1098 | 1142 | } | |
| 1099 | 1143 | ||
| 1100 | - | time.Sleep(100 * time.Millisecond) | |
| 1144 | + | server.waitForClients(t, 1) | |
| 1101 | 1145 | ||
| 1102 | 1146 | // Send first message | |
| 1103 | 1147 | msg1 := "first message\n" |
| ... | ... | @@ -1160,7 +1204,7 @@ func TestSub_WithoutKeepAliveExitsAfterPublisher(t *testing.T) { | |
| 1160 | 1204 | t.Fatalf("failed to start sub: %v", err) | |
| 1161 | 1205 | } | |
| 1162 | 1206 | ||
| 1163 | - | time.Sleep(100 * time.Millisecond) | |
| 1207 | + | server.waitForClients(t, 1) | |
| 1164 | 1208 | ||
| 1165 | 1209 | // Publish a message | |
| 1166 | 1210 | testMessage := "single message" |
| ... | ... | @@ -1227,7 +1271,7 @@ func TestPub_EmptyMessage(t *testing.T) { | |
| 1227 | 1271 | t.Fatalf("failed to start sub: %v", err) | |
| 1228 | 1272 | } | |
| 1229 | 1273 | ||
| 1230 | - | time.Sleep(100 * time.Millisecond) | |
| 1274 | + | server.waitForClients(t, 1) | |
| 1231 | 1275 | ||
| 1232 | 1276 | // Publish with -e flag (empty message) - should not require stdin | |
| 1233 | 1277 | output, err := user.RunCommand(pubClient, "pub emptytopic -e -c") |
| ... | ... | @@ -1291,7 +1335,7 @@ func TestPipe_AccessControl(t *testing.T) { | |
| 1291 | 1335 | t.Fatalf("failed to start alice pipe: %v", err) | |
| 1292 | 1336 | } | |
| 1293 | 1337 | ||
| 1294 | - | time.Sleep(100 * time.Millisecond) | |
| 1338 | + | server.waitForClients(t, 1) | |
| 1295 | 1339 | ||
| 1296 | 1340 | // Bob joins the pipe using alice's namespace | |
| 1297 | 1341 | bobSession, err := bobClient.NewSession() |
| ... | ... | @@ -1314,7 +1358,7 @@ func TestPipe_AccessControl(t *testing.T) { | |
| 1314 | 1358 | t.Fatalf("failed to start bob pipe: %v", err) | |
| 1315 | 1359 | } | |
| 1316 | 1360 | ||
| 1317 | - | time.Sleep(100 * time.Millisecond) | |
| 1361 | + | server.waitForClients(t, 2) | |
| 1318 | 1362 | ||
| 1319 | 1363 | // Alice sends message to bob | |
| 1320 | 1364 | aliceMsg := "hello bob\n" |
| ... | ... | @@ -1377,7 +1421,7 @@ func TestPipe_Replay(t *testing.T) { | |
| 1377 | 1421 | t.Fatalf("failed to start pipe: %v", err) | |
| 1378 | 1422 | } | |
| 1379 | 1423 | ||
| 1380 | - | time.Sleep(100 * time.Millisecond) | |
| 1424 | + | server.waitForClients(t, 1) | |
| 1381 | 1425 | ||
| 1382 | 1426 | // Send a message - with -r flag, should receive it back | |
| 1383 | 1427 | testMsg := "echo back\n" |
| ... | ... | @@ -1431,7 +1475,7 @@ func TestAccessControl_UnauthorizedUserDenied(t *testing.T) { | |
| 1431 | 1475 | t.Fatalf("failed to start alice sub: %v", err) | |
| 1432 | 1476 | } | |
| 1433 | 1477 | ||
| 1434 | - | time.Sleep(100 * time.Millisecond) | |
| 1478 | + | server.waitForClients(t, 1) | |
| 1435 | 1479 | ||
| 1436 | 1480 | // Charlie tries to publish to alice's restricted topic - should be denied | |
| 1437 | 1481 | output, err := charlie.RunCommandWithStdin(charlieClient, "pub alice/restrictedtopic -c", "unauthorized message") |
| ... | ... | @@ -1524,7 +1568,7 @@ func TestPubSub_MultipleSubscribers(t *testing.T) { | |
| 1524 | 1568 | t.Fatalf("failed to start sub3: %v", err) | |
| 1525 | 1569 | } | |
| 1526 | 1570 | ||
| 1527 | - | time.Sleep(100 * time.Millisecond) | |
| 1571 | + | server.waitForClients(t, 3) | |
| 1528 | 1572 | ||
| 1529 | 1573 | // Publish a single message | |
| 1530 | 1574 | testMessage := "broadcast message" |
| ... | ... | @@ -1995,7 +2039,7 @@ func TestPub_UpdatesMonitorLastPing(t *testing.T) { | |
| 1995 | 2039 | t.Fatalf("failed to start sub: %v", err) | |
| 1996 | 2040 | } | |
| 1997 | 2041 | ||
| 1998 | - | time.Sleep(100 * time.Millisecond) | |
| 2042 | + | server.waitForClients(t, 1) | |
| 1999 | 2043 | ||
| 2000 | 2044 | // Publish to the monitored topic | |
| 2001 | 2045 | _, err = user.RunCommandWithStdin(pubClient, "pub ping-test -c", "health check") |
| ... | ... | @@ -2093,7 +2137,7 @@ func TestStatus_PingResetsWindow(t *testing.T) { | |
| 2093 | 2137 | t.Fatalf("failed to start sub: %v", err) | |
| 2094 | 2138 | } | |
| 2095 | 2139 | ||
| 2096 | - | time.Sleep(100 * time.Millisecond) | |
| 2140 | + | server.waitForClients(t, 1) | |
| 2097 | 2141 | ||
| 2098 | 2142 | // Pub to trigger monitor update | |
| 2099 | 2143 | _, err = user.RunCommandWithStdin(client, "pub reset-test -c", "ping") |
| ... | ... | @@ -2154,7 +2198,7 @@ func TestStatus_HealthyImmediatelyAfterPing(t *testing.T) { | |
| 2154 | 2198 | t.Fatalf("failed to start sub: %v", err) | |
| 2155 | 2199 | } | |
| 2156 | 2200 | ||
| 2157 | - | time.Sleep(100 * time.Millisecond) | |
| 2201 | + | server.waitForClients(t, 1) | |
| 2158 | 2202 | ||
| 2159 | 2203 | // Pub to trigger ping | |
| 2160 | 2204 | pubClient, err := user.NewClient() |
+47,
-48
| ... | ... | @@ -119,7 +119,7 @@ func GetBlogName(username string) string { | |
| 119 | 119 | } | |
| 120 | 120 | ||
| 121 | 121 | func (web *webRouter) blogStyleHandler(w http.ResponseWriter, r *http.Request) { | |
| 122 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 122 | + | username := router.GetUsernameFromRequest(r) | |
| 123 | 123 | dbpool := web.db | |
| 124 | 124 | logger := web.cfg.Logger | |
| 125 | 125 | cfg := web.cfg |
| ... | ... | @@ -149,7 +149,7 @@ func (web *webRouter) blogStyleHandler(w http.ResponseWriter, r *http.Request) { | |
| 149 | 149 | } | |
| 150 | 150 | ||
| 151 | 151 | func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 152 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 152 | + | username := router.GetUsernameFromRequest(r) | |
| 153 | 153 | dbpool := web.db | |
| 154 | 154 | logger := web.cfg.Logger | |
| 155 | 155 | cfg := web.cfg |
| ... | ... | @@ -179,12 +179,12 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 179 | 179 | return | |
| 180 | 180 | } | |
| 181 | 181 | ||
| 182 | - | ts, err := router.RenderTemplate(cfg, []string{ | |
| 182 | + | ts, err := router.RenderTemplate(staticDir, []string{ | |
| 183 | 183 | cfg.StaticPath("html/blog-default.partial.tmpl"), | |
| 184 | 184 | cfg.StaticPath("html/blog.page.tmpl"), | |
| 185 | 185 | }) | |
| 186 | 186 | ||
| 187 | - | curl := shared.CreateURLFromRequest(cfg, r) | |
| 187 | + | curl := shared.CreateURLFromRequest(cfg.Protocol, cfg.Domain, r) | |
| 188 | 188 | ||
| 189 | 189 | if err != nil { | |
| 190 | 190 | logger.Error("render template", "err", err.Error()) |
| ... | ... | @@ -218,9 +218,7 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 218 | 218 | u, _ := url.Parse(nav.URL) | |
| 219 | 219 | finURL := nav.URL | |
| 220 | 220 | if !u.IsAbs() { | |
| 221 | - | finURL = cfg.FullPostURL( | |
| 222 | - | curl, | |
| 223 | - | readme.Username, | |
| 221 | + | finURL = curl.FullPostURL(readme.Username, | |
| 224 | 222 | nav.URL, | |
| 225 | 223 | ) | |
| 226 | 224 | } |
| ... | ... | @@ -245,8 +243,8 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 245 | 243 | postCollection := make([]PostItemData, 0, len(posts)) | |
| 246 | 244 | for _, post := range posts { | |
| 247 | 245 | p := PostItemData{ | |
| 248 | - | URL: template.URL(cfg.FullPostURL(curl, post.Username, post.Slug)), | |
| 249 | - | BlogURL: template.URL(cfg.FullBlogURL(curl, post.Username)), | |
| 246 | + | URL: template.URL(curl.FullPostURL(post.Username, post.Slug)), | |
| 247 | + | BlogURL: template.URL(curl.FullBlogURL(post.Username)), | |
| 250 | 248 | Title: shared.FilenameToTitle(post.Filename, post.Title), | |
| 251 | 249 | PublishAt: post.PublishAt.Format(time.DateOnly), | |
| 252 | 250 | PublishAtISO: post.PublishAt.Format(time.RFC3339), |
| ... | ... | @@ -257,16 +255,16 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 257 | 255 | } | |
| 258 | 256 | ||
| 259 | 257 | data := BlogPageData{ | |
| 260 | - | Site: *cfg.GetSiteData(), | |
| 258 | + | Site: cfg.SiteData(), | |
| 261 | 259 | PageTitle: headerTxt.Title, | |
| 262 | - | URL: template.URL(cfg.FullBlogURL(curl, username)), | |
| 263 | - | RSSURL: template.URL(cfg.RssBlogURL(curl, username, tag)), | |
| 260 | + | URL: template.URL(curl.FullBlogURL(username)), | |
| 261 | + | RSSURL: template.URL(curl.RssBlogURL(username, tag)), | |
| 264 | 262 | Readme: readmeTxt, | |
| 265 | 263 | Header: headerTxt, | |
| 266 | 264 | Username: username, | |
| 267 | 265 | Posts: postCollection, | |
| 268 | 266 | HasCSS: hasCSS, | |
| 269 | - | CssURL: template.URL(cfg.CssURL(username)), | |
| 267 | + | CssURL: template.URL(cfg.CssURL()), | |
| 270 | 268 | HasFilter: tag != "", | |
| 271 | 269 | } | |
| 272 | 270 |
| ... | ... | @@ -278,7 +276,7 @@ func (web *webRouter) blogHandler(w http.ResponseWriter, r *http.Request) { | |
| 278 | 276 | } | |
| 279 | 277 | ||
| 280 | 278 | func (web *webRouter) postRawHandler(w http.ResponseWriter, r *http.Request) { | |
| 281 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 279 | + | username := router.GetUsernameFromRequest(r) | |
| 282 | 280 | cfg := web.cfg | |
| 283 | 281 | slug, _ := url.PathUnescape(r.PathValue("slug")) | |
| 284 | 282 | slug = strings.TrimSuffix(slug, "/") |
| ... | ... | @@ -312,7 +310,7 @@ func (web *webRouter) postRawHandler(w http.ResponseWriter, r *http.Request) { | |
| 312 | 310 | } | |
| 313 | 311 | ||
| 314 | 312 | func (web *webRouter) robotsHandler(w http.ResponseWriter, r *http.Request) { | |
| 315 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 313 | + | username := router.GetUsernameFromRequest(r) | |
| 316 | 314 | cfg := web.cfg | |
| 317 | 315 | dbpool := web.db | |
| 318 | 316 | logger := web.cfg.Logger |
| ... | ... | @@ -338,7 +336,7 @@ func (web *webRouter) robotsHandler(w http.ResponseWriter, r *http.Request) { | |
| 338 | 336 | } | |
| 339 | 337 | ||
| 340 | 338 | func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 341 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 339 | + | username := router.GetUsernameFromRequest(r) | |
| 342 | 340 | cfg := web.cfg | |
| 343 | 341 | slug, _ := url.PathUnescape(r.PathValue("slug")) | |
| 344 | 342 | slug = strings.TrimSuffix(slug, "/") |
| ... | ... | @@ -357,7 +355,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 357 | 355 | logger = logger.With("slug", slug) | |
| 358 | 356 | ||
| 359 | 357 | blogName := GetBlogName(username) | |
| 360 | - | curl := shared.CreateURLFromRequest(cfg, r) | |
| 358 | + | curl := shared.CreateURLFromRequest(cfg.Protocol, cfg.Domain, r) | |
| 361 | 359 | ||
| 362 | 360 | favicon := "" | |
| 363 | 361 | ogImage := "" |
| ... | ... | @@ -441,10 +439,10 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 441 | 439 | } | |
| 442 | 440 | ||
| 443 | 441 | data = PostPageData{ | |
| 444 | - | Site: *cfg.GetSiteData(), | |
| 442 | + | Site: cfg.SiteData(), | |
| 445 | 443 | PageTitle: GetPostTitle(post), | |
| 446 | - | URL: template.URL(cfg.FullPostURL(curl, post.Username, post.Slug)), | |
| 447 | - | BlogURL: template.URL(cfg.FullBlogURL(curl, username)), | |
| 444 | + | URL: template.URL(curl.FullPostURL(post.Username, post.Slug)), | |
| 445 | + | BlogURL: template.URL(curl.FullBlogURL(username)), | |
| 448 | 446 | Description: post.Description, | |
| 449 | 447 | Title: shared.FilenameToTitle(post.Filename, post.Title), | |
| 450 | 448 | Slug: post.Slug, |
| ... | ... | @@ -456,7 +454,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 456 | 454 | BlogName: blogName, | |
| 457 | 455 | Contents: contents, | |
| 458 | 456 | HasCSS: hasCSS, | |
| 459 | - | CssURL: template.URL(cfg.CssURL(username)), | |
| 457 | + | CssURL: template.URL(cfg.CssURL()), | |
| 460 | 458 | Tags: tags, | |
| 461 | 459 | Image: template.URL(ogImage), | |
| 462 | 460 | ImageCard: ogImageCard, |
| ... | ... | @@ -492,8 +490,8 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 492 | 490 | now := time.Now() | |
| 493 | 491 | ||
| 494 | 492 | data = PostPageData{ | |
| 495 | - | Site: *cfg.GetSiteData(), | |
| 496 | - | BlogURL: template.URL(cfg.FullBlogURL(curl, username)), | |
| 493 | + | Site: cfg.SiteData(), | |
| 494 | + | BlogURL: template.URL(curl.FullBlogURL(username)), | |
| 497 | 495 | PageTitle: title, | |
| 498 | 496 | Description: desc, | |
| 499 | 497 | Title: title, |
| ... | ... | @@ -504,7 +502,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 504 | 502 | Username: username, | |
| 505 | 503 | BlogName: blogName, | |
| 506 | 504 | HasCSS: hasCSS, | |
| 507 | - | CssURL: template.URL(cfg.CssURL(username)), | |
| 505 | + | CssURL: template.URL(cfg.CssURL()), | |
| 508 | 506 | Image: template.URL(ogImage), | |
| 509 | 507 | ImageCard: ogImageCard, | |
| 510 | 508 | Favicon: template.URL(favicon), |
| ... | ... | @@ -515,7 +513,7 @@ func (web *webRouter) postHandler(w http.ResponseWriter, r *http.Request) { | |
| 515 | 513 | w.WriteHeader(http.StatusNotFound) | |
| 516 | 514 | } | |
| 517 | 515 | ||
| 518 | - | ts, err := router.RenderTemplate(cfg, []string{ | |
| 516 | + | ts, err := router.RenderTemplate(staticDir, []string{ | |
| 519 | 517 | cfg.StaticPath("html/list.partial.tmpl"), | |
| 520 | 518 | cfg.StaticPath("html/post.page.tmpl"), | |
| 521 | 519 | }) |
| ... | ... | @@ -545,7 +543,7 @@ func (web *webRouter) readHandler(w http.ResponseWriter, r *http.Request) { | |
| 545 | 543 | return | |
| 546 | 544 | } | |
| 547 | 545 | ||
| 548 | - | ts, err := router.RenderTemplate(cfg, []string{ | |
| 546 | + | ts, err := router.RenderTemplate(staticDir, []string{ | |
| 549 | 547 | cfg.StaticPath("html/read.page.tmpl"), | |
| 550 | 548 | }) | |
| 551 | 549 |
| ... | ... | @@ -554,14 +552,14 @@ func (web *webRouter) readHandler(w http.ResponseWriter, r *http.Request) { | |
| 554 | 552 | } | |
| 555 | 553 | ||
| 556 | 554 | data := ReadPageData{ | |
| 557 | - | Site: *cfg.GetSiteData(), | |
| 555 | + | Site: cfg.SiteData(), | |
| 558 | 556 | } | |
| 559 | 557 | ||
| 560 | - | curl := shared.NewCreateURL(cfg) | |
| 558 | + | curl := shared.NewCreateURL(cfg.Protocol, cfg.Domain) | |
| 561 | 559 | for _, post := range posts { | |
| 562 | 560 | item := PostItemData{ | |
| 563 | - | URL: template.URL(cfg.FullPostURL(curl, post.Username, post.Slug)), | |
| 564 | - | BlogURL: template.URL(cfg.FullBlogURL(curl, post.Username)), | |
| 561 | + | URL: template.URL(curl.FullPostURL(post.Username, post.Slug)), | |
| 562 | + | BlogURL: template.URL(curl.FullBlogURL(post.Username)), | |
| 565 | 563 | Title: shared.FilenameToTitle(post.Filename, post.Title), | |
| 566 | 564 | Description: post.Description, | |
| 567 | 565 | Username: post.Username, |
| ... | ... | @@ -582,7 +580,7 @@ func (web *webRouter) readHandler(w http.ResponseWriter, r *http.Request) { | |
| 582 | 580 | } | |
| 583 | 581 | ||
| 584 | 582 | func (web *webRouter) rssBlogHandler(w http.ResponseWriter, r *http.Request) { | |
| 585 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 583 | + | username := router.GetUsernameFromRequest(r) | |
| 586 | 584 | dbpool := web.db | |
| 587 | 585 | logger := web.cfg.Logger | |
| 588 | 586 | cfg := web.cfg |
| ... | ... | @@ -642,8 +640,8 @@ func (web *webRouter) rssBlogHandler(w http.ResponseWriter, r *http.Request) { | |
| 642 | 640 | } | |
| 643 | 641 | } | |
| 644 | 642 | ||
| 645 | - | curl := shared.CreateURLFromRequest(cfg, r) | |
| 646 | - | blogUrl := cfg.FullBlogURL(curl, username) | |
| 643 | + | curl := shared.CreateURLFromRequest(cfg.Protocol, cfg.Domain, r) | |
| 644 | + | blogUrl := curl.FullBlogURL(username) | |
| 647 | 645 | ||
| 648 | 646 | updatedAt := &time.Time{} | |
| 649 | 647 | if len(posts) > 0 { |
| ... | ... | @@ -708,7 +706,7 @@ func (web *webRouter) rssBlogHandler(w http.ResponseWriter, r *http.Request) { | |
| 708 | 706 | ||
| 709 | 707 | } | |
| 710 | 708 | ||
| 711 | - | realUrl := cfg.FullPostURL(curl, post.Username, post.Slug) | |
| 709 | + | realUrl := curl.FullPostURL(post.Username, post.Slug) | |
| 712 | 710 | feedId := realUrl | |
| 713 | 711 | ||
| 714 | 712 | item := &feeds.Item{ |
| ... | ... | @@ -772,7 +770,7 @@ func (web *webRouter) rssHandler(w http.ResponseWriter, r *http.Request) { | |
| 772 | 770 | Created: time.Now(), | |
| 773 | 771 | } | |
| 774 | 772 | ||
| 775 | - | curl := shared.CreateURLFromRequest(cfg, r) | |
| 773 | + | curl := shared.CreateURLFromRequest(cfg.Protocol, cfg.Domain, r) | |
| 776 | 774 | ||
| 777 | 775 | var feedItems []*feeds.Item | |
| 778 | 776 | for _, post := range posts { |
| ... | ... | @@ -806,7 +804,7 @@ func (web *webRouter) rssHandler(w http.ResponseWriter, r *http.Request) { | |
| 806 | 804 | ||
| 807 | 805 | } | |
| 808 | 806 | ||
| 809 | - | realUrl := cfg.FullPostURL(curl, post.Username, post.Slug) | |
| 807 | + | realUrl := curl.FullPostURL(post.Username, post.Slug) | |
| 810 | 808 | if !curl.Subdomain && !curl.UsernameInRoute { | |
| 811 | 809 | realUrl = fmt.Sprintf("%s://%s%s", cfg.Protocol, r.Host, realUrl) | |
| 812 | 810 | } |
| ... | ... | @@ -847,7 +845,7 @@ func (web *webRouter) imgRequest(w http.ResponseWriter, r *http.Request) { | |
| 847 | 845 | logger := web.cfg.Logger | |
| 848 | 846 | st := web.storage | |
| 849 | 847 | dbpool := web.db | |
| 850 | - | username := router.GetUsernameFromRequest(r, web.cfg) | |
| 848 | + | username := router.GetUsernameFromRequest(r) | |
| 851 | 849 | user, err := dbpool.FindUserByName(username) | |
| 852 | 850 | if err != nil { | |
| 853 | 851 | logger.Error("could not find user", "username", username) |
| ... | ... | @@ -881,19 +879,20 @@ func (web *webRouter) imgRequest(w http.ResponseWriter, r *http.Request) { | |
| 881 | 879 | } | |
| 882 | 880 | ||
| 883 | 881 | type webRouter struct { | |
| 884 | - | cfg *shared.ConfigSite | |
| 882 | + | cfg *Config | |
| 885 | 883 | db DB | |
| 886 | 884 | storage storage.StorageServe | |
| 887 | 885 | } | |
| 888 | 886 | ||
| 889 | 887 | func (web *webRouter) static(mux *http.ServeMux) { | |
| 890 | 888 | cfg := web.cfg | |
| 891 | - | mux.HandleFunc("GET /read.css", router.ServeFile(cfg, "read.css", "text/css")) | |
| 892 | - | mux.HandleFunc("GET /reset.css", router.ServeFile(cfg, "reset.css", "text/css")) | |
| 893 | - | mux.HandleFunc("GET /syntax.css", router.ServeFile(cfg, "syntax.css", "text/css")) | |
| 894 | - | mux.HandleFunc("GET /card.png", router.ServeFile(cfg, "card.png", "image/png")) | |
| 895 | - | mux.HandleFunc("GET /favicon-16x16.png", router.ServeFile(cfg, "favicon-16x16.png", "image/png")) | |
| 896 | - | mux.HandleFunc("GET /favicon.ico", router.ServeFile(cfg, "favicon.ico", "image/x-icon")) | |
| 889 | + | files := cfg.Static() | |
| 890 | + | mux.HandleFunc("GET /read.css", files.File("read.css", "text/css")) | |
| 891 | + | mux.HandleFunc("GET /reset.css", files.File("reset.css", "text/css")) | |
| 892 | + | mux.HandleFunc("GET /syntax.css", files.File("syntax.css", "text/css")) | |
| 893 | + | mux.HandleFunc("GET /card.png", files.File("card.png", "image/png")) | |
| 894 | + | mux.HandleFunc("GET /favicon-16x16.png", files.File("favicon-16x16.png", "image/png")) | |
| 895 | + | mux.HandleFunc("GET /favicon.ico", files.File("favicon.ico", "image/x-icon")) | |
| 897 | 896 | if cfg.Debug { | |
| 898 | 897 | router.CreatePProfRoutesMux(mux) | |
| 899 | 898 | } |
| ... | ... | @@ -904,11 +903,11 @@ func (web *webRouter) mainMux() *http.ServeMux { | |
| 904 | 903 | mux := http.NewServeMux() | |
| 905 | 904 | mux.HandleFunc("GET /{$}", web.readHandler) | |
| 906 | 905 | mux.HandleFunc("GET /read", web.readHandler) | |
| 907 | - | mux.HandleFunc("GET /check", router.CheckHandler(web.cfg, web.db)) | |
| 906 | + | mux.HandleFunc("GET /check", router.CheckHandler(web.cfg.Domain, web.cfg.Space, web.db)) | |
| 908 | 907 | mux.HandleFunc("GET /rss", web.rssHandler) | |
| 909 | 908 | mux.HandleFunc("GET /rss.atom", web.rssHandler) | |
| 910 | 909 | mux.Handle("GET /_metrics", promhttp.Handler()) | |
| 911 | - | mux.HandleFunc("GET /robots.txt", router.ServeFile(web.cfg, "robots.txt", "text/plain")) | |
| 910 | + | mux.HandleFunc("GET /robots.txt", web.cfg.Static().File("robots.txt", "text/plain")) | |
| 912 | 911 | web.static(mux) | |
| 913 | 912 | return mux | |
| 914 | 913 | } |
| ... | ... | @@ -963,7 +962,7 @@ func (web *webRouter) pathRoute(w http.ResponseWriter, r *http.Request) { | |
| 963 | 962 | } | |
| 964 | 963 | ||
| 965 | 964 | func StartApiServer() { | |
| 966 | - | cfg := NewConfigSite("prose-web") | |
| 965 | + | cfg := NewConfig("prose-web") | |
| 967 | 966 | dbpool := NewDB(postgres.NewDB(cfg.DbURL, cfg.Logger)) | |
| 968 | 967 | defer func() { | |
| 969 | 968 | _ = dbpool.Close() |
| ... | ... | @@ -978,7 +977,7 @@ func StartApiServer() { | |
| 978 | 977 | } | |
| 979 | 978 | ||
| 980 | 979 | web := &webRouter{cfg: cfg, db: dbpool, storage: st} | |
| 981 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 980 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 982 | 981 | ||
| 983 | 982 | portStr := fmt.Sprintf(":%s", cfg.Port) | |
| 984 | 983 | logger.Info( |
+2,
-2
| ... | ... | @@ -20,7 +20,7 @@ func TestRoutes(t *testing.T) { | |
| 20 | 20 | logger := slog.New(slog.DiscardHandler) | |
| 21 | 21 | user := &db.User{ID: "user-1", Name: "tester"} | |
| 22 | 22 | posts := stub.NewPostsDB(logger, user) | |
| 23 | - | cfg := NewConfigSite("prose-test") | |
| 23 | + | cfg := NewConfig("prose-test") | |
| 24 | 24 | cfg.Logger = logger | |
| 25 | 25 | post := filehandlers.NewPost("hello.md", []byte("# hello")) | |
| 26 | 26 | post.UserID, post.Space, post.Title = user.ID, cfg.Space, "Hello" |
| ... | ... | @@ -32,7 +32,7 @@ func TestRoutes(t *testing.T) { | |
| 32 | 32 | t.Fatal(err) | |
| 33 | 33 | } | |
| 34 | 34 | web := &webRouter{cfg: cfg, db: posts, storage: st} | |
| 35 | - | handler := router.NewHostRouter(cfg, web.mainMux(), web.sitesMux()) | |
| 35 | + | handler := router.NewHostRouter(cfg.Domain, cfg.Space, web.mainMux(), web.sitesMux()) | |
| 36 | 36 | ||
| 37 | 37 | site := "https://tester." + cfg.Domain | |
| 38 | 38 | for _, tt := range []struct { |
+48,
-2
| ... | ... | @@ -1,14 +1,37 @@ | |
| 1 | 1 | package prose | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | + | "fmt" | |
| 5 | + | "html/template" | |
| 6 | + | "log/slog" | |
| 7 | + | "path/filepath" | |
| 4 | 8 | "strings" | |
| 5 | 9 | ||
| 6 | 10 | "github.com/picosh/pico/pkg/shared" | |
| 11 | + | "github.com/picosh/pico/pkg/shared/router" | |
| 7 | 12 | ) | |
| 8 | 13 | ||
| 9 | 14 | var MAX_FILE_SIZE = 3 * shared.MB | |
| 10 | 15 | ||
| 11 | - | func NewConfigSite(service string) *shared.ConfigSite { | |
| 16 | + | // staticDir holds prose's templates and public files. | |
| 17 | + | const staticDir = "pkg/apps/prose" | |
| 18 | + | ||
| 19 | + | type Config struct { | |
| 20 | + | Debug bool | |
| 21 | + | Domain string | |
| 22 | + | Port string | |
| 23 | + | Protocol string | |
| 24 | + | DbURL string | |
| 25 | + | Space string | |
| 26 | + | AllowedExt []string | |
| 27 | + | HiddenPosts []string | |
| 28 | + | MaxSize uint64 | |
| 29 | + | MaxAssetSize int64 | |
| 30 | + | MaxSpecialFileSize int64 | |
| 31 | + | Logger *slog.Logger | |
| 32 | + | } | |
| 33 | + | ||
| 34 | + | func NewConfig(service string) *Config { | |
| 12 | 35 | debug := shared.GetEnv("PROSE_DEBUG", "0") | |
| 13 | 36 | domain := shared.GetEnv("PROSE_DOMAIN", "prose.sh") | |
| 14 | 37 | port := shared.GetEnv("PROSE_WEB_PORT", "3000") |
| ... | ... | @@ -18,7 +41,7 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 18 | 41 | maxImgSize := int64(10 * shared.MB) | |
| 19 | 42 | withPipe := strings.ToLower(shared.GetEnv("PICO_PIPE_ENABLED", "true")) == "true" | |
| 20 | 43 | ||
| 21 | - | return &shared.ConfigSite{ | |
| 44 | + | return &Config{ | |
| 22 | 45 | Debug: debug == "1", | |
| 23 | 46 | Domain: domain, | |
| 24 | 47 | Port: port, |
| ... | ... | @@ -42,3 +65,26 @@ func NewConfigSite(service string) *shared.ConfigSite { | |
| 42 | 65 | MaxAssetSize: maxImgSize, | |
| 43 | 66 | } | |
| 44 | 67 | } | |
| 68 | + | ||
| 69 | + | func (c *Config) StaticPath(fname string) string { | |
| 70 | + | return filepath.Join(staticDir, fname) | |
| 71 | + | } | |
| 72 | + | ||
| 73 | + | func (c *Config) SiteData() shared.SitePageData { | |
| 74 | + | return shared.SitePageData{ | |
| 75 | + | Domain: template.URL(c.Domain), | |
| 76 | + | HomeURL: template.URL("//" + c.Domain), | |
| 77 | + | } | |
| 78 | + | } | |
| 79 | + | ||
| 80 | + | func (c *Config) Static() router.Static { | |
| 81 | + | return router.Static{Dir: staticDir, Logger: c.Logger, Site: c.SiteData()} | |
| 82 | + | } | |
| 83 | + | ||
| 84 | + | func (c *Config) ReadURL() string { | |
| 85 | + | return fmt.Sprintf("%s://%s", c.Protocol, c.Domain) | |
| 86 | + | } | |
| 87 | + | ||
| 88 | + | func (c *Config) CssURL() string { | |
| 89 | + | return "/_styles.css" | |
| 90 | + | } |
R pkg/filehandlers/imgs/handler.go =>
pkg/apps/prose/imgs.go
+13,
-13
| ... | ... | @@ -19,8 +19,6 @@ import ( | |
| 19 | 19 | "github.com/picosh/pico/pkg/storage" | |
| 20 | 20 | ) | |
| 21 | 21 | ||
| 22 | - | var Space = "imgs" | |
| 23 | - | ||
| 24 | 22 | type PostMetaData struct { | |
| 25 | 23 | Text []byte | |
| 26 | 24 | FileSize int |
| ... | ... | @@ -32,12 +30,12 @@ type PostMetaData struct { | |
| 32 | 30 | } | |
| 33 | 31 | ||
| 34 | 32 | type UploadImgHandler struct { | |
| 35 | - | DBPool shared.FeatureFinder | |
| 36 | - | Cfg *shared.ConfigSite | |
| 33 | + | DBPool DB | |
| 34 | + | Cfg *Config | |
| 37 | 35 | Storage storage.StorageServe | |
| 38 | 36 | } | |
| 39 | 37 | ||
| 40 | - | func NewUploadImgHandler(dbpool shared.FeatureFinder, cfg *shared.ConfigSite, storage storage.StorageServe) *UploadImgHandler { | |
| 38 | + | func NewUploadImgHandler(dbpool DB, cfg *Config, storage storage.StorageServe) *UploadImgHandler { | |
| 41 | 39 | return &UploadImgHandler{ | |
| 42 | 40 | DBPool: dbpool, | |
| 43 | 41 | Cfg: cfg, |
| ... | ... | @@ -171,7 +169,13 @@ func (h *UploadImgHandler) Write(s *pssh.SSHServerConnSession, entry *sendutils. | |
| 171 | 169 | } | |
| 172 | 170 | ||
| 173 | 171 | fileSize := binary.Size(text) | |
| 174 | - | featureFlag := shared.FindPlusFF(h.DBPool, h.Cfg, user.ID) | |
| 172 | + | featureFlag, _ := h.DBPool.FindFeature(user.ID, "plus") | |
| 173 | + | // we have free tiers so users might not have a feature flag | |
| 174 | + | // in which case we set sane defaults | |
| 175 | + | if featureFlag == nil { | |
| 176 | + | featureFlag = db.NewFeatureFlag(user.ID, "plus", h.Cfg.MaxSize, h.Cfg.MaxAssetSize, h.Cfg.MaxSpecialFileSize) | |
| 177 | + | } | |
| 178 | + | featureFlag.SetLimits(h.Cfg.MaxSize, h.Cfg.MaxAssetSize, h.Cfg.MaxSpecialFileSize) | |
| 175 | 179 | ||
| 176 | 180 | bucket, err := h.Storage.UpsertBucket(shared.GetAssetBucketName(user.ID)) | |
| 177 | 181 | if err != nil { |
| ... | ... | @@ -200,12 +204,8 @@ func (h *UploadImgHandler) Write(s *pssh.SSHServerConnSession, entry *sendutils. | |
| 200 | 204 | return "", err | |
| 201 | 205 | } | |
| 202 | 206 | ||
| 203 | - | curl := shared.NewCreateURL(h.Cfg) | |
| 204 | - | url := h.Cfg.FullPostURL( | |
| 205 | - | curl, | |
| 206 | - | user.Name, | |
| 207 | - | metadata.Filename, | |
| 208 | - | ) | |
| 207 | + | curl := shared.NewCreateURL(h.Cfg.Protocol, h.Cfg.Domain) | |
| 208 | + | url := curl.FullPostURL(user.Name, metadata.Filename) | |
| 209 | 209 | return url + shared.StorageUsage(metadata.TotalFileSize+fileSize, int(featureFlag.Data.StorageMax)), nil | |
| 210 | 210 | } | |
| 211 | 211 |
+2,
-2
| ... | ... | @@ -16,7 +16,7 @@ import ( | |
| 16 | 16 | ||
| 17 | 17 | // postUploader stores prose's text files as posts. | |
| 18 | 18 | type postUploader struct { | |
| 19 | - | Cfg *shared.ConfigSite | |
| 19 | + | Cfg *Config | |
| 20 | 20 | DB DB | |
| 21 | 21 | } | |
| 22 | 22 |
| ... | ... | @@ -98,7 +98,7 @@ func (h *postUploader) Write(s *pssh.SSHServerConnSession, entry *sendutils.File | |
| 98 | 98 | } | |
| 99 | 99 | } | |
| 100 | 100 | ||
| 101 | - | return h.Cfg.FullPostURL(shared.NewCreateURL(h.Cfg), user.Name, post.Slug), nil | |
| 101 | + | return shared.NewCreateURL(h.Cfg.Protocol, h.Cfg.Domain).FullPostURL(user.Name, post.Slug), nil | |
| 102 | 102 | } | |
| 103 | 103 | ||
| 104 | 104 | // Rename moves a post to a new filename in place, so it keeps its ID, |
+1,
-1
| ... | ... | @@ -25,7 +25,7 @@ func StartSshServer() { | |
| 25 | 25 | host := shared.GetEnv("PROSE_HOST", "0.0.0.0") | |
| 26 | 26 | port := shared.GetEnv("PROSE_SSH_PORT", "2222") | |
| 27 | 27 | promPort := shared.GetEnv("PROSE_PROM_PORT", "9222") | |
| 28 | - | cfg := NewConfigSite(appName) | |
| 28 | + | cfg := NewConfig(appName) | |
| 29 | 29 | logger := cfg.Logger | |
| 30 | 30 | ||
| 31 | 31 | ctx, cancel := context.WithCancel(context.Background()) |
+7,
-43
| ... | ... | @@ -3,14 +3,11 @@ package prose | |
| 3 | 3 | import ( | |
| 4 | 4 | "fmt" | |
| 5 | 5 | "log/slog" | |
| 6 | - | "strings" | |
| 7 | 6 | ||
| 8 | 7 | "github.com/picosh/pico/pkg/db" | |
| 9 | 8 | "github.com/picosh/pico/pkg/filehandlers" | |
| 10 | - | uploadimgs "github.com/picosh/pico/pkg/filehandlers/imgs" | |
| 11 | 9 | "github.com/picosh/pico/pkg/pssh" | |
| 12 | 10 | sendutils "github.com/picosh/pico/pkg/send/utils" | |
| 13 | - | "github.com/picosh/pico/pkg/shared" | |
| 14 | 11 | "github.com/picosh/pico/pkg/storage" | |
| 15 | 12 | ) | |
| 16 | 13 |
| ... | ... | @@ -29,51 +26,17 @@ func setFeatureFlag(s *pssh.SSHServerConnSession, ff *db.FeatureFlag) { | |
| 29 | 26 | s.SetValue(ctxFeatureFlagKey{}, ff) | |
| 30 | 27 | } | |
| 31 | 28 | ||
| 32 | - | func setFeatureLimits(ff *db.FeatureFlag, cfg *shared.ConfigSite) { | |
| 33 | - | ff.Data.StorageMax = ff.FindStorageMax(cfg.MaxSize) | |
| 34 | - | ff.Data.FileMax = ff.FindFileMax(cfg.MaxAssetSize) | |
| 35 | - | ff.Data.SpecialFileMax = ff.FindSpecialFileMax(cfg.MaxSpecialFileSize) | |
| 36 | - | } | |
| 37 | - | ||
| 38 | - | func findFeatureFlag(dbpool DB, cfg *shared.ConfigSite, userID string) (*db.FeatureFlag, error) { | |
| 39 | - | ff, err := dbpool.FindFeature(userID, "plus") | |
| 40 | - | if err == nil { | |
| 41 | - | if ff.IsValid() { | |
| 42 | - | setFeatureLimits(ff, cfg) | |
| 43 | - | return ff, nil | |
| 44 | - | } | |
| 45 | - | err = fmt.Errorf("ERROR: your pico+ has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 46 | - | } | |
| 47 | - | ||
| 48 | - | ffProse, proseErr := dbpool.FindFeature(userID, "prose") | |
| 49 | - | if proseErr == nil { | |
| 50 | - | if ffProse.IsValid() { | |
| 51 | - | setFeatureLimits(ffProse, cfg) | |
| 52 | - | return ffProse, nil | |
| 53 | - | } | |
| 54 | - | proseErr = fmt.Errorf("ERROR: your prose access has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 55 | - | } | |
| 56 | - | ||
| 57 | - | if err != nil && strings.Contains(err.Error(), "expired") { | |
| 58 | - | return nil, err | |
| 59 | - | } | |
| 60 | - | if proseErr != nil && strings.Contains(proseErr.Error(), "expired") { | |
| 61 | - | return nil, proseErr | |
| 62 | - | } | |
| 63 | - | return nil, fmt.Errorf("ERROR: uploading to prose requires an invitation or pico+: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 64 | - | } | |
| 65 | - | ||
| 66 | 29 | type UploadHandler struct { | |
| 67 | 30 | *filehandlers.FileHandlerRouter | |
| 68 | - | Cfg *shared.ConfigSite | |
| 31 | + | Cfg *Config | |
| 69 | 32 | DB DB | |
| 70 | 33 | } | |
| 71 | 34 | ||
| 72 | 35 | var _ sendutils.CopyFromClientHandler = &UploadHandler{} | |
| 73 | 36 | var _ sendutils.CopyFromClientHandler = (*UploadHandler)(nil) | |
| 74 | 37 | ||
| 75 | - | func NewUploadHandler(cfg *shared.ConfigSite, dbpool DB, fileMap map[string]filehandlers.ReadWriteHandler) *UploadHandler { | |
| 76 | - | router := filehandlers.NewFileHandlerRouter(cfg, fileMap) | |
| 38 | + | func NewUploadHandler(cfg *Config, dbpool DB, fileMap map[string]filehandlers.ReadWriteHandler) *UploadHandler { | |
| 39 | + | router := filehandlers.NewFileHandlerRouter(cfg.Space, fileMap) | |
| 77 | 40 | return &UploadHandler{ | |
| 78 | 41 | FileHandlerRouter: router, | |
| 79 | 42 | Cfg: cfg, |
| ... | ... | @@ -82,7 +45,7 @@ func NewUploadHandler(cfg *shared.ConfigSite, dbpool DB, fileMap map[string]file | |
| 82 | 45 | } | |
| 83 | 46 | ||
| 84 | 47 | // NewFileHandler routes prose's text files to posts and the rest to images. | |
| 85 | - | func NewFileHandler(cfg *shared.ConfigSite, dbpool DB, st storage.StorageServe) *UploadHandler { | |
| 48 | + | func NewFileHandler(cfg *Config, dbpool DB, st storage.StorageServe) *UploadHandler { | |
| 86 | 49 | // One post handler serves every text extension, so a post can be | |
| 87 | 50 | // renamed in place from one to another. | |
| 88 | 51 | posts := &postUploader{Cfg: cfg, DB: dbpool} |
| ... | ... | @@ -91,7 +54,7 @@ func NewFileHandler(cfg *shared.ConfigSite, dbpool DB, st storage.StorageServe) | |
| 91 | 54 | ".txt": posts, | |
| 92 | 55 | ".css": posts, | |
| 93 | 56 | ".lxt": posts, | |
| 94 | - | "fallback": uploadimgs.NewUploadImgHandler(dbpool, cfg, st), | |
| 57 | + | "fallback": NewUploadImgHandler(dbpool, cfg, st), | |
| 95 | 58 | }) | |
| 96 | 59 | } | |
| 97 | 60 |
| ... | ... | @@ -116,10 +79,11 @@ func (h *UploadHandler) Validate(s *pssh.SSHServerConnSession) error { | |
| 116 | 79 | return err | |
| 117 | 80 | } | |
| 118 | 81 | ||
| 119 | - | ff, err := findFeatureFlag(h.DB, h.Cfg, user.ID) | |
| 82 | + | ff, err := db.FindAccess(h.DB, user.ID, "prose") | |
| 120 | 83 | if err != nil { | |
| 121 | 84 | return err | |
| 122 | 85 | } | |
| 86 | + | ff.SetLimits(h.Cfg.MaxSize, h.Cfg.MaxAssetSize, h.Cfg.MaxSpecialFileSize) | |
| 123 | 87 | setFeatureFlag(s, ff) | |
| 124 | 88 | ||
| 125 | 89 | return h.FileHandlerRouter.Validate(s) |
+2,
-2
| ... | ... | @@ -44,7 +44,7 @@ func (m *mockFeatureDB) setFeature(userID string, ff *db.FeatureFlag) { | |
| 44 | 44 | } | |
| 45 | 45 | ||
| 46 | 46 | func TestUploadHandlerValidate(t *testing.T) { | |
| 47 | - | cfg := NewConfigSite("prose-test") | |
| 47 | + | cfg := NewConfig("prose-test") | |
| 48 | 48 | validExpires := time.Now().Add(24 * time.Hour) | |
| 49 | 49 | userID := "user-1" | |
| 50 | 50 |
| ... | ... | @@ -124,7 +124,7 @@ func TestPostWriteTagsAndAliases(t *testing.T) { | |
| 124 | 124 | user := &db.User{ID: "user-1", Name: "tester"} | |
| 125 | 125 | pssh.SetUser(session, user) | |
| 126 | 126 | posts := stub.NewPostsDB(logger, user) | |
| 127 | - | cfg := NewConfigSite("prose-test") | |
| 127 | + | cfg := NewConfig("prose-test") | |
| 128 | 128 | h := &postUploader{Cfg: cfg, DB: posts} | |
| 129 | 129 | write := func(text string, mtime int64) *db.Post { | |
| 130 | 130 | t.Helper() |
+39,
-0
| ... | ... | @@ -7,6 +7,7 @@ import ( | |
| 7 | 7 | "errors" | |
| 8 | 8 | "fmt" | |
| 9 | 9 | "regexp" | |
| 10 | + | "strings" | |
| 10 | 11 | "time" | |
| 11 | 12 | ) | |
| 12 | 13 |
| ... | ... | @@ -686,6 +687,44 @@ type DB interface { | |
| 686 | 687 | Close() error | |
| 687 | 688 | } | |
| 688 | 689 | ||
| 690 | + | // SetLimits fills in the flag's storage, file and special file limits, using | |
| 691 | + | // the defaults where the flag sets none. | |
| 692 | + | func (ff *FeatureFlag) SetLimits(storageMax uint64, fileMax, specialFileMax int64) { | |
| 693 | + | ff.Data.StorageMax = ff.FindStorageMax(storageMax) | |
| 694 | + | ff.Data.FileMax = ff.FindFileMax(fileMax) | |
| 695 | + | ff.Data.SpecialFileMax = ff.FindSpecialFileMax(specialFileMax) | |
| 696 | + | } | |
| 697 | + | ||
| 698 | + | // FindAccess returns the flag that lets a user use a service: pico+, or the | |
| 699 | + | // service's own feature. The error says why a user has neither. | |
| 700 | + | func FindAccess(dbpool interface { | |
| 701 | + | FindFeature(userID string, feature string) (*FeatureFlag, error) | |
| 702 | + | }, userID, service string) (*FeatureFlag, error) { | |
| 703 | + | ff, err := dbpool.FindFeature(userID, "plus") | |
| 704 | + | if err == nil { | |
| 705 | + | if ff.IsValid() { | |
| 706 | + | return ff, nil | |
| 707 | + | } | |
| 708 | + | err = fmt.Errorf("ERROR: your pico+ has expired: https://blog.pico.sh/ann-038-pico-invite-system") | |
| 709 | + | } | |
| 710 | + | ||
| 711 | + | ffService, serviceErr := dbpool.FindFeature(userID, service) | |
| 712 | + | if serviceErr == nil { | |
| 713 | + | if ffService.IsValid() { | |
| 714 | + | return ffService, nil | |
| 715 | + | } | |
| 716 | + | serviceErr = fmt.Errorf("ERROR: your %s access has expired: https://blog.pico.sh/ann-038-pico-invite-system", service) | |
| 717 | + | } | |
| 718 | + | ||
| 719 | + | if err != nil && strings.Contains(err.Error(), "expired") { | |
| 720 | + | return nil, err | |
| 721 | + | } | |
| 722 | + | if serviceErr != nil && strings.Contains(serviceErr.Error(), "expired") { | |
| 723 | + | return nil, serviceErr | |
| 724 | + | } | |
| 725 | + | return nil, fmt.Errorf("ERROR: uploading to %s requires an invitation or pico+: https://blog.pico.sh/ann-038-pico-invite-system", service) | |
| 726 | + | } | |
| 727 | + | ||
| 689 | 728 | func HasPlusOrSpace(dbpool interface { | |
| 690 | 729 | HasFeatureByUser(userID string, feature string) bool | |
| 691 | 730 | }, userID, space string) bool { |
+1,
-2
| ... | ... | @@ -15,7 +15,6 @@ import ( | |
| 15 | 15 | "github.com/picosh/pico/pkg/db/stub" | |
| 16 | 16 | "github.com/picosh/pico/pkg/pssh" | |
| 17 | 17 | sendutils "github.com/picosh/pico/pkg/send/utils" | |
| 18 | - | "github.com/picosh/pico/pkg/shared" | |
| 19 | 18 | "golang.org/x/crypto/ssh" | |
| 20 | 19 | ) | |
| 21 | 20 |
| ... | ... | @@ -140,7 +139,7 @@ func (otherHandler) List(*pssh.SSHServerConnSession, string, bool, bool) ([]os.F | |
| 140 | 139 | func TestRouterSharedHandler(t *testing.T) { | |
| 141 | 140 | session, posts := newPostsSession(t) | |
| 142 | 141 | postHandler := &postsHandler{db: posts} | |
| 143 | - | router := NewFileHandlerRouter(&shared.ConfigSite{Space: "prose"}, map[string]ReadWriteHandler{ | |
| 142 | + | router := NewFileHandlerRouter("prose", map[string]ReadWriteHandler{ | |
| 144 | 143 | ".md": postHandler, | |
| 145 | 144 | ".lxt": postHandler, | |
| 146 | 145 | ".txt": &postsHandler{db: posts}, |
+4,
-5
| ... | ... | @@ -11,7 +11,6 @@ import ( | |
| 11 | 11 | "github.com/picosh/pico/pkg/db" | |
| 12 | 12 | "github.com/picosh/pico/pkg/pssh" | |
| 13 | 13 | "github.com/picosh/pico/pkg/send/utils" | |
| 14 | - | "github.com/picosh/pico/pkg/shared" | |
| 15 | 14 | ) | |
| 16 | 15 | ||
| 17 | 16 | type ReadWriteHandler interface { |
| ... | ... | @@ -23,15 +22,15 @@ type ReadWriteHandler interface { | |
| 23 | 22 | ||
| 24 | 23 | type FileHandlerRouter struct { | |
| 25 | 24 | FileMap map[string]ReadWriteHandler | |
| 26 | - | Cfg *shared.ConfigSite | |
| 25 | + | Space string | |
| 27 | 26 | } | |
| 28 | 27 | ||
| 29 | 28 | var _ utils.CopyFromClientHandler = &FileHandlerRouter{} // Verify implementation | |
| 30 | 29 | var _ utils.CopyFromClientHandler = (*FileHandlerRouter)(nil) // Verify implementation | |
| 31 | 30 | ||
| 32 | - | func NewFileHandlerRouter(cfg *shared.ConfigSite, mapper map[string]ReadWriteHandler) *FileHandlerRouter { | |
| 31 | + | func NewFileHandlerRouter(space string, mapper map[string]ReadWriteHandler) *FileHandlerRouter { | |
| 33 | 32 | return &FileHandlerRouter{ | |
| 34 | - | Cfg: cfg, | |
| 33 | + | Space: space, | |
| 35 | 34 | FileMap: mapper, | |
| 36 | 35 | } | |
| 37 | 36 | } |
| ... | ... | @@ -150,7 +149,7 @@ func (r *FileHandlerRouter) Validate(s *pssh.SSHServerConnSession) error { | |
| 150 | 149 | logger.Info( | |
| 151 | 150 | "attempting to upload files", | |
| 152 | 151 | "user", user.Name, | |
| 153 | - | "space", r.Cfg.Space, | |
| 152 | + | "space", r.Space, | |
| 154 | 153 | ) | |
| 155 | 154 | return nil | |
| 156 | 155 | } |
+8,
-5
| ... | ... | @@ -50,24 +50,27 @@ func newPostsEnv(t *testing.T, app string) *postsEnv { | |
| 50 | 50 | posts := stub.NewPostsDB(logger, &db.User{ID: "user-1", Name: "tester"}) | |
| 51 | 51 | posts.Pubkey = shared.KeyForKeyText(signer.PublicKey()) | |
| 52 | 52 | ||
| 53 | - | var cfg *shared.ConfigSite | |
| 53 | + | var space string | |
| 54 | 54 | var handler interface { | |
| 55 | 55 | utils.CopyFromClientHandler | |
| 56 | 56 | pssh.GetLoggerInterface | |
| 57 | 57 | } | |
| 58 | 58 | switch app { | |
| 59 | 59 | case "prose": | |
| 60 | - | cfg = prose.NewConfigSite("prose-test") | |
| 60 | + | cfg := prose.NewConfig("prose-test") | |
| 61 | + | cfg.Logger = logger | |
| 61 | 62 | st, err := storage.NewStorageMemory(map[string]map[string]string{}) | |
| 62 | 63 | if err != nil { | |
| 63 | 64 | t.Fatal(err) | |
| 64 | 65 | } | |
| 65 | 66 | handler = prose.NewFileHandler(cfg, posts, st) | |
| 67 | + | space = cfg.Space | |
| 66 | 68 | case "pastes": | |
| 67 | - | cfg = pastes.NewConfigSite("pastes-test") | |
| 69 | + | cfg := pastes.NewConfig("pastes-test") | |
| 70 | + | cfg.Logger = logger | |
| 68 | 71 | handler = pastes.NewUploadHandler(cfg, posts) | |
| 72 | + | space = cfg.Space | |
| 69 | 73 | } | |
| 70 | - | cfg.Logger = logger | |
| 71 | 74 | ||
| 72 | 75 | ctx, cancel := context.WithCancel(context.Background()) | |
| 73 | 76 | t.Cleanup(cancel) |
| ... | ... | @@ -107,7 +110,7 @@ func newPostsEnv(t *testing.T, app string) *postsEnv { | |
| 107 | 110 | if err := os.WriteFile(key, pem.EncodeToMemory(b), 0o600); err != nil { | |
| 108 | 111 | t.Fatal(err) | |
| 109 | 112 | } | |
| 110 | - | return &postsEnv{t: t, db: posts, space: cfg.Space, port: port, key: key} | |
| 113 | + | return &postsEnv{t: t, db: posts, space: space, port: port, key: key} | |
| 111 | 114 | } | |
| 112 | 115 | ||
| 113 | 116 | func (e *postsEnv) sshOpts() []string { |
| ... | ... | @@ -8,7 +8,6 @@ import ( | |
| 8 | 8 | "net/http" | |
| 9 | 9 | "net/url" | |
| 10 | 10 | "os" | |
| 11 | - | "path" | |
| 12 | 11 | "strings" | |
| 13 | 12 | "time" | |
| 14 | 13 |
| ... | ... | @@ -28,169 +27,72 @@ type PageData struct { | |
| 28 | 27 | Site SitePageData | |
| 29 | 28 | } | |
| 30 | 29 | ||
| 31 | - | type ConfigSite struct { | |
| 32 | - | Debug bool | |
| 33 | - | SendgridKey string | |
| 34 | - | Domain string | |
| 35 | - | Port string | |
| 36 | - | PortOverride string | |
| 37 | - | Protocol string | |
| 38 | - | DbURL string | |
| 39 | - | Space string | |
| 40 | - | Issuer string | |
| 41 | - | Secret string | |
| 42 | - | SecretWebhook string | |
| 43 | - | AllowedExt []string | |
| 44 | - | HiddenPosts []string | |
| 45 | - | MaxSize uint64 | |
| 46 | - | MaxAssetSize int64 | |
| 47 | - | MaxSpecialFileSize int64 | |
| 48 | - | Logger *slog.Logger | |
| 49 | - | TunsSecret string | |
| 50 | - | } | |
| 51 | - | ||
| 52 | - | func NewConfigSite() *ConfigSite { | |
| 53 | - | return &ConfigSite{} | |
| 54 | - | } | |
| 55 | - | ||
| 30 | + | // CreateURL builds links to users' sites on Domain, as seen from the host a | |
| 31 | + | // request came in on. | |
| 56 | 32 | type CreateURL struct { | |
| 33 | + | Protocol string | |
| 34 | + | Domain string | |
| 57 | 35 | Subdomain bool | |
| 58 | 36 | UsernameInRoute bool | |
| 59 | 37 | HostDomain string | |
| 60 | - | AppDomain string | |
| 61 | - | Username string | |
| 62 | - | Cfg *ConfigSite | |
| 63 | 38 | } | |
| 64 | 39 | ||
| 65 | - | func NewCreateURL(cfg *ConfigSite) *CreateURL { | |
| 40 | + | // NewCreateURL builds links that point at users' subdomains. | |
| 41 | + | func NewCreateURL(protocol, domain string) *CreateURL { | |
| 66 | 42 | return &CreateURL{ | |
| 67 | - | Cfg: cfg, | |
| 68 | - | Subdomain: cfg.IsSubdomains(), | |
| 43 | + | Protocol: protocol, | |
| 44 | + | Domain: domain, | |
| 45 | + | Subdomain: true, | |
| 69 | 46 | } | |
| 70 | 47 | } | |
| 71 | 48 | ||
| 72 | - | func CreateURLFromRequest(cfg *ConfigSite, r *http.Request) *CreateURL { | |
| 49 | + | func CreateURLFromRequest(protocol, domain string, r *http.Request) *CreateURL { | |
| 73 | 50 | hostDomain := strings.Split(r.Host, ":")[0] | |
| 74 | - | appDomain := strings.Split(cfg.Domain, ":")[0] | |
| 51 | + | appDomain := strings.Split(domain, ":")[0] | |
| 75 | 52 | ||
| 76 | - | onSubdomain := cfg.IsSubdomains() && strings.Contains(hostDomain, appDomain) | |
| 77 | - | withUserName := !cfg.IsCustomdomains() || (!onSubdomain && hostDomain == appDomain) | |
| 53 | + | onSubdomain := strings.Contains(hostDomain, appDomain) | |
| 54 | + | withUserName := !onSubdomain && hostDomain == appDomain | |
| 78 | 55 | ||
| 79 | 56 | return &CreateURL{ | |
| 80 | - | Cfg: cfg, | |
| 81 | - | AppDomain: appDomain, | |
| 57 | + | Protocol: protocol, | |
| 58 | + | Domain: domain, | |
| 82 | 59 | HostDomain: hostDomain, | |
| 83 | 60 | Subdomain: onSubdomain, | |
| 84 | 61 | UsernameInRoute: withUserName, | |
| 85 | 62 | } | |
| 86 | 63 | } | |
| 87 | 64 | ||
| 88 | - | func (c *ConfigSite) GetSiteData() *SitePageData { | |
| 89 | - | return &SitePageData{ | |
| 90 | - | Domain: template.URL(c.Domain), | |
| 91 | - | HomeURL: template.URL(c.HomeURL()), | |
| 92 | - | } | |
| 93 | - | } | |
| 94 | - | ||
| 95 | - | func (c *ConfigSite) IsSubdomains() bool { | |
| 96 | - | return true | |
| 97 | - | } | |
| 98 | - | ||
| 99 | - | func (c *ConfigSite) IsCustomdomains() bool { | |
| 100 | - | return true | |
| 101 | - | } | |
| 102 | - | ||
| 103 | - | func (c *ConfigSite) HomeURL() string { | |
| 104 | - | if c.IsSubdomains() || c.IsCustomdomains() { | |
| 105 | - | return fmt.Sprintf("//%s", c.Domain) | |
| 106 | - | } | |
| 107 | - | ||
| 108 | - | return "/" | |
| 109 | - | } | |
| 110 | - | ||
| 111 | - | func (c *ConfigSite) ReadURL() string { | |
| 112 | - | if c.IsSubdomains() || c.IsCustomdomains() { | |
| 113 | - | return fmt.Sprintf("%s://%s", c.Protocol, c.Domain) | |
| 114 | - | } | |
| 115 | - | ||
| 116 | - | return "/" | |
| 117 | - | } | |
| 118 | - | ||
| 119 | - | func (c *ConfigSite) StaticPath(fname string) string { | |
| 120 | - | return path.Join("pkg", "apps", c.Space, fname) | |
| 121 | - | } | |
| 122 | - | ||
| 123 | - | func (c *ConfigSite) BlogURL(username string) string { | |
| 124 | - | if c.IsSubdomains() { | |
| 125 | - | return fmt.Sprintf("%s://%s.%s", c.Protocol, username, c.Domain) | |
| 126 | - | } | |
| 127 | - | ||
| 128 | - | return fmt.Sprintf("/%s", username) | |
| 129 | - | } | |
| 130 | - | ||
| 131 | - | func (c *ConfigSite) CssURL(username string) string { | |
| 132 | - | if c.IsSubdomains() || c.IsCustomdomains() { | |
| 133 | - | return "/_styles.css" | |
| 134 | - | } | |
| 135 | - | ||
| 136 | - | return fmt.Sprintf("/%s/styles.css", username) | |
| 137 | - | } | |
| 138 | - | ||
| 139 | - | func (c *ConfigSite) PostURL(username, slug string) string { | |
| 140 | - | fname := url.PathEscape(slug) | |
| 141 | - | if c.IsSubdomains() { | |
| 142 | - | return fmt.Sprintf("%s://%s.%s/%s", c.Protocol, username, c.Domain, fname) | |
| 143 | - | } | |
| 144 | - | ||
| 145 | - | return fmt.Sprintf("/%s/%s", username, fname) | |
| 146 | - | ||
| 147 | - | } | |
| 148 | - | ||
| 149 | - | func (c *ConfigSite) RawPostURL(username, slug string) string { | |
| 150 | - | fname := url.PathEscape(slug) | |
| 151 | - | if c.IsSubdomains() { | |
| 152 | - | return fmt.Sprintf("%s://%s.%s/raw/%s", c.Protocol, username, c.Domain, fname) | |
| 153 | - | } | |
| 154 | - | ||
| 155 | - | return fmt.Sprintf("/raw/%s/%s", username, fname) | |
| 156 | - | } | |
| 157 | - | ||
| 158 | - | func (c *ConfigSite) ImgFullURL(username, slug string) string { | |
| 159 | - | fname := url.PathEscape(strings.TrimLeft(slug, "/")) | |
| 160 | - | return fmt.Sprintf("%s://%s.%s/%s", c.Protocol, username, c.Domain, fname) | |
| 161 | - | } | |
| 162 | - | ||
| 163 | - | func (c *ConfigSite) FullBlogURL(curl *CreateURL, username string) string { | |
| 164 | - | if c.IsSubdomains() && curl.Subdomain { | |
| 65 | + | func (c *CreateURL) FullBlogURL(username string) string { | |
| 66 | + | if c.Subdomain { | |
| 165 | 67 | return fmt.Sprintf("%s://%s.%s", c.Protocol, username, c.Domain) | |
| 166 | 68 | } | |
| 167 | 69 | ||
| 168 | - | if curl.UsernameInRoute { | |
| 70 | + | if c.UsernameInRoute { | |
| 169 | 71 | return fmt.Sprintf("/%s", username) | |
| 170 | 72 | } | |
| 171 | 73 | ||
| 172 | - | return fmt.Sprintf("%s://%s", c.Protocol, curl.HostDomain) | |
| 74 | + | return fmt.Sprintf("%s://%s", c.Protocol, c.HostDomain) | |
| 173 | 75 | } | |
| 174 | 76 | ||
| 175 | - | func (c *ConfigSite) FullPostURL(curl *CreateURL, username, slug string) string { | |
| 77 | + | func (c *CreateURL) FullPostURL(username, slug string) string { | |
| 176 | 78 | fname := url.PathEscape(strings.TrimLeft(slug, "/")) | |
| 177 | 79 | ||
| 178 | - | if curl.Subdomain && c.IsSubdomains() { | |
| 80 | + | if c.Subdomain { | |
| 179 | 81 | return fmt.Sprintf("%s://%s.%s/%s", c.Protocol, username, c.Domain, fname) | |
| 180 | 82 | } | |
| 181 | 83 | ||
| 182 | - | if curl.UsernameInRoute { | |
| 84 | + | if c.UsernameInRoute { | |
| 183 | 85 | return fmt.Sprintf("%s://%s/%s/%s", c.Protocol, c.Domain, username, fname) | |
| 184 | 86 | } | |
| 185 | 87 | ||
| 186 | - | return fmt.Sprintf("%s://%s/%s", c.Protocol, curl.HostDomain, fname) | |
| 88 | + | return fmt.Sprintf("%s://%s/%s", c.Protocol, c.HostDomain, fname) | |
| 187 | 89 | } | |
| 188 | 90 | ||
| 189 | - | func (c *ConfigSite) RssBlogURL(curl *CreateURL, username, tag string) string { | |
| 91 | + | func (c *CreateURL) RssBlogURL(username, tag string) string { | |
| 190 | 92 | url := "" | |
| 191 | - | if c.IsSubdomains() && curl.Subdomain { | |
| 93 | + | if c.Subdomain { | |
| 192 | 94 | url = fmt.Sprintf("%s://%s.%s/rss", c.Protocol, username, c.Domain) | |
| 193 | - | } else if curl.UsernameInRoute { | |
| 95 | + | } else if c.UsernameInRoute { | |
| 194 | 96 | url = fmt.Sprintf("/%s/rss", username) | |
| 195 | 97 | } else { | |
| 196 | 98 | url = "/rss" |
| ... | ... | @@ -203,71 +105,6 @@ func (c *ConfigSite) RssBlogURL(curl *CreateURL, username, tag string) string { | |
| 203 | 105 | return url | |
| 204 | 106 | } | |
| 205 | 107 | ||
| 206 | - | func (c *ConfigSite) ImgURL(curl *CreateURL, username string, slug string) string { | |
| 207 | - | fname := url.PathEscape(strings.TrimLeft(slug, "/")) | |
| 208 | - | if c.IsSubdomains() && curl.Subdomain { | |
| 209 | - | return fmt.Sprintf("%s://%s.%s/%s", c.Protocol, username, c.Domain, fname) | |
| 210 | - | } | |
| 211 | - | ||
| 212 | - | if curl.UsernameInRoute { | |
| 213 | - | return fmt.Sprintf("/%s/%s", username, fname) | |
| 214 | - | } | |
| 215 | - | ||
| 216 | - | return fmt.Sprintf("/%s", fname) | |
| 217 | - | } | |
| 218 | - | ||
| 219 | - | func (c *ConfigSite) ImgPostURL(curl *CreateURL, username string, slug string) string { | |
| 220 | - | fname := url.PathEscape(strings.TrimLeft(slug, "/")) | |
| 221 | - | if c.IsSubdomains() && curl.Subdomain { | |
| 222 | - | return fmt.Sprintf("%s://%s.%s/p/%s", c.Protocol, username, c.Domain, fname) | |
| 223 | - | } | |
| 224 | - | ||
| 225 | - | if curl.UsernameInRoute { | |
| 226 | - | return fmt.Sprintf("/%s/p/%s", username, fname) | |
| 227 | - | } | |
| 228 | - | ||
| 229 | - | return fmt.Sprintf("/p/%s", fname) | |
| 230 | - | } | |
| 231 | - | ||
| 232 | - | func (c *ConfigSite) ImgOrigURL(curl *CreateURL, username string, slug string) string { | |
| 233 | - | fname := url.PathEscape(strings.TrimLeft(slug, "/")) | |
| 234 | - | if c.IsSubdomains() && curl.Subdomain { | |
| 235 | - | return fmt.Sprintf("%s://%s.%s/o/%s", c.Protocol, username, c.Domain, fname) | |
| 236 | - | } | |
| 237 | - | ||
| 238 | - | if curl.UsernameInRoute { | |
| 239 | - | return fmt.Sprintf("/%s/o/%s", username, fname) | |
| 240 | - | } | |
| 241 | - | ||
| 242 | - | return fmt.Sprintf("/o/%s", fname) | |
| 243 | - | } | |
| 244 | - | ||
| 245 | - | func (c *ConfigSite) TagURL(curl *CreateURL, username, tag string) string { | |
| 246 | - | tg := url.PathEscape(tag) | |
| 247 | - | return fmt.Sprintf("%s?tag=%s", c.FullBlogURL(curl, username), tg) | |
| 248 | - | } | |
| 249 | - | ||
| 250 | - | func (c *ConfigSite) AssetURL(username, projectName, fpath string) string { | |
| 251 | - | if username == projectName { | |
| 252 | - | return fmt.Sprintf( | |
| 253 | - | "%s://%s.%s/%s", | |
| 254 | - | c.Protocol, | |
| 255 | - | username, | |
| 256 | - | c.Domain, | |
| 257 | - | fpath, | |
| 258 | - | ) | |
| 259 | - | } | |
| 260 | - | ||
| 261 | - | return fmt.Sprintf( | |
| 262 | - | "%s://%s-%s.%s/%s", | |
| 263 | - | c.Protocol, | |
| 264 | - | username, | |
| 265 | - | projectName, | |
| 266 | - | c.Domain, | |
| 267 | - | fpath, | |
| 268 | - | ) | |
| 269 | - | } | |
| 270 | - | ||
| 271 | 108 | func CreateLogger(space string, withPipe bool) *slog.Logger { | |
| 272 | 109 | logger := slog.New( | |
| 273 | 110 | slog.NewTextHandler( |
| ... | ... | @@ -1,10 +1,11 @@ | |
| 1 | 1 | package router | |
| 2 | 2 | ||
| 3 | 3 | import ( | |
| 4 | - | "fmt" | |
| 5 | 4 | "html/template" | |
| 5 | + | "log/slog" | |
| 6 | 6 | "net/http" | |
| 7 | 7 | "os" | |
| 8 | + | "path/filepath" | |
| 8 | 9 | "strings" | |
| 9 | 10 | ||
| 10 | 11 | "github.com/picosh/pico/pkg/db" |
| ... | ... | @@ -41,23 +42,22 @@ func UnauthorizedHandler(w http.ResponseWriter, r *http.Request) { | |
| 41 | 42 | http.Error(w, "You do not have access to this site", http.StatusUnauthorized) | |
| 42 | 43 | } | |
| 43 | 44 | ||
| 44 | - | // CheckHandler reports whether a custom domain points at a user's site. | |
| 45 | - | func CheckHandler(cfg *shared.ConfigSite, users interface { | |
| 45 | + | // CheckHandler reports whether a custom domain points at a user's site on | |
| 46 | + | // domain, through its TXT record for txtPrefix. | |
| 47 | + | func CheckHandler(domain, txtPrefix string, users interface { | |
| 46 | 48 | FindUserByName(name string) (*db.User, error) | |
| 47 | 49 | }) http.HandlerFunc { | |
| 48 | 50 | return func(w http.ResponseWriter, r *http.Request) { | |
| 49 | - | if cfg.IsCustomdomains() { | |
| 50 | - | hostDomain := r.URL.Query().Get("domain") | |
| 51 | - | appDomain := strings.Split(cfg.Domain, ":")[0] | |
| 52 | - | ||
| 53 | - | if !strings.Contains(hostDomain, appDomain) { | |
| 54 | - | subdomain := GetCustomDomain(hostDomain, cfg.Space) | |
| 55 | - | if subdomain != "" { | |
| 56 | - | u, err := users.FindUserByName(subdomain) | |
| 57 | - | if u != nil && err == nil { | |
| 58 | - | w.WriteHeader(http.StatusOK) | |
| 59 | - | return | |
| 60 | - | } | |
| 51 | + | hostDomain := r.URL.Query().Get("domain") | |
| 52 | + | appDomain := strings.Split(domain, ":")[0] | |
| 53 | + | ||
| 54 | + | if !strings.Contains(hostDomain, appDomain) { | |
| 55 | + | subdomain := GetCustomDomain(hostDomain, txtPrefix) | |
| 56 | + | if subdomain != "" { | |
| 57 | + | u, err := users.FindUserByName(subdomain) | |
| 58 | + | if u != nil && err == nil { | |
| 59 | + | w.WriteHeader(http.StatusOK) | |
| 60 | + | return | |
| 61 | 61 | } | |
| 62 | 62 | } | |
| 63 | 63 | } |
| ... | ... | @@ -68,31 +68,11 @@ func CheckHandler(cfg *shared.ConfigSite, users interface { | |
| 68 | 68 | ||
| 69 | 69 | // GetUsernameFromRequest is the user whose site a request is for: the | |
| 70 | 70 | // subdomain, or the path's {user} on the main domain. | |
| 71 | - | func GetUsernameFromRequest(r *http.Request, cfg *shared.ConfigSite) string { | |
| 72 | - | subdomain := GetSubdomain(r) | |
| 73 | - | if !cfg.IsSubdomains() || subdomain == "" { | |
| 74 | - | return r.PathValue("user") | |
| 75 | - | } | |
| 76 | - | return subdomain | |
| 77 | - | } | |
| 78 | - | ||
| 79 | - | func ServeFile(cfg *shared.ConfigSite, file string, contentType string) http.HandlerFunc { | |
| 80 | - | return func(w http.ResponseWriter, r *http.Request) { | |
| 81 | - | logger := cfg.Logger | |
| 82 | - | ||
| 83 | - | contents, err := os.ReadFile(cfg.StaticPath(fmt.Sprintf("public/%s", file))) | |
| 84 | - | if err != nil { | |
| 85 | - | logger.Error(err.Error()) | |
| 86 | - | http.Error(w, "file not found", 404) | |
| 87 | - | } | |
| 88 | - | ||
| 89 | - | w.Header().Add("Content-Type", contentType) | |
| 90 | - | ||
| 91 | - | _, err = w.Write(contents) | |
| 92 | - | if err != nil { | |
| 93 | - | logger.Error(err.Error()) | |
| 94 | - | } | |
| 71 | + | func GetUsernameFromRequest(r *http.Request) string { | |
| 72 | + | if subdomain := GetSubdomain(r); subdomain != "" { | |
| 73 | + | return subdomain | |
| 95 | 74 | } | |
| 75 | + | return r.PathValue("user") | |
| 96 | 76 | } | |
| 97 | 77 | ||
| 98 | 78 | func minus(a, b int) int { |
| ... | ... | @@ -113,14 +93,16 @@ var FuncMap = template.FuncMap{ | |
| 113 | 93 | "intRange": intRange, | |
| 114 | 94 | } | |
| 115 | 95 | ||
| 116 | - | func RenderTemplate(cfg *shared.ConfigSite, templates []string) (*template.Template, error) { | |
| 96 | + | // RenderTemplate parses templates with the layout and footers in an app's | |
| 97 | + | // dir. | |
| 98 | + | func RenderTemplate(dir string, templates []string) (*template.Template, error) { | |
| 117 | 99 | files := make([]string, len(templates)) | |
| 118 | 100 | copy(files, templates) | |
| 119 | 101 | files = append( | |
| 120 | 102 | files, | |
| 121 | - | cfg.StaticPath("html/footer.partial.tmpl"), | |
| 122 | - | cfg.StaticPath("html/marketing-footer.partial.tmpl"), | |
| 123 | - | cfg.StaticPath("html/base.layout.tmpl"), | |
| 103 | + | filepath.Join(dir, "html/footer.partial.tmpl"), | |
| 104 | + | filepath.Join(dir, "html/marketing-footer.partial.tmpl"), | |
| 105 | + | filepath.Join(dir, "html/base.layout.tmpl"), | |
| 124 | 106 | ) | |
| 125 | 107 | ||
| 126 | 108 | ts, err := template.New("base").Funcs(FuncMap).ParseFiles(files...) |
| ... | ... | @@ -130,23 +112,45 @@ func RenderTemplate(cfg *shared.ConfigSite, templates []string) (*template.Templ | |
| 130 | 112 | return ts, nil | |
| 131 | 113 | } | |
| 132 | 114 | ||
| 133 | - | func CreatePageHandler(cfg *shared.ConfigSite, fname string) http.HandlerFunc { | |
| 115 | + | // Static serves an app's files from Dir/public and its pages from Dir/html. | |
| 116 | + | type Static struct { | |
| 117 | + | Dir string | |
| 118 | + | Logger *slog.Logger | |
| 119 | + | Site shared.SitePageData | |
| 120 | + | } | |
| 121 | + | ||
| 122 | + | // File serves the file name in Dir/public. | |
| 123 | + | func (s Static) File(name string, contentType string) http.HandlerFunc { | |
| 134 | 124 | return func(w http.ResponseWriter, r *http.Request) { | |
| 135 | - | logger := cfg.Logger | |
| 136 | - | ts, err := RenderTemplate(cfg, []string{cfg.StaticPath(fname)}) | |
| 125 | + | contents, err := os.ReadFile(filepath.Join(s.Dir, "public", name)) | |
| 126 | + | if err != nil { | |
| 127 | + | s.Logger.Error("could not read file", "fname", name, "err", err.Error()) | |
| 128 | + | http.Error(w, "file not found", http.StatusNotFound) | |
| 129 | + | return | |
| 130 | + | } | |
| 131 | + | ||
| 132 | + | w.Header().Add("Content-Type", contentType) | |
| 133 | + | ||
| 134 | + | _, err = w.Write(contents) | |
| 135 | + | if err != nil { | |
| 136 | + | s.Logger.Error("could not write http response", "file", name, "err", err.Error()) | |
| 137 | + | } | |
| 138 | + | } | |
| 139 | + | } | |
| 137 | 140 | ||
| 141 | + | // Page renders the template fname in Dir with the site's data. | |
| 142 | + | func (s Static) Page(fname string) http.HandlerFunc { | |
| 143 | + | return func(w http.ResponseWriter, r *http.Request) { | |
| 144 | + | ts, err := RenderTemplate(s.Dir, []string{filepath.Join(s.Dir, fname)}) | |
| 138 | 145 | if err != nil { | |
| 139 | - | logger.Error(err.Error()) | |
| 146 | + | s.Logger.Error("could not render template", "fname", fname, "err", err.Error()) | |
| 140 | 147 | http.Error(w, err.Error(), http.StatusInternalServerError) | |
| 141 | 148 | return | |
| 142 | 149 | } | |
| 143 | 150 | ||
| 144 | - | data := shared.PageData{ | |
| 145 | - | Site: *cfg.GetSiteData(), | |
| 146 | - | } | |
| 147 | - | err = ts.Execute(w, data) | |
| 151 | + | err = ts.Execute(w, shared.PageData{Site: s.Site}) | |
| 148 | 152 | if err != nil { | |
| 149 | - | logger.Error(err.Error()) | |
| 153 | + | s.Logger.Error("could not execute template", "fname", fname, "err", err.Error()) | |
| 150 | 154 | http.Error(w, err.Error(), http.StatusInternalServerError) | |
| 151 | 155 | } | |
| 152 | 156 | } |
| ... | ... | @@ -56,30 +56,35 @@ func GetSubdomainFromRequest(r *http.Request, domain, space string) string { | |
| 56 | 56 | return "" | |
| 57 | 57 | } | |
| 58 | 58 | ||
| 59 | - | // NewHostRouter serves requests for users' sites, on subdomains and custom | |
| 60 | - | // domains, with sites, and the rest with main. GetSubdomain returns the | |
| 61 | - | // site's name. A nil sites serves everything with main. | |
| 62 | - | func NewHostRouter(cfg *shared.ConfigSite, main, sites http.Handler) http.Handler { | |
| 59 | + | // NewHostRouter serves requests for users' sites with sites, and the rest | |
| 60 | + | // with main. A site is a subdomain of domain, or a custom domain whose TXT | |
| 61 | + | // record for txtPrefix names one. GetSubdomain returns the site's name. A | |
| 62 | + | // nil sites serves everything with main. | |
| 63 | + | func NewHostRouter(domain, txtPrefix string, main, sites http.Handler) http.Handler { | |
| 63 | 64 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 64 | 65 | if sites == nil { | |
| 65 | 66 | main.ServeHTTP(w, r) | |
| 66 | 67 | return | |
| 67 | 68 | } | |
| 68 | - | subdomain := GetSubdomainFromRequest(r, cfg.Domain, cfg.Space) | |
| 69 | + | subdomain := GetSubdomainFromRequest(r, domain, txtPrefix) | |
| 69 | 70 | if subdomain == "" { | |
| 70 | 71 | main.ServeHTTP(w, r) | |
| 71 | 72 | return | |
| 72 | 73 | } | |
| 73 | - | ctx := context.WithValue(r.Context(), CtxSubdomainKey{}, subdomain) | |
| 74 | - | sites.ServeHTTP(w, r.WithContext(ctx)) | |
| 74 | + | sites.ServeHTTP(w, r.WithContext(WithSubdomain(r.Context(), subdomain))) | |
| 75 | 75 | }) | |
| 76 | 76 | } | |
| 77 | 77 | ||
| 78 | - | type CtxSubdomainKey struct{} | |
| 78 | + | type ctxSubdomainKey struct{} | |
| 79 | + | ||
| 80 | + | // WithSubdomain marks ctx as a request for the site subdomain. | |
| 81 | + | func WithSubdomain(ctx context.Context, subdomain string) context.Context { | |
| 82 | + | return context.WithValue(ctx, ctxSubdomainKey{}, subdomain) | |
| 83 | + | } | |
| 79 | 84 | ||
| 80 | 85 | // GetSubdomain is the site a request is for, or "" for the main domain. | |
| 81 | 86 | func GetSubdomain(r *http.Request) string { | |
| 82 | - | subdomain, _ := r.Context().Value(CtxSubdomainKey{}).(string) | |
| 87 | + | subdomain, _ := r.Context().Value(ctxSubdomainKey{}).(string) | |
| 83 | 88 | return subdomain | |
| 84 | 89 | } | |
| 85 | 90 |
| ... | ... | @@ -6,8 +6,6 @@ import ( | |
| 6 | 6 | "net/http" | |
| 7 | 7 | "net/http/httptest" | |
| 8 | 8 | "testing" | |
| 9 | - | ||
| 10 | - | "github.com/picosh/pico/pkg/shared" | |
| 11 | 9 | ) | |
| 12 | 10 | ||
| 13 | 11 | func TestGetCustomDomainCachesMisses(t *testing.T) { |
| ... | ... | @@ -56,7 +54,6 @@ func TestGetCustomDomainCachesMisses(t *testing.T) { | |
| 56 | 54 | } | |
| 57 | 55 | ||
| 58 | 56 | func TestNewHostRouter(t *testing.T) { | |
| 59 | - | cfg := &shared.ConfigSite{Domain: "pico.test", Space: "prose"} | |
| 60 | 57 | serve := func(name string) http.Handler { | |
| 61 | 58 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 62 | 59 | _, _ = w.Write([]byte(name + ":" + GetSubdomain(r))) |
| ... | ... | @@ -68,14 +65,14 @@ func TestNewHostRouter(t *testing.T) { | |
| 68 | 65 | return res.Body.String() | |
| 69 | 66 | } | |
| 70 | 67 | ||
| 71 | - | h := NewHostRouter(cfg, serve("main"), serve("sites")) | |
| 68 | + | h := NewHostRouter("pico.test", "prose", serve("main"), serve("sites")) | |
| 72 | 69 | if got := get(h, "https://pico.test/"); got != "main:" { | |
| 73 | 70 | t.Errorf("main domain = %q", got) | |
| 74 | 71 | } | |
| 75 | 72 | if got := get(h, "https://tester.pico.test/"); got != "sites:tester" { | |
| 76 | 73 | t.Errorf("subdomain = %q", got) | |
| 77 | 74 | } | |
| 78 | - | if got := get(NewHostRouter(cfg, serve("main"), nil), "https://tester.pico.test/"); got != "main:" { | |
| 75 | + | if got := get(NewHostRouter("pico.test", "prose", serve("main"), nil), "https://tester.pico.test/"); got != "main:" { | |
| 79 | 76 | t.Errorf("subdomain without sites = %q", got) | |
| 80 | 77 | } | |
| 81 | 78 | } |
| ... | ... | @@ -150,27 +150,3 @@ func (r *SshAuthHandler) PubkeyAuthHandler(conn ssh.ConnMetadata, key ssh.Public | |
| 150 | 150 | ||
| 151 | 151 | return perms, nil | |
| 152 | 152 | } | |
| 153 | - | ||
| 154 | - | type FeatureFinder interface { | |
| 155 | - | FindFeature(userID string, feature string) (*db.FeatureFlag, error) | |
| 156 | - | } | |
| 157 | - | ||
| 158 | - | func FindPlusFF(dbpool FeatureFinder, cfg *ConfigSite, userID string) *db.FeatureFlag { | |
| 159 | - | ff, _ := dbpool.FindFeature(userID, "plus") | |
| 160 | - | // we have free tiers so users might not have a feature flag | |
| 161 | - | // in which case we set sane defaults | |
| 162 | - | if ff == nil { | |
| 163 | - | ff = db.NewFeatureFlag( | |
| 164 | - | userID, | |
| 165 | - | "plus", | |
| 166 | - | cfg.MaxSize, | |
| 167 | - | cfg.MaxAssetSize, | |
| 168 | - | cfg.MaxSpecialFileSize, | |
| 169 | - | ) | |
| 170 | - | } | |
| 171 | - | // this is jank | |
| 172 | - | ff.Data.StorageMax = ff.FindStorageMax(cfg.MaxSize) | |
| 173 | - | ff.Data.FileMax = ff.FindFileMax(cfg.MaxAssetSize) | |
| 174 | - | ff.Data.SpecialFileMax = ff.FindSpecialFileMax(cfg.MaxSpecialFileSize) | |
| 175 | - | return ff | |
| 176 | - | } |
+2,
-2
| ... | ... | @@ -472,12 +472,12 @@ func (m *TunsPage) fetchEventLogs() { | |
| 472 | 472 | } | |
| 473 | 473 | ||
| 474 | 474 | func (m *TunsPage) fetchTuns() { | |
| 475 | - | tMap, err := fetch("tuns.sh", m.shared.Cfg.TunsSecret) | |
| 475 | + | tMap, err := fetch("tuns.sh", m.shared.TunsSecret) | |
| 476 | 476 | if err != nil { | |
| 477 | 477 | m.err = err | |
| 478 | 478 | return | |
| 479 | 479 | } | |
| 480 | - | nMap, err := fetch("nue.tuns.sh", m.shared.Cfg.TunsSecret) | |
| 480 | + | nMap, err := fetch("nue.tuns.sh", m.shared.TunsSecret) | |
| 481 | 481 | if err != nil { | |
| 482 | 482 | m.err = err | |
| 483 | 483 | return |
+2,
-2