返回 DeepSeek-Reasonix
attachments.go
根目录 / internal / control / attachments.go
1 package control
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "io"
9 "net/http"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "regexp"
14 "runtime"
15 "slices"
16 "strconv"
17 "strings"
18 "sync/atomic"
19 "time"
20
21 "reasonix/internal/attachment"
22 "reasonix/internal/proc"
23 "reasonix/internal/secrets"
24 )
25
26 const maxImageAttachmentBytes = 64 * 1024 * 1024
27 const maxFileAttachmentBytes = 25 * 1024 * 1024
28 const maxAttachmentCreateAttempts = 1000
29
30 // ErrAttachmentTooLarge and ErrImageTooLarge mark a payload over its size cap.
31 var (
32 ErrAttachmentTooLarge = errors.New("attachment must be between 1 byte and 25 MB")
33 ErrImageTooLarge = errors.New("pasted image must be between 1 byte and 64 MB")
34 )
35
36 // base64DecodedCeiling bounds the decoded size from the encoded length alone,
37 // so an oversized payload is refused before the decode buffer exists.
38 func base64DecodedCeiling(encodedLen int) int {
39 return encodedLen / 4 * 3
40 }
41
42 // ErrNoClipboardImage reports that the clipboard was read successfully but holds
43 // no supported image. It is distinct from a missing clipboard tool: callers
44 // offering an image-first paste shortcut use it to fall back to text before
45 // surfacing an image-specific diagnostic.
46 var ErrNoClipboardImage = errors.New("clipboard does not contain an image")
47
48 // ErrUnsupportedClipboardImage marks the more specific no-pasteable-image case
49 // where the clipboard advertised only image formats Reasonix cannot save.
50 var ErrUnsupportedClipboardImage = errors.New("clipboard image type is not supported")
51
52 type unsupportedClipboardImageError struct {
53 tool string
54 types []string
55 }
56
57 func (e unsupportedClipboardImageError) Error() string {
58 return fmt.Sprintf("%s offers unsupported image types: %s", e.tool, strings.Join(e.types, ", "))
59 }
60
61 // Unsupported image formats still mean there is no image Reasonix can paste.
62 // Wrapping the sentinel lets image-first shortcuts try their normal text
63 // fallback before surfacing the more specific diagnostic.
64 func (e unsupportedClipboardImageError) Unwrap() []error {
65 return []error{ErrNoClipboardImage, ErrUnsupportedClipboardImage}
66 }
67
68 var (
69 lookClipboardTool = exec.LookPath
70 runClipboardTool = func(path string, args ...string) ([]byte, []byte, error) {
71 cmd := proc.Command(path, args...)
72 cmd.Env = secrets.ProcessEnv()
73 var stderr bytes.Buffer
74 cmd.Stderr = &stderr
75 out, err := cmd.Output()
76 return out, stderr.Bytes(), err
77 }
78 )
79
80 var attachmentPathSeq atomic.Uint64
81 var attachmentNow = time.Now
82 var safeAttachmentExt = regexp.MustCompile(`^\.[a-z0-9]{1,12}$`)
83
84 // SaveAttachmentDataURL stores a non-image file (dropped/pasted in the desktop
85 // app, where the browser exposes bytes but not a real path) under
86 // .reasonix/attachments and returns its repo-relative path for @referencing.
87 // origName supplies only the extension; the stored name is generated.
88 func SaveAttachmentDataURL(origName, dataURL string) (string, error) {
89 return SaveAttachmentDataURLInRoot(".", origName, dataURL)
90 }
91
92 func SaveAttachmentDataURLInRoot(root, origName, dataURL string) (string, error) {
93 const marker = ";base64,"
94 _, after, ok := strings.Cut(dataURL, marker)
95 if !strings.HasPrefix(dataURL, "data:") || !ok {
96 return "", fmt.Errorf("unsupported pasted file")
97 }
98 if base64DecodedCeiling(len(after)) > maxFileAttachmentBytes+2 {
99 return "", ErrAttachmentTooLarge
100 }
101 raw, err := base64.StdEncoding.DecodeString(after)
102 if err != nil {
103 return "", fmt.Errorf("decode pasted file: %w", err)
104 }
105 return SaveAttachmentBytesInRoot(root, origName, raw)
106 }
107
108 func SaveAttachmentBytes(origName string, raw []byte) (string, error) {
109 return SaveAttachmentBytesInRoot(".", origName, raw)
110 }
111
112 func SaveAttachmentBytesInRoot(root, origName string, raw []byte) (string, error) {
113 if len(raw) == 0 || len(raw) > maxFileAttachmentBytes {
114 return "", ErrAttachmentTooLarge
115 }
116 ext := strings.ToLower(filepath.Ext(origName))
117 if !safeAttachmentExt.MatchString(ext) {
118 ext = ".bin"
119 }
120 return saveAttachmentBytesInRoot(root, ext, raw)
121 }
122
123 func SaveImageDataURL(dataURL string) (string, error) {
124 return SaveImageDataURLInRoot(".", dataURL)
125 }
126
127 func SaveImageDataURLInRoot(root, dataURL string) (string, error) {
128 const prefix = "data:"
129 const marker = ";base64,"
130 if !strings.HasPrefix(dataURL, prefix) {
131 return "", fmt.Errorf("unsupported pasted image")
132 }
133 i := strings.Index(dataURL, marker)
134 if i <= len(prefix) {
135 return "", fmt.Errorf("unsupported pasted image")
136 }
137 mime := strings.ToLower(dataURL[len(prefix):i])
138 if base64DecodedCeiling(len(dataURL)-i-len(marker)) > maxImageAttachmentBytes+2 {
139 return "", ErrImageTooLarge
140 }
141 raw, err := base64.StdEncoding.DecodeString(dataURL[i+len(marker):])
142 if err != nil {
143 return "", fmt.Errorf("decode pasted image: %w", err)
144 }
145 return SaveImageBytesInRoot(root, mime, raw)
146 }
147
148 func SaveImageBytes(declaredMime string, raw []byte) (string, error) {
149 return SaveImageBytesInRoot(".", declaredMime, raw)
150 }
151
152 func SaveImageBytesInRoot(root, declaredMime string, raw []byte) (string, error) {
153 if len(raw) == 0 || len(raw) > maxImageAttachmentBytes {
154 return "", ErrImageTooLarge
155 }
156 mime := detectedImageMime(raw)
157 if mime == "" {
158 return "", fmt.Errorf("pasted data is not a supported image")
159 }
160 if declaredMime != "" && imageExt(declaredMime) == "" {
161 return "", fmt.Errorf("unsupported image type: %s", declaredMime)
162 }
163 ext := imageExt(mime)
164 return saveAttachmentBytesInRoot(root, ext, raw)
165 }
166
167 func saveAttachmentBytesInRoot(root, ext string, raw []byte) (string, error) {
168 owned, err := createOwnedAttachmentFile(root, ext)
169 if err != nil {
170 return "", err
171 }
172 defer owned.cleanup()
173 if n, err := owned.Write(raw); err != nil {
174 return "", err
175 } else if n != len(raw) {
176 return "", io.ErrShortWrite
177 }
178 if err := owned.finish(); err != nil {
179 return "", err
180 }
181 return filepath.ToSlash(owned.rel), nil
182 }
183
184 func SaveImageFile(path string) (string, error) {
185 return SaveImageFileInRoot(".", path)
186 }
187
188 func SaveImageFileInRoot(root, path string) (string, error) {
189 info, err := os.Lstat(path)
190 if err != nil {
191 return "", err
192 }
193 if info.Mode()&os.ModeSymlink != 0 {
194 return "", fmt.Errorf("pasted image path must not be a symlink")
195 }
196 if info.IsDir() || info.Size() <= 0 || info.Size() > maxImageAttachmentBytes {
197 return "", ErrImageTooLarge
198 }
199 f, err := os.Open(path)
200 if err != nil {
201 return "", err
202 }
203 defer f.Close()
204 opened, err := f.Stat()
205 if err != nil {
206 return "", err
207 }
208 if !os.SameFile(info, opened) {
209 return "", fmt.Errorf("pasted image changed while opening")
210 }
211 raw, err := io.ReadAll(io.LimitReader(f, maxImageAttachmentBytes+1))
212 if err != nil {
213 return "", err
214 }
215 if len(raw) == 0 || len(raw) > maxImageAttachmentBytes {
216 return "", ErrImageTooLarge
217 }
218 if after, err := f.Stat(); err != nil {
219 return "", err
220 } else if !os.SameFile(opened, after) || after.Size() != opened.Size() {
221 return "", fmt.Errorf("pasted image changed while reading")
222 }
223 return SaveImageBytesInRoot(root, "", raw)
224 }
225
226 func SaveAttachmentFile(path string) (string, error) {
227 return SaveAttachmentFileInRoot(".", path)
228 }
229
230 func SaveAttachmentFileInRoot(root, path string) (string, error) {
231 info, err := os.Lstat(path)
232 if err != nil {
233 return "", err
234 }
235 if info.Mode()&os.ModeSymlink != 0 {
236 return "", fmt.Errorf("attachment path must not be a symlink")
237 }
238 if info.IsDir() || info.Size() <= 0 || info.Size() > maxFileAttachmentBytes {
239 return "", ErrAttachmentTooLarge
240 }
241 f, err := os.Open(path)
242 if err != nil {
243 return "", err
244 }
245 defer f.Close()
246 opened, err := f.Stat()
247 if err != nil {
248 return "", err
249 }
250 if !os.SameFile(info, opened) {
251 return "", fmt.Errorf("attachment changed while opening")
252 }
253 raw, err := io.ReadAll(io.LimitReader(f, maxFileAttachmentBytes+1))
254 if err != nil {
255 return "", err
256 }
257 if len(raw) == 0 || len(raw) > maxFileAttachmentBytes {
258 return "", ErrAttachmentTooLarge
259 }
260 if after, err := f.Stat(); err != nil {
261 return "", err
262 } else if !os.SameFile(opened, after) || after.Size() != opened.Size() {
263 return "", fmt.Errorf("attachment changed while reading")
264 }
265 ext := strings.ToLower(filepath.Ext(path))
266 if !safeAttachmentExt.MatchString(ext) {
267 ext = ".bin"
268 }
269 return saveAttachmentBytesInRoot(root, ext, raw)
270 }
271
272 func SaveClipboardImage() (string, error) {
273 return SaveClipboardImageInRoot(".")
274 }
275
276 func SaveClipboardImageInRoot(root string) (string, error) {
277 switch runtime.GOOS {
278 case "darwin":
279 return saveDarwinClipboardImageInRoot(root)
280 case "windows":
281 return saveWindowsClipboardImageInRoot(root)
282 case "linux":
283 return saveLinuxClipboardImageInRoot(root)
284 default:
285 return "", fmt.Errorf("clipboard image paste is not supported on %s yet", runtime.GOOS)
286 }
287 }
288
289 func saveWindowsClipboardImageInRoot(root string) (string, error) {
290 // Windows PowerShell 5.1 (preinstalled) reaches the GUI clipboard; pwsh (Core)
291 // lacks Get-Clipboard -Format Image, so invoke powershell.exe. The PNG is
292 // returned as base64 on stdout so no temp file is involved.
293 script := `Add-Type -AssemblyName System.Drawing
294 $img = Get-Clipboard -Format Image
295 if ($null -eq $img) { [Console]::Error.WriteLine('clipboard has no image'); exit 1 }
296 $ms = New-Object System.IO.MemoryStream
297 $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
298 [Convert]::ToBase64String($ms.ToArray())`
299 cmd := proc.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", script)
300 cmd.Env = secrets.ProcessEnv()
301 proc.HideWindow(cmd)
302 out, err := cmd.Output()
303 if err != nil {
304 var ee *exec.ExitError
305 if errors.As(err, &ee) && len(ee.Stderr) > 0 {
306 return "", fmt.Errorf("read clipboard image: %s", strings.TrimSpace(string(ee.Stderr)))
307 }
308 return "", fmt.Errorf("read clipboard image: %w", err)
309 }
310 raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(out)))
311 if err != nil {
312 return "", fmt.Errorf("decode clipboard image: %w", err)
313 }
314 return SaveImageBytesInRoot(root, "", raw)
315 }
316
317 // clipboardImageTypes lists the image mimes we can save, most preferred
318 // first; Wayland compositors and screenshot apps offer any of these.
319 var clipboardImageTypes = []string{"image/png", "image/jpeg", "image/gif", "image/webp"}
320
321 func clipboardImageReadArgs(tool, mime string) []string {
322 if tool == "wl-paste" {
323 return []string{"--type", mime, "--no-newline"}
324 }
325 return []string{"-selection", "clipboard", "-t", mime, "-o"}
326 }
327
328 func saveLinuxClipboardImage() (string, error) {
329 return saveLinuxClipboardImageInRoot(".")
330 }
331
332 func saveLinuxClipboardImageInRoot(root string) (string, error) {
333 type clipboardTool struct {
334 name string
335 typesArgs []string
336 }
337 tools := []clipboardTool{
338 {name: "wl-paste", typesArgs: []string{"--list-types"}},
339 {name: "xclip", typesArgs: []string{"-selection", "clipboard", "-t", "TARGETS", "-o"}},
340 }
341 foundTool := false
342 confirmedNoImage := false
343 var probeFailures, readFailures []error
344 for _, tool := range tools {
345 path, err := lookClipboardTool(tool.name)
346 if err != nil {
347 continue
348 }
349 foundTool = true
350 types, stderr, err := runClipboardTool(path, tool.typesArgs...)
351 if err != nil {
352 if clipboardProbeMeansNoImage(tool.name, stderr) {
353 confirmedNoImage = true
354 continue
355 }
356 probeFailures = append(probeFailures, fmt.Errorf("probe %s clipboard types: %w", tool.name, err))
357 continue
358 }
359 mime := ""
360 for _, want := range clipboardImageTypes {
361 if clipboardTypeListed(types, want) {
362 mime = want
363 break
364 }
365 }
366 if mime == "" {
367 if offered := offeredImageTypes(types); len(offered) > 0 {
368 readFailures = append(readFailures, unsupportedClipboardImageError{tool: tool.name, types: offered})
369 continue
370 }
371 confirmedNoImage = true
372 continue
373 }
374 out, _, err := runClipboardTool(path, clipboardImageReadArgs(tool.name, mime)...)
375 if err != nil {
376 readFailures = append(readFailures, fmt.Errorf("read clipboard image with %s: %w", tool.name, err))
377 continue
378 }
379 if len(out) == 0 {
380 readFailures = append(readFailures, fmt.Errorf("read clipboard image with %s: empty image data", tool.name))
381 continue
382 }
383 rel, err := SaveImageBytesInRoot(root, "", out)
384 if err != nil {
385 readFailures = append(readFailures, fmt.Errorf("save clipboard image from %s: %w", tool.name, err))
386 continue
387 }
388 return rel, nil
389 }
390 if !foundTool {
391 return "", fmt.Errorf("clipboard image paste needs wl-paste (Wayland) or xclip (X11)")
392 }
393 if len(readFailures) > 0 {
394 return "", fmt.Errorf("read clipboard image: %w", errors.Join(readFailures...))
395 }
396 if confirmedNoImage {
397 return "", ErrNoClipboardImage
398 }
399 return "", fmt.Errorf("read clipboard image: %w", errors.Join(probeFailures...))
400 }
401
402 func clipboardTypeListed(raw []byte, want string) bool {
403 for field := range strings.FieldsSeq(string(raw)) {
404 if strings.EqualFold(field, want) {
405 return true
406 }
407 }
408 return false
409 }
410
411 // offeredImageTypes returns safely quoted image/* MIME names that Reasonix
412 // cannot save. Clipboard owners control these strings, so errors must never
413 // contain their terminal control sequences verbatim.
414 func offeredImageTypes(raw []byte) []string {
415 var offered []string
416 for field := range strings.FieldsSeq(string(raw)) {
417 lower := strings.ToLower(field)
418 if strings.HasPrefix(lower, "image/") && !slices.Contains(clipboardImageTypes, lower) {
419 offered = append(offered, strconv.QuoteToASCII(field))
420 }
421 }
422 return offered
423 }
424
425 func clipboardProbeMeansNoImage(tool string, stderr []byte) bool {
426 message := string(stderr)
427 switch tool {
428 case "wl-paste":
429 return strings.Contains(message, "Nothing is copied")
430 case "xclip":
431 return strings.Contains(message, "There is no owner for the") && strings.Contains(message, "selection")
432 default:
433 return false
434 }
435 }
436
437 func ImageDataURL(path string) (string, error) {
438 return ImageDataURLInRoot(".", path)
439 }
440
441 func ImageDataURLInRoot(root, path string) (string, error) {
442 raw, mime, err := readAttachmentImageInRoot(root, path)
443 if err != nil {
444 return "", err
445 }
446 return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(raw), nil
447 }
448
449 // visionImageDataURLInRoot prepares a bounded request image from a workspace attachment.
450 func visionImageDataURLInRoot(root, path string) (string, error) {
451 raw, mime, err := readAttachmentImageInRoot(root, path)
452 if err != nil {
453 return "", err
454 }
455 raw, mime = compressForVision(raw, mime)
456 return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(raw), nil
457 }
458
459 func readAttachmentImageInRoot(root, path string) (raw []byte, mime string, err error) {
460 if _, err := cleanAttachmentPathInRoot(root, path); err != nil {
461 return nil, "", err
462 }
463 raw, err = attachment.ReadWorkspaceImageBytes(root, path, maxImageAttachmentBytes)
464 if err != nil {
465 return nil, "", err
466 }
467 mime = detectedImageMime(raw)
468 if mime == "" {
469 return nil, "", fmt.Errorf("attachment is not an image")
470 }
471 return raw, mime, nil
472 }
473
474 // ValidateAttachmentInRoot checks a persisted attachment without loading its
475 // contents. The bounded root prevents parent replacement from escaping the
476 // workspace and Lstat rejects a final symlink.
477 func ValidateAttachmentInRoot(root, path string) error {
478 clean, err := cleanAttachmentPathInRoot(root, path)
479 if err != nil {
480 return err
481 }
482 absRoot, err := filepath.Abs(root)
483 if err != nil {
484 return err
485 }
486 rel, err := filepath.Rel(absRoot, clean)
487 if err != nil || !filepath.IsLocal(rel) {
488 return fmt.Errorf("attachment path is outside workspace")
489 }
490 bounded, err := os.OpenRoot(absRoot)
491 if err != nil {
492 return err
493 }
494 defer bounded.Close()
495 info, err := bounded.Lstat(rel)
496 if err != nil {
497 return err
498 }
499 if info.Mode()&os.ModeSymlink != 0 {
500 return fmt.Errorf("attachment path must not be a symlink")
501 }
502 if !info.Mode().IsRegular() || info.Size() <= 0 {
503 return fmt.Errorf("attachment is missing or empty")
504 }
505 f, err := bounded.OpenFile(rel, os.O_RDONLY, 0)
506 if err != nil {
507 return err
508 }
509 defer f.Close()
510 opened, err := f.Stat()
511 if err != nil {
512 return err
513 }
514 if !os.SameFile(info, opened) {
515 return fmt.Errorf("attachment changed while opening")
516 }
517 return nil
518 }
519
520 func cleanAttachmentPathInRoot(base, path string) (string, error) {
521 if filepath.IsAbs(path) {
522 return "", fmt.Errorf("attachment path must be relative")
523 }
524 clean := filepath.Clean(filepath.FromSlash(path))
525 relRoot := filepath.Join(".reasonix", "attachments")
526 if clean == "." || clean == relRoot || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || !strings.HasPrefix(clean, relRoot+string(filepath.Separator)) {
527 return "", fmt.Errorf("attachment path is outside .reasonix/attachments")
528 }
529 if strings.TrimSpace(base) == "" {
530 base = "."
531 }
532 absBase, err := filepath.Abs(base)
533 if err != nil {
534 return "", err
535 }
536 root := filepath.Join(absBase, relRoot)
537 if err := validateAttachmentDirectories(absBase); err != nil {
538 return "", err
539 }
540 absPath := filepath.Join(absBase, clean)
541 if err := rejectSymlinkComponents(absPath, root); err != nil {
542 return "", err
543 }
544 return absPath, nil
545 }
546
547 func rejectSymlinkComponents(path, root string) error {
548 rel, err := filepath.Rel(root, path)
549 if err != nil {
550 return err
551 }
552 if rel == "." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || rel == ".." {
553 return fmt.Errorf("attachment path is outside .reasonix/attachments")
554 }
555 cur := root
556 for part := range strings.SplitSeq(rel, string(filepath.Separator)) {
557 if part == "" || part == "." {
558 continue
559 }
560 cur = filepath.Join(cur, part)
561 info, err := os.Lstat(cur)
562 if err != nil {
563 return err
564 }
565 if info.Mode()&os.ModeSymlink != 0 {
566 return fmt.Errorf("attachment path must not contain symlinks")
567 }
568 }
569 return nil
570 }
571
572 func ensureAttachmentRoot() error {
573 return ensureAttachmentRootIn(".")
574 }
575
576 func ensureAttachmentRootIn(base string) error {
577 directory, err := openAttachmentRootIn(base)
578 if err != nil {
579 return err
580 }
581 return directory.Close()
582 }
583
584 func validateAttachmentDirectories(base string) error {
585 for _, path := range []string{
586 filepath.Join(base, ".reasonix"),
587 filepath.Join(base, ".reasonix", "attachments"),
588 } {
589 info, err := os.Lstat(path)
590 if err != nil {
591 return err
592 }
593 if info.Mode()&os.ModeSymlink != 0 {
594 return fmt.Errorf("attachment path must not contain symlinks")
595 }
596 if !info.IsDir() {
597 return fmt.Errorf("attachment path exists but is not a directory")
598 }
599 }
600 return nil
601 }
602
603 func saveDarwinClipboardImageInRoot(root string) (string, error) {
604 return saveDarwinClipboardImageWith(func(class string) (string, error) {
605 return saveDarwinClipboardClassInRoot(root, class)
606 })
607 }
608
609 func saveDarwinClipboardImageWith(readClass func(string) (string, error)) (string, error) {
610 for _, class := range []string{"PNGf", "JPEG"} {
611 rel, err := readClass(class)
612 if err == nil {
613 return rel, nil
614 }
615 if !errors.Is(err, ErrNoClipboardImage) {
616 return "", err
617 }
618 }
619 return "", ErrNoClipboardImage
620 }
621
622 func saveDarwinClipboardClassInRoot(root, class string) (string, error) {
623 if strings.TrimSpace(root) == "" {
624 root = "."
625 }
626 absRoot, err := filepath.Abs(root)
627 if err != nil {
628 return "", err
629 }
630 if err := ensureAttachmentRootIn(absRoot); err != nil {
631 return "", err
632 }
633 rel, f, err := createAttachmentFileIn(absRoot, ".bin")
634 if err != nil {
635 return "", err
636 }
637 if err := f.Close(); err != nil {
638 _ = os.Remove(filepath.Join(absRoot, rel))
639 return "", err
640 }
641 abs := filepath.Join(absRoot, rel)
642 const noImageMarker = "__REASONIX_NO_CLIPBOARD_IMAGE__"
643 script := fmt.Sprintf(`
644 set hasImageType to false
645 repeat with typeEntry in (clipboard info)
646 if (item 1 of typeEntry) is «class %s» then
647 set hasImageType to true
648 exit repeat
649 end if
650 end repeat
651 if not hasImageType then return %q
652 set outPath to POSIX file %q
653 set img to the clipboard as «class %s»
654 set f to open for access outPath with write permission
655 try
656 set eof f to 0
657 write img to f
658 close access f
659 on error errMsg
660 try
661 close access f
662 end try
663 error errMsg
664 end try
665 `, class, noImageMarker, abs, class)
666 clip := proc.Command("osascript", "-e", script)
667 clip.Env = secrets.ProcessEnv()
668 out, runErr := clip.CombinedOutput()
669 if err := classifyDarwinClipboardResult(out, runErr, noImageMarker); err != nil {
670 _ = os.Remove(abs)
671 return "", err
672 }
673 raw, err := os.ReadFile(abs)
674 _ = os.Remove(abs)
675 if err != nil {
676 return "", err
677 }
678 return SaveImageBytesInRoot(absRoot, "", raw)
679 }
680
681 func classifyDarwinClipboardResult(out []byte, runErr error, noImageMarker string) error {
682 detail := strings.TrimSpace(string(out))
683 if runErr == nil {
684 if detail == noImageMarker {
685 return ErrNoClipboardImage
686 }
687 return nil
688 }
689 if detail == "" {
690 return fmt.Errorf("read clipboard image: %w", runErr)
691 }
692 return fmt.Errorf("read clipboard image: %s: %w", detail, runErr)
693 }
694
695 func createAttachmentFile(ext string) (string, *os.File, error) {
696 return createAttachmentFileIn(".", ext)
697 }
698
699 func createAttachmentFileIn(base, ext string) (string, *os.File, error) {
700 owned, err := createOwnedAttachmentFile(base, ext)
701 if err != nil {
702 return "", nil, err
703 }
704 _ = owned.directory.Close()
705 return owned.rel, owned.File, nil
706 }
707
708 func attachmentPath(ext string) string {
709 seq := attachmentPathSeq.Add(1)
710 name := fmt.Sprintf("clipboard-%s-%06d%s", attachmentNow().Format("20060102-150405.000000"), seq, ext)
711 return filepath.Join(".reasonix", "attachments", name)
712 }
713
714 func detectedImageMime(raw []byte) string {
715 if len(raw) == 0 {
716 return ""
717 }
718 mime := http.DetectContentType(raw[:min(len(raw), 512)])
719 if imageExt(mime) == "" {
720 return ""
721 }
722 return mime
723 }
724
725 func imageExt(mime string) string {
726 switch strings.ToLower(strings.TrimSpace(mime)) {
727 case "image/png":
728 return ".png"
729 case "image/jpeg":
730 return ".jpg"
731 case "image/gif":
732 return ".gif"
733 case "image/webp":
734 return ".webp"
735 }
736 return ""
737 }
738
738 lines GO