package appui import ( "encoding/base64" "fmt" "mime" "os" "path/filepath" "strings" "time" "github.com/egoist/asuka/colors" "github.com/egoist/asuka/fonts" "github.com/egoist/asuka/sdk/device" "github.com/egoist/asuka/sdk/store" "github.com/egoist/asuka/signal" "github.com/egoist/asuka/ui" "github.com/openchamber/openchamber-native/internal/ocapi" ) // maxAttachmentBytes bounds one file: prompts carry their files inline, and // a huge photo would make the send slow and may exceed what the server // accepts. const maxAttachmentBytes = 10 << 20 // attachment is a picked file waiting to ride with the next prompt. type attachment struct { Name string MIME string DataURL string Size int64 LocalPath string // a copy in the app's data dir, for inline preview } func (ch *chat) attachMenu() { ui.Alert(ui.AlertProps{ Title: "添加附件", ActionSheet: true, Actions: []ui.Action{ {Title: ui.Val("照片"), Icon: "photo", OnPress: ch.pickPhotos}, {Title: ui.Val("文件"), Icon: ui.IconFolder, OnPress: ch.pickFiles}, {Title: ui.Val("取消"), Role: ui.ActionCancel}, }, }) } func (ch *chat) pickPhotos() { ch.attaching.Set(true) device.PickPhotos(5, func(paths []string, err error) { ch.attaching.Set(false) if err != nil { ui.Snackbar(ui.SnackbarProps{Message: "无法选择照片:" + err.Error()}) return } for _, path := range paths { mimeType := mime.TypeByExtension(strings.ToLower(filepath.Ext(path))) if !strings.HasPrefix(mimeType, "image/") { mimeType = "image/jpeg" } ch.readAttachment(path, filepath.Base(path), mimeType) } }) } func (ch *chat) pickFiles() { ch.attaching.Set(true) device.PickFiles(device.FileOptions{Multiple: true}, func(files []device.File, err error) { ch.attaching.Set(false) if err != nil { ui.Snackbar(ui.SnackbarProps{Message: "无法选择文件:" + err.Error()}) return } for _, f := range files { mimeType := f.Type if mimeType == "" { mimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(f.Name))) } if mimeType == "" { mimeType = "application/octet-stream" } name := f.Name if name == "" { name = filepath.Base(f.Path) } ch.readAttachment(f.Path, name, mimeType) } }) } // readAttachment reads a picked file off the main thread and hands the // composer a data URL. func (ch *chat) readAttachment(path, name, mimeType string) { go func() { info, err := os.Stat(path) if err != nil { ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) }) return } if info.Size() > maxAttachmentBytes { ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: fmt.Sprintf("%s 超过 10 MB,未添加", name)}) }) return } data, err := os.ReadFile(path) if err != nil { ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) }) return } url := "data:" + mimeType + ";base64," + base64.StdEncoding.EncodeToString(data) kept := "" if strings.HasPrefix(mimeType, "image/") { kept = keepImage(path, name) } ui.Post(func() { list := ch.attachments.Peek() next := make([]attachment, len(list), len(list)+1) copy(next, list) next = append(next, attachment{Name: name, MIME: mimeType, DataURL: url, Size: info.Size(), LocalPath: kept}) ch.attachments.Set(next) }) }() } func (ch *chat) removeAttachment(index int) { list := ch.attachments.Peek() if index < 0 || index >= len(list) { return } next := make([]attachment, 0, len(list)-1) next = append(next, list[:index]...) next = append(next, list[index+1:]...) ch.attachments.Set(next) } // attachmentRow shows the files the next prompt will carry. func (ch *chat) attachmentRow() ui.Node { return ui.Show(signal.Func(func() bool { return len(ch.attachments.Get()) > 0 }), func() ui.Node { return ui.Scroll( ui.ScrollProps{Horizontal: true, Style: ui.Style{}, ContentStyle: ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6}}, ui.For(ch.attachments, func(a attachment) string { return a.Name + a.DataURL[:24] }, func(a signal.Accessor[attachment], index signal.Accessor[int]) ui.Node { return ui.View(ui.ViewProps{ Style: ui.Style{Padding: ui.Symmetric(6, 10), CornerRadius: 8, Background: colors.SecondaryBackground, Align: ui.AlignCenter}, }, ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter}, ui.Symbol("paperclip", ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}), ui.Text(signal.Func(func() string { a := a.Get() return fmt.Sprintf("%s · %s", a.Name, humanSize(a.Size)) }), ui.Style{Font: fonts.Caption, Lines: 1}), ui.Button(ui.ButtonProps{Icon: ui.IconClose, Label: ui.Val("移除附件"), OnPress: func() { ch.removeAttachment(index.Get()) }}), ), ) }), ) }) } func (ch *chat) attachmentFiles() []ocapi.PromptFile { list := ch.attachments.Peek() out := make([]ocapi.PromptFile, 0, len(list)) for _, a := range list { out = append(out, ocapi.PromptFile{URI: a.DataURL, Name: a.Name}) } return out } func (ch *chat) optimisticFiles() []ocapi.FileAttachment { list := ch.attachments.Peek() out := make([]ocapi.FileAttachment, 0, len(list)) for _, a := range list { out = append(out, ocapi.FileAttachment{URI: a.DataURL, Name: a.Name, MIME: a.MIME}) } return out } // keepImage copies a picked image into the app's data dir so the sent // message can show it inline after a reload clears the caches copy. func keepImage(source, name string) string { dir := filepath.Join(store.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 humanSize(bytes int64) string { switch { case bytes >= 1<<20: return fmt.Sprintf("%.1f MB", float64(bytes)/(1<<20)) case bytes >= 1<<10: return fmt.Sprintf("%.0f KB", float64(bytes)/(1<<10)) default: return fmt.Sprintf("%d B", bytes) } }