2017-06-27 20:49:53 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2018-06-17 14:26:57 +00:00
|
|
|
"encoding/json"
|
2017-06-27 20:49:53 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2021-02-19 18:26:07 +00:00
|
|
|
httpHelper "github.com/Luzifer/go_helpers/v2/http"
|
|
|
|
"github.com/Luzifer/rconfig/v2"
|
2017-06-27 21:09:46 +00:00
|
|
|
"github.com/didip/tollbooth"
|
2018-04-03 19:14:16 +00:00
|
|
|
"github.com/didip/tollbooth/limiter"
|
2017-06-27 20:49:53 +00:00
|
|
|
"github.com/golang/geo/s2"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
colorful "github.com/lucasb-eyer/go-colorful"
|
2023-10-15 11:19:01 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
2017-06-27 20:49:53 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
cfg struct {
|
2023-10-15 11:19:01 +00:00
|
|
|
CacheDir string `flag:"cache-dir" default:"cache" description:"Directory to save the cached images to"`
|
|
|
|
ForceCache time.Duration `flag:"force-cache" default:"24h" description:"Force map to be cached for this duration"`
|
2017-06-27 20:49:53 +00:00
|
|
|
Listen string `flag:"listen" default:":3000" description:"IP/Port to listen on"`
|
2023-10-15 11:19:01 +00:00
|
|
|
MaxSize string `flag:"max-size" default:"1024x1024" description:"Maximum map size requestable"`
|
|
|
|
RateLimit float64 `flag:"rate-limit" default:"1" description:"How many requests to allow per time"`
|
|
|
|
RateLimitTime time.Duration `flag:"rate-limit-time" default:"1s" description:"Time interval to allow N requests in"`
|
2017-06-27 20:49:53 +00:00
|
|
|
VersionAndExit bool `flag:"version" default:"false" description:"Print version information and exit"`
|
|
|
|
}
|
|
|
|
|
|
|
|
mapMaxX, mapMaxY int
|
|
|
|
cacheFunc cacheFunction = filesystemCache // For now this is simply set and might be extended later
|
|
|
|
|
|
|
|
version = "dev"
|
|
|
|
)
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
func initApp() (err error) {
|
|
|
|
rconfig.AutoEnv(true)
|
2018-04-03 18:32:31 +00:00
|
|
|
if err = rconfig.ParseAndValidate(&cfg); err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
return errors.Wrap(err, "parsing CLI parameters")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
if mapMaxX, mapMaxY, err = parseSize(cfg.MaxSize); err != nil {
|
|
|
|
return errors.Wrap(err, "parsing max-size")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
return nil
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2023-10-15 11:19:01 +00:00
|
|
|
var err error
|
|
|
|
if err = initApp(); err != nil {
|
|
|
|
logrus.WithError(err).Fatal("initializing app")
|
|
|
|
}
|
|
|
|
|
|
|
|
if cfg.VersionAndExit {
|
|
|
|
fmt.Printf("staticmap %s\n", version) //nolint:forbidigo
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-04-03 19:14:16 +00:00
|
|
|
rateLimit := tollbooth.NewLimiter(cfg.RateLimit, &limiter.ExpirableOptions{
|
|
|
|
DefaultExpirationTTL: cfg.RateLimitTime,
|
|
|
|
})
|
|
|
|
rateLimit.SetIPLookups([]string{"X-Forwarded-For", "RemoteAddr", "X-Real-IP"})
|
2017-06-27 21:09:46 +00:00
|
|
|
|
2017-06-27 20:49:53 +00:00
|
|
|
r := mux.NewRouter()
|
|
|
|
r.HandleFunc("/status", func(res http.ResponseWriter, r *http.Request) { http.Error(res, "I'm fine", http.StatusOK) })
|
2018-06-17 14:26:57 +00:00
|
|
|
r.Handle("/map.png", tollbooth.LimitFuncHandler(rateLimit, handleMapRequest)).Methods("GET")
|
|
|
|
r.Handle("/map.png", tollbooth.LimitFuncHandler(rateLimit, handlePostMapRequest)).Methods("POST")
|
2023-10-15 11:19:01 +00:00
|
|
|
|
|
|
|
server := &http.Server{
|
|
|
|
Addr: cfg.Listen,
|
2023-10-15 11:44:04 +00:00
|
|
|
Handler: httpHelper.NewHTTPLogHandlerWithLogger(r, logrus.StandardLogger()),
|
2023-10-15 11:19:01 +00:00
|
|
|
ReadHeaderTimeout: time.Second,
|
|
|
|
}
|
|
|
|
|
|
|
|
logrus.WithField("version", version).Info("staticmap started")
|
|
|
|
if err = server.ListenAndServe(); err != nil {
|
|
|
|
logrus.WithError(err).Fatal("running HTTP server")
|
|
|
|
}
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleMapRequest(res http.ResponseWriter, r *http.Request) {
|
|
|
|
var (
|
2018-06-17 13:19:28 +00:00
|
|
|
err error
|
|
|
|
mapReader io.ReadCloser
|
|
|
|
opts = generateMapConfig{
|
|
|
|
DisableAttribution: r.URL.Query().Get("no-attribution") == "true",
|
|
|
|
}
|
2017-06-27 20:49:53 +00:00
|
|
|
)
|
|
|
|
|
2018-06-17 13:19:28 +00:00
|
|
|
if opts.Center, err = parseCoordinate(r.URL.Query().Get("center")); err != nil {
|
2017-06-27 20:49:53 +00:00
|
|
|
http.Error(res, fmt.Sprintf("Unable to parse 'center' parameter: %s", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-06-17 13:19:28 +00:00
|
|
|
if opts.Zoom, err = strconv.Atoi(r.URL.Query().Get("zoom")); err != nil {
|
2017-06-27 20:49:53 +00:00
|
|
|
http.Error(res, fmt.Sprintf("Unable to parse 'zoom' parameter: %s", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
if opts.Width, opts.Height, err = parseSize(r.URL.Query().Get("size")); err != nil {
|
2017-06-27 20:49:53 +00:00
|
|
|
http.Error(res, fmt.Sprintf("Unable to parse 'size' parameter: %s", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-06-17 13:19:28 +00:00
|
|
|
if opts.Markers, err = parseMarkerLocations(r.URL.Query()["markers"]); err != nil {
|
2017-06-27 20:49:53 +00:00
|
|
|
http.Error(res, fmt.Sprintf("Unable to parse 'markers' parameter: %s", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-06-17 13:19:28 +00:00
|
|
|
if mapReader, err = cacheFunc(opts); err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
logrus.Errorf("map render failed: %s (Request: %s)", err, r.URL.String())
|
2017-06-27 20:49:53 +00:00
|
|
|
http.Error(res, fmt.Sprintf("I experienced difficulties rendering your map: %s", err), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2023-10-15 11:19:01 +00:00
|
|
|
defer func() {
|
|
|
|
if err := mapReader.Close(); err != nil {
|
|
|
|
logrus.WithError(err).Error("closing map cache reader (leaked fd)")
|
|
|
|
}
|
|
|
|
}()
|
2017-06-27 20:49:53 +00:00
|
|
|
|
|
|
|
res.Header().Set("Content-Type", "image/png")
|
|
|
|
res.Header().Set("Cache-Control", "public")
|
2023-10-15 11:19:01 +00:00
|
|
|
|
|
|
|
if _, err = io.Copy(res, mapReader); err != nil {
|
|
|
|
logrus.WithError(err).Debug("writing image to HTTP client")
|
|
|
|
}
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2018-06-17 14:26:57 +00:00
|
|
|
func handlePostMapRequest(res http.ResponseWriter, r *http.Request) {
|
|
|
|
var (
|
|
|
|
body = postMapEnvelope{}
|
|
|
|
mapReader io.ReadCloser
|
|
|
|
)
|
|
|
|
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
|
|
http.Error(res, fmt.Sprintf("Unable to parse input: %s", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
opts, err := body.toGenerateMapConfig()
|
|
|
|
if err != nil {
|
|
|
|
http.Error(res, fmt.Sprintf("Unable to process input: %s", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if mapReader, err = cacheFunc(opts); err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
logrus.Errorf("map render failed: %s (Request: %s)", err, r.URL.String())
|
2018-06-17 14:26:57 +00:00
|
|
|
http.Error(res, fmt.Sprintf("I experienced difficulties rendering your map: %s", err), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2023-10-15 11:19:01 +00:00
|
|
|
defer func() {
|
|
|
|
if err := mapReader.Close(); err != nil {
|
|
|
|
logrus.WithError(err).Error("closing map cache reader (leaked fd)")
|
|
|
|
}
|
|
|
|
}()
|
2018-06-17 14:26:57 +00:00
|
|
|
|
|
|
|
res.Header().Set("Content-Type", "image/png")
|
|
|
|
res.Header().Set("Cache-Control", "public")
|
2023-10-15 11:19:01 +00:00
|
|
|
|
|
|
|
if _, err = io.Copy(res, mapReader); err != nil {
|
|
|
|
logrus.WithError(err).Debug("writing image to HTTP client")
|
|
|
|
}
|
2018-06-17 14:26:57 +00:00
|
|
|
}
|
|
|
|
|
2018-06-17 13:19:28 +00:00
|
|
|
func parseCoordinate(coord string) (s2.LatLng, error) {
|
2017-06-27 20:49:53 +00:00
|
|
|
if coord == "" {
|
2018-06-17 13:19:28 +00:00
|
|
|
return s2.LatLng{}, errors.New("No coordinate given")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
parts := strings.Split(coord, ",")
|
2023-10-15 11:19:01 +00:00
|
|
|
if len(parts) != 2 { //nolint:gomnd
|
2018-06-17 13:19:28 +00:00
|
|
|
return s2.LatLng{}, errors.New("Coordinate not in format lat,lon")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
lat, lon float64
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
if lat, err = strconv.ParseFloat(parts[0], 64); err != nil {
|
2018-06-17 13:19:28 +00:00
|
|
|
return s2.LatLng{}, errors.New("Latitude not parseable as float")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if lon, err = strconv.ParseFloat(parts[1], 64); err != nil {
|
2018-06-17 13:19:28 +00:00
|
|
|
return s2.LatLng{}, errors.New("Longitude not parseable as float")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pt := s2.LatLngFromDegrees(lat, lon)
|
2018-06-17 13:19:28 +00:00
|
|
|
return pt, nil
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
func parseSize(size string) (x, y int, err error) {
|
2017-06-27 20:49:53 +00:00
|
|
|
if size == "" {
|
|
|
|
return 0, 0, errors.New("No size given")
|
|
|
|
}
|
|
|
|
|
|
|
|
parts := strings.Split(size, "x")
|
2023-10-15 11:19:01 +00:00
|
|
|
if len(parts) != 2 { //nolint:gomnd
|
2017-06-27 20:49:53 +00:00
|
|
|
return 0, 0, errors.New("Size not in format 600x300")
|
|
|
|
}
|
|
|
|
|
|
|
|
if x, err = strconv.Atoi(parts[0]); err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
return 0, 0, errors.Wrap(err, "parsing width")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if y, err = strconv.Atoi(parts[1]); err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
return 0, 0, errors.Wrap(err, "parsing height")
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
if (x > mapMaxX || y > mapMaxY) && mapMaxX > 0 && mapMaxY > 0 {
|
|
|
|
return 0, 0, errors.Errorf("map size exceeds allowed bounds of %dx%d", mapMaxX, mapMaxY)
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:19:01 +00:00
|
|
|
return x, y, nil
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func parseMarkerLocations(markers []string) ([]marker, error) {
|
|
|
|
if markers == nil {
|
|
|
|
// No markers parameters passed, lets ignore this
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
result := []marker{}
|
|
|
|
|
|
|
|
for _, markerInformation := range markers {
|
|
|
|
parts := strings.Split(markerInformation, "|")
|
|
|
|
|
|
|
|
var (
|
|
|
|
size = markerSizes["small"]
|
|
|
|
col = markerColors["red"]
|
|
|
|
)
|
|
|
|
|
|
|
|
for _, p := range parts {
|
|
|
|
switch {
|
|
|
|
case strings.HasPrefix(p, "size:"):
|
2023-10-15 11:19:01 +00:00
|
|
|
s, ok := markerSizes[strings.TrimPrefix(p, "size:")]
|
|
|
|
if !ok {
|
|
|
|
return nil, errors.Errorf("bad marker size %q", strings.TrimPrefix(p, "size:"))
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
2023-10-15 11:19:01 +00:00
|
|
|
size = s
|
|
|
|
|
2017-06-27 20:49:53 +00:00
|
|
|
case strings.HasPrefix(p, "color:0x"):
|
2023-10-15 11:19:01 +00:00
|
|
|
c, err := colorful.Hex("#" + strings.TrimPrefix(p, "color:0x"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "parsing color %q", strings.TrimPrefix(p, "color:"))
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
2023-10-15 11:19:01 +00:00
|
|
|
col = c
|
|
|
|
|
2017-06-27 20:49:53 +00:00
|
|
|
case strings.HasPrefix(p, "color:"):
|
2023-10-15 11:19:01 +00:00
|
|
|
c, ok := markerColors[strings.TrimPrefix(p, "color:")]
|
|
|
|
if !ok {
|
|
|
|
return nil, errors.Errorf("bad color name %q", strings.TrimPrefix(p, "color:"))
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
2023-10-15 11:19:01 +00:00
|
|
|
col = c
|
|
|
|
|
2017-06-27 20:49:53 +00:00
|
|
|
default:
|
|
|
|
pos, err := parseCoordinate(p)
|
|
|
|
if err != nil {
|
2023-10-15 11:19:01 +00:00
|
|
|
return nil, errors.Errorf("unparsable chunk found in marker: %q", p)
|
2017-06-27 20:49:53 +00:00
|
|
|
}
|
|
|
|
result = append(result, marker{
|
2018-06-17 13:19:28 +00:00
|
|
|
pos: pos,
|
2017-06-27 20:49:53 +00:00
|
|
|
color: col,
|
|
|
|
size: size,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|