2026-11-17 21:52:06 +08:00
|
|
|
package appui
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/base64"
|
|
|
|
|
"fmt"
|
|
|
|
|
"mime"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
|
|
|
|
"strings"
|
2026-11-17 23:46:06 +08:00
|
|
|
"time"
|
2026-11-17 21:52:06 +08:00
|
|
|
|
2026-11-18 13:00:20 +08:00
|
|
|
"github.com/egoist/mygo"
|
2026-11-17 21:52:06 +08:00
|
|
|
)
|
|
|
|
|
|
2026-11-18 13:00:20 +08:00
|
|
|
// keepImage copies a picked image into the app's data directory so the sent
|
|
|
|
|
// message can show it inline after a reload clears the picker's copy.
|
2026-11-17 23:46:06 +08:00
|
|
|
func keepImage(source, name string) string {
|
2026-11-18 13:00:20 +08:00
|
|
|
dir, err := mygo.App.Path(mygo.PathUserData)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
dir = filepath.Join(dir, "attachments")
|
2026-11-17 23:46:06 +08:00
|
|
|
_ = os.MkdirAll(dir, 0o700)
|
|
|
|
|
dst := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), sanitizeName(name)))
|
|
|
|
|
if err := copyFile(source, dst); err != nil {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
return dst
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func sanitizeName(name string) string {
|
|
|
|
|
clean := strings.Map(func(r rune) rune {
|
|
|
|
|
switch r {
|
|
|
|
|
case '/', '\\', ':', '*', '?', '"', '<', '>', '|':
|
|
|
|
|
return '_'
|
|
|
|
|
}
|
|
|
|
|
return r
|
|
|
|
|
}, name)
|
|
|
|
|
if clean == "" {
|
|
|
|
|
return "image"
|
|
|
|
|
}
|
|
|
|
|
return clean
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func copyFile(src, dst string) error {
|
|
|
|
|
data, err := os.ReadFile(src)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
return os.WriteFile(dst, data, 0o600)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 13:00:20 +08:00
|
|
|
func mimeByExt(path string) string {
|
|
|
|
|
if m := mime.TypeByExtension(filepath.Ext(path)); m != "" {
|
|
|
|
|
return m
|
|
|
|
|
}
|
|
|
|
|
return "application/octet-stream"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func base64URL(data []byte) string {
|
|
|
|
|
return base64.StdEncoding.EncodeToString(data)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 21:52:06 +08:00
|
|
|
func humanSize(bytes int64) string {
|
|
|
|
|
switch {
|
|
|
|
|
case bytes >= 1<<20:
|
2026-11-18 13:00:20 +08:00
|
|
|
return fmt.Sprintf("%.1fMB", float64(bytes)/(1<<20))
|
2026-11-17 21:52:06 +08:00
|
|
|
case bytes >= 1<<10:
|
2026-11-18 13:00:20 +08:00
|
|
|
return fmt.Sprintf("%.0fKB", float64(bytes)/(1<<10))
|
2026-11-17 21:52:06 +08:00
|
|
|
default:
|
2026-11-18 13:00:20 +08:00
|
|
|
return fmt.Sprintf("%dB", bytes)
|
2026-11-17 21:52:06 +08:00
|
|
|
}
|
|
|
|
|
}
|