package attach import ( "errors" "net/url" "strings" "git.golem15.com/golem15/summercms/modules/compass" ) // ErrNoAbsoluteURL is returned by AbsolutePublicURL when the configuration // gives no absolute base: neither storage.uploads.public_url nor an absolute // app.url is set. var ErrNoAbsoluteURL = errors.New("attach: no absolute public URL: set storage.uploads.public_url or app.url") // AbsolutePublicURL returns the absolute public URL of a blob key, for use // outside the site, as in mail. With storage.uploads.public_url set it is // that base and the key joined by one slash, as PublicURL returns. Otherwise // it is app.url, storage.uploads.public_path_prefix (the default prefix when // unset) and the key. With neither it returns ErrNoAbsoluteURL; a malformed // public_url is its own error. // // It reads cfg only, never the values OpenBucket recorded, so it returns the // same URL in a process that opened no bucket, such as a job worker. func AbsolutePublicURL(cfg *compass.Config, key string) (string, error) { if cfg == nil { return "", ErrNoAbsoluteURL } key = strings.TrimLeft(key, "/") base, err := parsePublicURL(cfg.String("storage.uploads.public_url")) if err != nil { return "", err } if base != nil { return strings.TrimRight(base.String(), "/") + "/" + key, nil } app, err := url.Parse(strings.TrimSpace(cfg.String("app.url"))) if err != nil || app.Host == "" || (!strings.EqualFold(app.Scheme, "http") && !strings.EqualFold(app.Scheme, "https")) { return "", ErrNoAbsoluteURL } prefix := strings.TrimSpace(cfg.String("storage.uploads.public_path_prefix")) if prefix == "" { prefix = defaultPublicPathPrefix } out := app.Scheme + "://" + app.Host + strings.TrimRight(app.Path, "/") if prefix = strings.Trim(prefix, "/"); prefix != "" { out += "/" + prefix } return out + "/" + key, nil }