Files
openchamber-android-native/internal/appui/attachments.go
T

73 lines
1.5 KiB
Go
Raw Normal View History

package appui
import (
"encoding/base64"
"fmt"
"mime"
"os"
"path/filepath"
"strings"
"time"
"github.com/egoist/mygo"
)
// 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.
func keepImage(source, name string) string {
dir, err := mygo.App.Path(mygo.PathUserData)
if err != nil {
return ""
}
dir = filepath.Join(dir, "attachments")
_ = 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)
}
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)
}
func humanSize(bytes int64) string {
switch {
case bytes >= 1<<20:
return fmt.Sprintf("%.1fMB", float64(bytes)/(1<<20))
case bytes >= 1<<10:
return fmt.Sprintf("%.0fKB", float64(bytes)/(1<<10))
default:
return fmt.Sprintf("%dB", bytes)
}
}