navid/veinsforge / 92d87e69f0b857e9088f27921a23fc6c9a87aeb96bc4b6c46a4296df54bd2527 / internal/web/helpers.go
helpers.go
← internal/web · 8962 bytes · raw · download
package web
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/url"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"veinsforge/internal/data"
)
type ctxKey int
const (
userKey ctxKey = iota
sessionKey
csrfKey
ipKey
)
type requestSession struct {
ID string
CSRF string
}
func userFrom(r *http.Request) *data.User {
u, _ := r.Context().Value(userKey).(*data.User)
return u
}
func sessionFrom(r *http.Request) *requestSession {
s, _ := r.Context().Value(sessionKey).(*requestSession)
return s
}
func csrfFrom(r *http.Request) string {
if r == nil {
return ""
}
s, _ := r.Context().Value(csrfKey).(string)
return s
}
func ipFrom(r *http.Request) string {
ip, _ := r.Context().Value(ipKey).(string)
return ip
}
func parseID(s string) (int64, bool) {
n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
return n, err == nil && n > 0
}
func redirect(w http.ResponseWriter, r *http.Request, target, notice, errMsg string) {
if !strings.HasPrefix(target, "/") || strings.HasPrefix(target, "//") {
target = "/"
}
u, err := url.Parse(target)
if err != nil {
u = &url.URL{Path: "/"}
}
q := u.Query()
if notice != "" {
q.Set("notice", notice)
}
if errMsg != "" {
q.Set("error", errMsg)
}
u.RawQuery = q.Encode()
http.Redirect(w, r, u.String(), http.StatusSeeOther)
}
func repoURL(repo *data.Repo) string {
if repo == nil {
return "/"
}
return "/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name)
}
// nativeAddress returns the host:port clients should use for the native
// protocol. An explicitly configured public host wins; when that host is only
// a loopback/default, prefer the host the browser actually reached us on so
// the UI never advertises "your-host" or 127.0.0.1 to remote users.
func (s *Server) nativeAddress(r *http.Request) string {
addr := s.cfg.NativeAddress()
host, port, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
host = strings.Trim(host, "[]")
if r != nil && isLoopbackHost(host) {
requested := r.Host
if h, _, splitErr := net.SplitHostPort(requested); splitErr == nil {
requested = h
}
requested = strings.Trim(requested, "[]")
if requested != "" && !isLoopbackHost(requested) {
host = requested
}
}
return net.JoinHostPort(host, port)
}
func isLoopbackHost(host string) bool {
if host == "" || strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil {
return ip.IsLoopback() || ip.IsUnspecified()
}
return false
}
func (s *Server) nativeCloneURL(r *http.Request, owner, name string) string {
return "veins://" + s.nativeAddress(r) + "/" + url.PathEscape(owner) + "/" + url.PathEscape(name)
}
func ownerURL(repo *data.Repo) string {
if repo == nil {
return "/"
}
if repo.OwnerType == "org" {
return "/orgs/" + url.PathEscape(repo.OwnerName)
}
return "/u/" + url.PathEscape(repo.OwnerName)
}
func issueURL(repo *data.Repo, n int64) string {
return repoURL(repo) + "/issues/" + strconv.FormatInt(n, 10)
}
func pullURL(repo *data.Repo, n int64) string {
return repoURL(repo) + "/pulls/" + strconv.FormatInt(n, 10)
}
func commitURL(repo *data.Repo, rev string) string {
return repoURL(repo) + "/commit/" + revPath(rev)
}
func treeURL(repo *data.Repo, rev, p string) string {
base := repoURL(repo) + "/tree/" + revPath(rev)
if p != "" {
base += "/" + escapePath(p)
}
return base
}
func blobURL(repo *data.Repo, rev, p string) string {
return repoURL(repo) + "/blob/" + revPath(rev) + "/" + escapePath(p)
}
func rawURL(repo *data.Repo, rev, p string) string {
return repoURL(repo) + "/raw/" + revPath(rev) + "/" + escapePath(p)
}
func archiveURL(repo *data.Repo, rev string) string {
return repoURL(repo) + "/archive/" + revPath(rev) + ".zip"
}
// revPath keeps slash-containing bookmark names inside a single URL segment.
func revPath(rev string) string {
if rev == "" {
return ""
}
if !strings.ContainsAny(rev, "/?#%") {
return url.PathEscape(rev)
}
return "~" + base64.RawURLEncoding.EncodeToString([]byte(rev))
}
func decodeRevPath(token string) string {
if strings.HasPrefix(token, "~") {
if decoded, err := base64.RawURLEncoding.DecodeString(token[1:]); err == nil {
return string(decoded)
}
}
return token
}
func escapePath(p string) string {
parts := strings.Split(strings.TrimLeft(path.Clean("/"+p), "/"), "/")
for i, part := range parts {
parts[i] = url.PathEscape(part)
}
return strings.Join(parts, "/")
}
func avatarURL(username string) string {
return "/avatars/" + url.PathEscape(username)
}
func orgAvatarURL(name string) string {
return "/avatars/org-" + url.PathEscape(name)
}
type TreeEntry struct {
Name string
Path string
IsDir bool
}
func buildTree(files []string, prefix string) []TreeEntry {
prefix = strings.TrimSuffix(prefix, "/")
seen := make(map[string]bool)
for _, f := range files {
if prefix != "" {
if !strings.HasPrefix(f, prefix+"/") {
continue
}
f = strings.TrimPrefix(f, prefix+"/")
}
if f == "" {
continue
}
parts := strings.SplitN(f, "/", 2)
name := parts[0]
full := name
if prefix != "" {
full = prefix + "/" + name
}
if len(parts) == 2 {
seen["d:"+name] = true
seen["p:"+name] = true
_ = full
} else {
seen["f:"+name] = true
seen["p:"+name] = true
}
}
var dirs, regular []TreeEntry
for k := range seen {
if !strings.HasPrefix(k, "p:") {
continue
}
name := strings.TrimPrefix(k, "p:")
if name == "" {
continue
}
full := name
if prefix != "" {
full = prefix + "/" + name
}
e := TreeEntry{Name: name, Path: full, IsDir: seen["d:"+name]}
if e.IsDir {
dirs = append(dirs, e)
} else {
regular = append(regular, e)
}
}
sort.Slice(dirs, func(i, j int) bool { return strings.ToLower(dirs[i].Name) < strings.ToLower(dirs[j].Name) })
sort.Slice(regular, func(i, j int) bool { return strings.ToLower(regular[i].Name) < strings.ToLower(regular[j].Name) })
return append(dirs, regular...)
}
type CodeLine struct {
Number int
Text string
}
type DiffLine struct {
Text string
Class string
}
func splitCode(data []byte) ([]CodeLine, bool, bool) {
if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {
return nil, true, false
}
// A final newline terminates the last line rather than starting a new one.
text := strings.TrimSuffix(string(data), "\n")
truncated := false
lines := strings.Split(text, "\n")
if len(lines) > 5000 {
lines = lines[:5000]
truncated = true
}
out := make([]CodeLine, 0, len(lines))
for i, line := range lines {
out = append(out, CodeLine{Number: i + 1, Text: strings.TrimSuffix(line, "\r")})
}
return out, false, truncated
}
func codeText(lines []CodeLine) string {
texts := make([]string, len(lines))
for i, line := range lines {
texts[i] = line.Text
}
return strings.Join(texts, "\n")
}
func lineNumbers(count int) []int {
out := make([]int, count)
for i := range out {
out[i] = i + 1
}
return out
}
func splitDiff(diff string) []DiffLine {
if diff == "" {
return nil
}
diff = strings.TrimSuffix(diff, "\n")
var out []DiffLine
for _, line := range strings.Split(diff, "\n") {
class := ""
switch {
case strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "---"):
class = "diff-file"
case strings.HasPrefix(line, "@@"):
class = "diff-hunk"
case strings.HasPrefix(line, "+"):
class = "diff-add"
case strings.HasPrefix(line, "-"):
class = "diff-del"
case strings.HasPrefix(line, "diff "), strings.HasPrefix(line, "index "):
class = "diff-meta"
}
out = append(out, DiffLine{Text: line, Class: class})
}
return out
}
func humanSize(n int64) string {
const unit = 1024
if n < unit {
return fmt.Sprintf("%d B", n)
}
div, exp := int64(unit), 0
for n/div >= unit && exp < 4 {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])
}
func mimeFor(name string) string {
ext := strings.ToLower(filepath.Ext(name))
switch ext {
case ".md", ".markdown", ".txt", ".sx", ".c", ".h", ".go", ".rs", ".py", ".js", ".ts", ".css", ".html", ".json", ".toml", ".yaml", ".yml", ".sh", ".mod", ".lock":
return "text/plain; charset=utf-8"
case ".png":
return "image/png"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".gif":
return "image/gif"
case ".webp":
return "image/webp"
case ".svg":
return "image/svg+xml"
case ".pdf":
return "application/pdf"
case ".zip":
return "application/zip"
default:
return "application/octet-stream"
}
}
func isSafeImage(mime string) bool {
switch mime {
case "image/png", "image/jpeg", "image/gif", "image/webp":
return true
}
return false
}
func (s *Server) setting(name, def string, r *http.Request) string {
return s.data.Setting(r.Context(), name, def)
}
func backgroundWithTimeout(d time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), d)
}