Release beta_v0.1.0
Release Note: - feature: - capture the screenshot, and copy it in clipboard or save it to local file - annotate the screenshot with in many ways, e.g. Line, Arrow, Text, Mosaic... - upload the screenshot to remote server and copy path, e.g. OBS, SCP, FTP... - extract text from the screenshot (OCR), and copy to clipboard - describe the screenshot by AI according your requirements - other: - Landing page for promo - README.md and AGENTS.md for AI and Humman developers
@@ -16,3 +16,6 @@ scripts/secrets.sh
|
||||
# IDE
|
||||
.trae/
|
||||
.vscode/
|
||||
|
||||
# OS
|
||||
*.DS_Store
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# AGENTS.md
|
||||
|
||||
## 项目概述
|
||||
|
||||
SnapGo 是一个常驻菜单栏的轻量截图工具:全局快捷键唤起选区截图,确认后自动上传到 S3 兼容对象存储(或通过 SSH/SCP 保存到远端),并把可分享链接复制到剪贴板。目前主要打磨 macOS 体验。
|
||||
|
||||
技术栈:**Wails v2**(Go 后端 + WebView 前端)+ **Vue 3 / TypeScript / Vite** 前端。Go 后端遵循分层架构(domain → application → infrastructure),macOS 上截图选区使用原生 AppKit overlay,其它平台回退到 Wails 透明窗口 overlay。
|
||||
|
||||
### 分层架构(`internal/`)
|
||||
|
||||
- `domain/`:核心业务类型与接口,**不依赖任何第三方 SDK 或 OS API**(仅标准库)。如 `OSSProvider` 接口、`AppConfig`/`S3Config`/`SSHConfig`、`Screenshot`/`UploadResult`。
|
||||
- `application/`:用例编排(capture → upload/save → clipboard → notify)。**只依赖 domain 接口**,具体适配器从 `main.go`/`app.go` 注入,便于单测。如 `CaptureAndUploadService`、`CaptureActionsService`、`CaptureAndSSHService`、`ApplyAnnotations`。
|
||||
- `infrastructure/`:对接外部世界的适配器实现 —— `oss/`(S3)、`ssh/`(内置 Go client + Kerberos 委托系统 ssh)、`clipboard/`、`config/`(JSON 文件存储)、`screencapture/`、`display/`、`cursor/`、`hotkey/`、`tray/`(菜单栏)、`logging/`。
|
||||
|
||||
### 顶层文件(`main` 包,根目录)
|
||||
|
||||
- `main.go`:Wails 启动入口,embed `frontend/dist`,装配 tray 与 `App`。
|
||||
- `app.go`:`App` 结构体,通过 Wails `Bind` 暴露给前端的方法(RPC),编排截图/上传/保存流程与 overlay 窗口生命周期。
|
||||
- `*_darwin.go` / `*_other.go`:平台分离的 overlay、dock 图标、激活策略、帧刷新等实现。`native_overlay_darwin.go` 使用 cgo + AppKit。
|
||||
|
||||
### 关键约定
|
||||
|
||||
- 前端通过 Wails 自动生成的 `frontend/wailsjs/go/main/App.js` 调用后端 `App` 的导出方法;后端通过 `wruntime.EventsEmit` 向前端推事件(如 `upload:success`、`upload:failure`、`hotkey:ready`、`capture:overlay`)。
|
||||
- 新增 OSS provider 只需在 `infrastructure/oss/` 加适配器并实现 `domain.OSSProvider`,无需改 application 层。
|
||||
- S3 与 SSH 走独立 pipeline(`runUploadPipeline` vs `runSaveRemotePipeline`),避免 provider 分支泄漏进彼此。
|
||||
|
||||
## 构建与命令
|
||||
|
||||
依赖前置:Go 1.23+、Node/npm、`wails` CLI(`go install github.com/wailsapp/wails/v2/cmd/wails@latest`)。
|
||||
|
||||
- `go mod tidy`:同步 Go 依赖。
|
||||
- `wails dev`:开发模式(热重载前端 + 后端),日志可直接在终端看到。
|
||||
- `wails build -platform darwin/arm64 -clean`:构建 `.app`(产物在 `build/bin/`)。
|
||||
- `./scripts/create-dev-cert.sh`:首次创建本地自签开发证书(保证 macOS TCC 权限不被反复重置)。
|
||||
- `./scripts/dev-build.sh`:本地迭代用 —— 构建 + 稳定证书重签名 + 同步到 `/Applications` + 打开。优先用它而非裸 `wails build`。
|
||||
- `./scripts/release.sh`:一键 build → sign → DMG → notarize(notarize 需 `NOTARIZE=1` 与凭证,默认跳过)。`ARCH=universal` 可出 fat binary。
|
||||
- 前端单独命令(`frontend/`):`npm run dev` / `npm run build`(`vue-tsc --noEmit && vite build`)/ `npm run preview`。
|
||||
|
||||
## 代码风格
|
||||
|
||||
- **Go**:标准 `gofmt`(tab 缩进)。包级 doc 注释说明“设计动机/rationale”是本仓库的强约定,注释解释“为什么”而非“是什么”。导出标识符必须有注释。错误用 `fmt.Errorf("...: %w", err)` 包装。日志统一用 `log/slog`(结构化 kv,如 `slog.Info("...", "host", h)`)。
|
||||
- **平台分离**:用 `_darwin.go` / `_other.go` 文件名后缀或 `//go:build` 标签隔离平台代码,保持跨平台编译通过。
|
||||
- **TypeScript/Vue**:Vue 3 `<script setup>` + Composition API;2 空格缩进。视图在 `frontend/src/views/`,组件在 `components/`。
|
||||
- 注释中可使用中文(部分 infra 包如 logging 已用中文 rationale),与现有文件保持一致即可。
|
||||
- 不要手改 `frontend/wailsjs/` 下文件,它们由 Wails 生成。
|
||||
|
||||
## 测试
|
||||
|
||||
- 框架:Go 标准 `testing` 包(无第三方断言库)。运行:`go test ./...`。
|
||||
- 现有测试集中在 `internal/application/`(如 `capture_actions_test.go`、`annotation_test.go`)。
|
||||
- 约定:application 层依赖 domain 接口,测试用手写 fake 实现(如 `fakeClipboard`、`fakeNotifier`)注入,不触碰真实 OS/网络。文件 IO 测试使用 `t.TempDir()`。
|
||||
- infrastructure 适配器(S3/SSH/screencapture 等)依赖真实环境,通常不写单测;SSH 连通性可借助 `cmd/sshdiag/` 诊断工具与设置页的 “Test connection” 按钮验证。
|
||||
|
||||
## 安全
|
||||
|
||||
- **凭证落盘**:配置(含 S3 access key、SSH 密码)以 JSON 存于 `os.UserConfigDir()/SnapGo/config.json`,文件权限 `0600`、目录 `0700`。尚未接入 OS keychain(后续计划),改动配置存储时务必保持严格权限并避免把密钥写入日志。
|
||||
- **日志**:写入 `~/Library/Logs/SnapGo/snapgo.log`(大小滚动,5MiB×2 备份)。记录连接信息时只记 host/user/port 等非敏感字段,**切勿记录密码/密钥**(参考 `app.go` 中的 `slog` 用法)。
|
||||
- **SSH**:`StrictHostKey=false` 时使用 `InsecureIgnoreHostKey()`(牺牲安全换首启可用性,仅限个人 LAN);Kerberos 模式委托系统 `/usr/bin/ssh` 复用 `kinit` 凭证缓存。`PathPrefix` 相对远端 `$HOME`,会剥离前导 `/` 和 `~` 防止逃逸。
|
||||
- **上传兜底**:上传失败时把 PNG 落地到 `~/Pictures/SnapGo` 并复制本地路径,保证不丢截图。
|
||||
- macOS 需 Screen Recording / Accessibility(TCC)权限;稳定的代码签名身份与安装路径是权限保持的关键(见 `dev-build.sh` 注释)。
|
||||
|
||||
## 配置
|
||||
|
||||
- Wails 项目配置:`wails.json`(产物名、frontend install/build/dev 命令、应用元信息)。
|
||||
- 运行时配置:首启写入默认值(`domain.DefaultAppConfig()`:快捷键 `cmd+shift+a`、S3 `pathPrefix=snapgo/`、SSH port 22 / timeout 10s)。原子写入(temp + rename)。
|
||||
- 环境变量:`SNAPGO_LOG_LEVEL=debug|info|warn|error`(默认 debug)。Release 相关:`ARCH`、`NOTARIZE`、`SIGN_MODE`、`DEVELOPER_ID_APPLICATION`、`KEYCHAIN_PROFILE`、`APPLE_ID`/`APPLE_TEAM_ID`/`APPLE_APP_SPECIFIC_PASSWORD`。
|
||||
- S3 兼容性:`UsePathStyle` 默认 true(适配 MinIO/R2);`PublicURLBase` 可选用于 CDN/自定义域名,否则回退 `{Endpoint}/{Bucket}/{Key}`。
|
||||
@@ -0,0 +1,36 @@
|
||||
# SnapGo
|
||||
|
||||
SnapGo 是一个以 macOS 为核心体验的截图上传工具,面向“截图后立刻分享链接”的高频场景。它常驻于菜单栏,支持全局快捷键唤起截图覆盖层,在完成区域选择后自动将图片上传到兼容 S3 协议的对象存储,并把最终公开链接写入剪贴板,尽可能减少“截图、保存、上传、复制链接”之间的手动切换成本。
|
||||
|
||||
项目当前基于 `Wails + Go + Vue 3` 构建,桌面端负责截图、热键、托盘与系统集成,前端负责设置页与截图交互界面。整体设计围绕“轻量常驻、快速触发、上传即复制”展开,适合作为个人图床工作流中的本地入口工具。
|
||||
|
||||
## 核心功能
|
||||
|
||||
- 全局快捷键截图:支持通过全局快捷键在任意应用中快速唤起截图流程。
|
||||
- 区域选择覆盖层:提供接近原生体验的截图选区交互,优先针对 macOS 做了透明覆盖层与窗口层级优化。
|
||||
- 自动上传到 S3 兼容存储:支持 AWS S3、MinIO、Cloudflare R2、Backblaze B2 及其他兼容 S3 API 的对象存储。
|
||||
- 自动复制公开链接:上传成功后自动将图片 URL 写入剪贴板,方便直接粘贴到 IM、文档或工单系统。
|
||||
- 菜单栏常驻与设置面板:通过托盘菜单进入设置,配置热键、存储参数,并测试连接可用性。
|
||||
- 上传失败兜底:当上传失败时,会将截图落盘到本地临时目录,避免截图结果丢失。
|
||||
|
||||
## 典型使用流程
|
||||
|
||||
1. 首次启动后,在设置页中填写 S3 兼容对象存储的连接信息。
|
||||
2. 保存配置并测试连通性,确认目标 Bucket 可写。
|
||||
3. 使用默认快捷键 `cmd+shift+a`,或自定义快捷键,随时发起截图。
|
||||
4. 选择需要截取的区域并确认。
|
||||
5. 应用自动上传截图,并将生成的公开链接复制到剪贴板。
|
||||
|
||||
## 项目定位
|
||||
|
||||
SnapGo 当前更偏向一个面向个人使用的高效工具,而不是“大而全”的截图平台。它的重点不在复杂标注或云端管理能力,而在于把“截图并生成可分享链接”这条链路压缩到尽可能短,尤其适合开发者、产品、测试或需要频繁在聊天工具中分享截图的用户。
|
||||
|
||||
虽然工程结构中保留了跨平台方向的设计,但现阶段的核心交互与系统集成主要围绕 macOS 打磨,包括菜单栏形态、原生覆盖层、窗口透明化处理以及与系统截图能力的衔接。因此,如果你希望获得完整体验,macOS 是当前最合适的运行平台。
|
||||
|
||||
## 技术实现概览
|
||||
|
||||
- 桌面壳与应用编排:Go + Wails
|
||||
- 设置界面与截图覆盖层:Vue 3 + TypeScript + Vite
|
||||
- 全局快捷键:`golang.design/x/hotkey`
|
||||
- 对象存储接入:AWS SDK for Go v2(S3 兼容实现)
|
||||
- macOS 截图与窗口控制:系统 `screencapture` 命令 + AppKit 原生能力
|
||||
@@ -1,10 +1,10 @@
|
||||
# SnipPicGo
|
||||
# SnapGo
|
||||
|
||||
SnipPicGo 是一个为“截完图马上发链接”而做的轻量截图工具。
|
||||
SnapGo 是一个为“截完图马上发链接”而做的轻量截图工具。
|
||||
|
||||
它常驻菜单栏,通过全局快捷键一键唤起截图,选区确认后自动上传到你自己的 S3 兼容对象存储,并把图片链接直接复制到剪贴板。你不需要再经历“截图 -> 保存本地 -> 打开图床 -> 上传 -> 复制链接”这串繁琐操作。
|
||||
|
||||
如果你经常在聊天工具、工单、文档、Issue 或 PR 里发截图,SnipPicGo 的目标就是把这件事变成一次动作。
|
||||
如果你经常在聊天工具、工单、文档、Issue 或 PR 里发截图,SnapGo 的目标就是把这件事变成一次动作。
|
||||
|
||||
## 它适合谁
|
||||
|
||||
@@ -21,6 +21,7 @@ SnipPicGo 是一个为“截完图马上发链接”而做的轻量截图工具
|
||||
- 全局快捷键触发:无论当前在什么应用里,都能快速发起截图
|
||||
- 菜单栏常驻:随用随取,不打断主流程
|
||||
- 支持 S3 兼容存储:可接入 AWS S3、MinIO、Cloudflare R2、Backblaze B2 等
|
||||
- 支持 FTP / SFTP:可通过独立截图操作上传到文件服务器,并复制远端路径
|
||||
- 支持自定义公开地址:可配合 CDN 或自定义域名使用
|
||||
- 上传失败自动兜底:至少保住截图文件,不会白截
|
||||
|
||||
@@ -31,14 +32,38 @@ SnipPicGo 是一个为“截完图马上发链接”而做的轻量截图工具
|
||||
- 更可控:图片上传到你自己的对象存储,而不是托管在陌生服务上
|
||||
- 更适合高频工作:特别适合要反复发截图沟通的人
|
||||
|
||||
# 测试版安装
|
||||
|
||||
## MacOS
|
||||
1. 进入项目目录
|
||||
- `cd /path/of/project`
|
||||
|
||||
2. 安装 go 项目依赖
|
||||
- `go mod tidy & go install github.com/wailsapp/wails/v2/cmd/wails@latest`
|
||||
|
||||
3. 生成 macos 应用开发证书(首次安装前执行)
|
||||
- `./scripts/create-dev-cert.sh`
|
||||
|
||||
4. 检查证书(首次安装前执行)
|
||||
- `security find-identity -v -p codesigning`
|
||||
你应当能看到类似下面的显示(一条或两条)
|
||||
```bash
|
||||
2) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "SnapGo Dev Cert"
|
||||
3) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "SnapGo Dev Cert"
|
||||
```
|
||||
|
||||
5. 安装 & 打开应用
|
||||
- `./scripts/dev-build.sh`
|
||||
然后你就可以在应用列表里看到它了
|
||||
|
||||
## 使用方式
|
||||
|
||||
1. 打开应用,填写你的 S3 兼容对象存储配置
|
||||
1. 打开应用,填写 S3、FTP / SFTP 或 SSH 远端配置
|
||||
2. 保存并测试连接
|
||||
3. 按下默认快捷键 `cmd+shift+a`
|
||||
4. 框选截图区域
|
||||
5. 直接粘贴刚刚自动复制好的图片链接
|
||||
5. 点击目标上传按钮,直接粘贴自动复制的图片链接或远端路径
|
||||
|
||||
## 当前体验
|
||||
|
||||
SnipPicGo 当前主要围绕 macOS 打磨体验。如果你希望获得完整、顺滑的截图上传工作流,macOS 是目前最推荐的使用平台。
|
||||
SnapGo 当前主要围绕 macOS 打磨体验。如果你希望获得完整、顺滑的截图上传工作流,macOS 是目前最推荐的使用平台。
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//go:build darwin
|
||||
|
||||
package main
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
||||
#cgo LDFLAGS: -framework AppKit
|
||||
// Silence the "ignoring duplicate libraries: '-lobjc'" note emitted by the
|
||||
// Xcode 15+ linker (ld-prime): cgo links -lobjc for our Objective-C code and
|
||||
// the Go darwin runtime pulls it in as well, which the new linker flags as a
|
||||
// duplicate. Suppressing it here keeps the build output clean; the flag is a
|
||||
// no-op on the legacy ld64 path.
|
||||
#cgo LDFLAGS: -Wl,-no_warn_duplicate_libraries
|
||||
#include <dispatch/dispatch.h>
|
||||
#import <AppKit/AppKit.h>
|
||||
|
||||
static id snipDidHideObserver = nil;
|
||||
|
||||
static void snipSetActivationPolicy(bool regular, bool activate) {
|
||||
void (^work)(void) = ^{
|
||||
[NSApp setActivationPolicy: regular
|
||||
? NSApplicationActivationPolicyRegular
|
||||
: NSApplicationActivationPolicyAccessory];
|
||||
if (activate) {
|
||||
[NSApp unhide:nil];
|
||||
[NSApp activateIgnoringOtherApps:YES];
|
||||
}
|
||||
};
|
||||
|
||||
if ([NSThread isMainThread]) {
|
||||
work();
|
||||
} else {
|
||||
dispatch_sync(dispatch_get_main_queue(), work);
|
||||
}
|
||||
}
|
||||
|
||||
static void snipInstallActivationPolicyHooks(void) {
|
||||
void (^work)(void) = ^{
|
||||
if (snipDidHideObserver != nil) {
|
||||
return;
|
||||
}
|
||||
snipDidHideObserver = [[NSNotificationCenter defaultCenter]
|
||||
addObserverForName:NSApplicationDidHideNotification
|
||||
object:NSApp
|
||||
queue:[NSOperationQueue mainQueue]
|
||||
usingBlock:^(__unused NSNotification *note) {
|
||||
[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
|
||||
}];
|
||||
};
|
||||
|
||||
if ([NSThread isMainThread]) {
|
||||
work();
|
||||
} else {
|
||||
dispatch_sync(dispatch_get_main_queue(), work);
|
||||
}
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
|
||||
// installActivationPolicyHooks observes the native hide path used by Wails'
|
||||
// HideWindowOnClose on macOS. Closing Settings calls `[NSApp hide:nil]`,
|
||||
// which does not reliably pass through Wails' Go OnBeforeClose hook.
|
||||
func installActivationPolicyHooks() {
|
||||
C.snipInstallActivationPolicyHooks()
|
||||
}
|
||||
|
||||
// showDockIcon makes the app behave like a normal foreground macOS app while
|
||||
// Settings is visible.
|
||||
func showDockIcon(activate bool) {
|
||||
C.snipSetActivationPolicy(true, C.bool(activate))
|
||||
}
|
||||
|
||||
// hideDockIcon returns the app to menu-bar-agent mode: no persistent Dock
|
||||
// icon, while the status-bar item remains available.
|
||||
func hideDockIcon() {
|
||||
C.snipSetActivationPolicy(false, false)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !darwin
|
||||
|
||||
package main
|
||||
|
||||
// installActivationPolicyHooks is only meaningful on macOS.
|
||||
func installActivationPolicyHooks() {}
|
||||
|
||||
// showDockIcon is only meaningful on macOS.
|
||||
func showDockIcon(_ bool) {}
|
||||
|
||||
// hideDockIcon is only meaningful on macOS.
|
||||
func hideDockIcon() {}
|
||||
@@ -0,0 +1,35 @@
|
||||
# Build Directory
|
||||
|
||||
The build directory is used to house all the build files and assets for your application.
|
||||
|
||||
The structure is:
|
||||
|
||||
* bin - Output directory
|
||||
* darwin - macOS specific files
|
||||
* windows - Windows specific files
|
||||
|
||||
## Mac
|
||||
|
||||
The `darwin` directory holds files specific to Mac builds.
|
||||
These may be customised and used as part of the build. To return these files to the default state, simply delete them
|
||||
and
|
||||
build with `wails build`.
|
||||
|
||||
The directory contains the following files:
|
||||
|
||||
- `Info.plist` - the main plist file used for Mac builds. It is used when building using `wails build`.
|
||||
- `Info.dev.plist` - same as the main plist file but used when building using `wails dev`.
|
||||
|
||||
## Windows
|
||||
|
||||
The `windows` directory contains the manifest and rc files used when building with `wails build`.
|
||||
These may be customised for your application. To return these files to the default state, simply delete them and
|
||||
build with `wails build`.
|
||||
|
||||
- `icon.ico` - The icon used for the application. This is used when building using `wails build`. If you wish to
|
||||
use a different icon, simply replace this file with your own. If it is missing, a new `icon.ico` file
|
||||
will be created using the `appicon.png` file in the build directory.
|
||||
- `installer/*` - The files used to create the Windows installer. These are used when building using `wails build`.
|
||||
- `info.json` - Application details used for Windows builds. The data here will be used by the Windows installer,
|
||||
as well as the application itself (right click the exe -> properties -> details)
|
||||
- `wails.exe.manifest` - The main application manifest file.
|
||||
|
After Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,74 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>{{.Info.ProductName}}</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>{{.OutputFilename}}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>io.snapgo.app</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>{{.Info.ProductVersion}}</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>{{.Info.Comments}}</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>{{.Info.ProductVersion}}</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>iconfile</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>11.0.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<string>true</string>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>NSAppleEventsUsageDescription</key>
|
||||
<string>SnapGo needs Apple Events access to capture the active window.</string>
|
||||
<key>NSScreenCaptureUsageDescription</key>
|
||||
<string>SnapGo needs screen recording permission to capture screenshots.</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>{{.Info.Copyright}}</string>
|
||||
{{if .Info.FileAssociations}}
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
{{range .Info.FileAssociations}}
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>{{.Ext}}</string>
|
||||
</array>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>{{.Name}}</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>{{.Role}}</string>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>{{.IconName}}</string>
|
||||
</dict>
|
||||
{{end}}
|
||||
</array>
|
||||
{{end}}
|
||||
{{if .Info.Protocols}}
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
{{range .Info.Protocols}}
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>com.wails.{{.Scheme}}</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>{{.Scheme}}</string>
|
||||
</array>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>{{.Role}}</string>
|
||||
</dict>
|
||||
{{end}}
|
||||
</array>
|
||||
{{end}}
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,75 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>{{.Info.ProductName}}</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>{{.OutputFilename}}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>io.snapgo.app</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>{{.Info.ProductVersion}}</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>{{.Info.Comments}}</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>{{.Info.ProductVersion}}</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>iconfile</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>11.0.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<string>true</string>
|
||||
<!--
|
||||
LSUIElement=true turns the app into a "menu-bar agent": it does
|
||||
NOT show up in the Dock, has no application menu, and is driven
|
||||
entirely from a menu-bar icon. Mirrors apps like Snipaste,
|
||||
Bartender, Itsycal, etc.
|
||||
-->
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>NSAppleEventsUsageDescription</key>
|
||||
<string>SnapGo needs Apple Events access to capture the active window.</string>
|
||||
<key>NSScreenCaptureUsageDescription</key>
|
||||
<string>SnapGo needs screen recording permission to capture screenshots.</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>{{.Info.Copyright}}</string>
|
||||
{{if .Info.FileAssociations}}
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
{{range .Info.FileAssociations}}
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>{{.Ext}}</string>
|
||||
</array>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>{{.Name}}</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>{{.Role}}</string>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>{{.IconName}}</string>
|
||||
</dict>
|
||||
{{end}}
|
||||
</array>
|
||||
{{end}}
|
||||
{{if .Info.Protocols}}
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
{{range .Info.Protocols}}
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>com.wails.{{.Scheme}}</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>{{.Scheme}}</string>
|
||||
</array>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>{{.Role}}</string>
|
||||
</dict>
|
||||
{{end}}
|
||||
</array>
|
||||
{{end}}
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Hardened Runtime entitlements for SnapGo on macOS.
|
||||
|
||||
Design rationale:
|
||||
- Hardened Runtime is REQUIRED for notarization (Apple Notary Service).
|
||||
- We deliberately keep entitlements MINIMAL: only what the screenshot tool
|
||||
actually needs. Granting more increases attack surface and slows review.
|
||||
- JIT / unsigned-executable-memory is enabled because the embedded WebView
|
||||
(WKWebView via wails) needs JS JIT.
|
||||
- We do NOT enable App Sandbox: the app uses /usr/sbin/screencapture and a
|
||||
global hotkey that requires non-sandboxed access. (App Sandbox + screen
|
||||
recording requires extra plumbing not in MVP scope.)
|
||||
-->
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Allow JIT for WKWebView JavaScript engine -->
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
|
||||
<!-- Allow unsigned executable memory pages used by JIT -->
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
|
||||
<!-- Allow loading dylibs not signed by the same team (Wails runtime needs this on some setups) -->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
|
||||
<!-- Outbound network for S3 / OSS uploads -->
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
|
||||
<!--
|
||||
Apple Events: required to invoke /usr/sbin/screencapture and to query
|
||||
display info via system_profiler. Combined with NSAppleEventsUsageDescription
|
||||
in Info.plist, this triggers the standard TCC prompt.
|
||||
-->
|
||||
<key>com.apple.security.automation.apple-events</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"fixed": {
|
||||
"file_version": "{{.Info.ProductVersion}}"
|
||||
},
|
||||
"info": {
|
||||
"0000": {
|
||||
"ProductVersion": "{{.Info.ProductVersion}}",
|
||||
"CompanyName": "{{.Info.CompanyName}}",
|
||||
"FileDescription": "{{.Info.ProductName}}",
|
||||
"LegalCopyright": "{{.Info.Copyright}}",
|
||||
"ProductName": "{{.Info.ProductName}}",
|
||||
"Comments": "{{.Info.Comments}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
Unicode true
|
||||
|
||||
####
|
||||
## Please note: Template replacements don't work in this file. They are provided with default defines like
|
||||
## mentioned underneath.
|
||||
## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo.
|
||||
## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually
|
||||
## from outside of Wails for debugging and development of the installer.
|
||||
##
|
||||
## For development first make a wails nsis build to populate the "wails_tools.nsh":
|
||||
## > wails build --target windows/amd64 --nsis
|
||||
## Then you can call makensis on this file with specifying the path to your binary:
|
||||
## For a AMD64 only installer:
|
||||
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app.exe
|
||||
## For a ARM64 only installer:
|
||||
## > makensis -DARG_WAILS_ARM64_BINARY=..\..\bin\app.exe
|
||||
## For a installer with both architectures:
|
||||
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe
|
||||
####
|
||||
## The following information is taken from the ProjectInfo file, but they can be overwritten here.
|
||||
####
|
||||
## !define INFO_PROJECTNAME "MyProject" # Default "{{.Name}}"
|
||||
## !define INFO_COMPANYNAME "MyCompany" # Default "{{.Info.CompanyName}}"
|
||||
## !define INFO_PRODUCTNAME "MyProduct" # Default "{{.Info.ProductName}}"
|
||||
## !define INFO_PRODUCTVERSION "1.0.0" # Default "{{.Info.ProductVersion}}"
|
||||
## !define INFO_COPYRIGHT "Copyright" # Default "{{.Info.Copyright}}"
|
||||
###
|
||||
## !define PRODUCT_EXECUTABLE "Application.exe" # Default "${INFO_PROJECTNAME}.exe"
|
||||
## !define UNINST_KEY_NAME "UninstKeyInRegistry" # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"
|
||||
####
|
||||
## !define REQUEST_EXECUTION_LEVEL "admin" # Default "admin" see also https://nsis.sourceforge.io/Docs/Chapter4.html
|
||||
####
|
||||
## Include the wails tools
|
||||
####
|
||||
!include "wails_tools.nsh"
|
||||
|
||||
# The version information for this two must consist of 4 parts
|
||||
VIProductVersion "${INFO_PRODUCTVERSION}.0"
|
||||
VIFileVersion "${INFO_PRODUCTVERSION}.0"
|
||||
|
||||
VIAddVersionKey "CompanyName" "${INFO_COMPANYNAME}"
|
||||
VIAddVersionKey "FileDescription" "${INFO_PRODUCTNAME} Installer"
|
||||
VIAddVersionKey "ProductVersion" "${INFO_PRODUCTVERSION}"
|
||||
VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}"
|
||||
VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}"
|
||||
VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}"
|
||||
|
||||
# Enable HiDPI support. https://nsis.sourceforge.io/Reference/ManifestDPIAware
|
||||
ManifestDPIAware true
|
||||
|
||||
!include "MUI.nsh"
|
||||
|
||||
!define MUI_ICON "..\icon.ico"
|
||||
!define MUI_UNICON "..\icon.ico"
|
||||
# !define MUI_WELCOMEFINISHPAGE_BITMAP "resources\leftimage.bmp" #Include this to add a bitmap on the left side of the Welcome Page. Must be a size of 164x314
|
||||
!define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps
|
||||
!define MUI_ABORTWARNING # This will warn the user if they exit from the installer.
|
||||
|
||||
!insertmacro MUI_PAGE_WELCOME # Welcome to the installer page.
|
||||
# !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer
|
||||
!insertmacro MUI_PAGE_DIRECTORY # In which folder install page.
|
||||
!insertmacro MUI_PAGE_INSTFILES # Installing page.
|
||||
!insertmacro MUI_PAGE_FINISH # Finished installation page.
|
||||
|
||||
!insertmacro MUI_UNPAGE_INSTFILES # Uinstalling page
|
||||
|
||||
!insertmacro MUI_LANGUAGE "English" # Set the Language of the installer
|
||||
|
||||
## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1
|
||||
#!uninstfinalize 'signtool --file "%1"'
|
||||
#!finalize 'signtool --file "%1"'
|
||||
|
||||
Name "${INFO_PRODUCTNAME}"
|
||||
OutFile "..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file.
|
||||
InstallDir "$PROGRAMFILES64\${INFO_COMPANYNAME}\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder).
|
||||
ShowInstDetails show # This will always show the installation details.
|
||||
|
||||
Function .onInit
|
||||
!insertmacro wails.checkArchitecture
|
||||
FunctionEnd
|
||||
|
||||
Section
|
||||
!insertmacro wails.setShellContext
|
||||
|
||||
!insertmacro wails.webview2runtime
|
||||
|
||||
SetOutPath $INSTDIR
|
||||
|
||||
!insertmacro wails.files
|
||||
|
||||
CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
|
||||
CreateShortCut "$DESKTOP\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
|
||||
|
||||
!insertmacro wails.associateFiles
|
||||
!insertmacro wails.associateCustomProtocols
|
||||
|
||||
!insertmacro wails.writeUninstaller
|
||||
SectionEnd
|
||||
|
||||
Section "uninstall"
|
||||
!insertmacro wails.setShellContext
|
||||
|
||||
RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath
|
||||
|
||||
RMDir /r $INSTDIR
|
||||
|
||||
Delete "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk"
|
||||
Delete "$DESKTOP\${INFO_PRODUCTNAME}.lnk"
|
||||
|
||||
!insertmacro wails.unassociateFiles
|
||||
!insertmacro wails.unassociateCustomProtocols
|
||||
|
||||
!insertmacro wails.deleteUninstaller
|
||||
SectionEnd
|
||||
@@ -0,0 +1,249 @@
|
||||
# DO NOT EDIT - Generated automatically by `wails build`
|
||||
|
||||
!include "x64.nsh"
|
||||
!include "WinVer.nsh"
|
||||
!include "FileFunc.nsh"
|
||||
|
||||
!ifndef INFO_PROJECTNAME
|
||||
!define INFO_PROJECTNAME "{{.Name}}"
|
||||
!endif
|
||||
!ifndef INFO_COMPANYNAME
|
||||
!define INFO_COMPANYNAME "{{.Info.CompanyName}}"
|
||||
!endif
|
||||
!ifndef INFO_PRODUCTNAME
|
||||
!define INFO_PRODUCTNAME "{{.Info.ProductName}}"
|
||||
!endif
|
||||
!ifndef INFO_PRODUCTVERSION
|
||||
!define INFO_PRODUCTVERSION "{{.Info.ProductVersion}}"
|
||||
!endif
|
||||
!ifndef INFO_COPYRIGHT
|
||||
!define INFO_COPYRIGHT "{{.Info.Copyright}}"
|
||||
!endif
|
||||
!ifndef PRODUCT_EXECUTABLE
|
||||
!define PRODUCT_EXECUTABLE "${INFO_PROJECTNAME}.exe"
|
||||
!endif
|
||||
!ifndef UNINST_KEY_NAME
|
||||
!define UNINST_KEY_NAME "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"
|
||||
!endif
|
||||
!define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${UNINST_KEY_NAME}"
|
||||
|
||||
!ifndef REQUEST_EXECUTION_LEVEL
|
||||
!define REQUEST_EXECUTION_LEVEL "admin"
|
||||
!endif
|
||||
|
||||
RequestExecutionLevel "${REQUEST_EXECUTION_LEVEL}"
|
||||
|
||||
!ifdef ARG_WAILS_AMD64_BINARY
|
||||
!define SUPPORTS_AMD64
|
||||
!endif
|
||||
|
||||
!ifdef ARG_WAILS_ARM64_BINARY
|
||||
!define SUPPORTS_ARM64
|
||||
!endif
|
||||
|
||||
!ifdef SUPPORTS_AMD64
|
||||
!ifdef SUPPORTS_ARM64
|
||||
!define ARCH "amd64_arm64"
|
||||
!else
|
||||
!define ARCH "amd64"
|
||||
!endif
|
||||
!else
|
||||
!ifdef SUPPORTS_ARM64
|
||||
!define ARCH "arm64"
|
||||
!else
|
||||
!error "Wails: Undefined ARCH, please provide at least one of ARG_WAILS_AMD64_BINARY or ARG_WAILS_ARM64_BINARY"
|
||||
!endif
|
||||
!endif
|
||||
|
||||
!macro wails.checkArchitecture
|
||||
!ifndef WAILS_WIN10_REQUIRED
|
||||
!define WAILS_WIN10_REQUIRED "This product is only supported on Windows 10 (Server 2016) and later."
|
||||
!endif
|
||||
|
||||
!ifndef WAILS_ARCHITECTURE_NOT_SUPPORTED
|
||||
!define WAILS_ARCHITECTURE_NOT_SUPPORTED "This product can't be installed on the current Windows architecture. Supports: ${ARCH}"
|
||||
!endif
|
||||
|
||||
${If} ${AtLeastWin10}
|
||||
!ifdef SUPPORTS_AMD64
|
||||
${if} ${IsNativeAMD64}
|
||||
Goto ok
|
||||
${EndIf}
|
||||
!endif
|
||||
|
||||
!ifdef SUPPORTS_ARM64
|
||||
${if} ${IsNativeARM64}
|
||||
Goto ok
|
||||
${EndIf}
|
||||
!endif
|
||||
|
||||
IfSilent silentArch notSilentArch
|
||||
silentArch:
|
||||
SetErrorLevel 65
|
||||
Abort
|
||||
notSilentArch:
|
||||
MessageBox MB_OK "${WAILS_ARCHITECTURE_NOT_SUPPORTED}"
|
||||
Quit
|
||||
${else}
|
||||
IfSilent silentWin notSilentWin
|
||||
silentWin:
|
||||
SetErrorLevel 64
|
||||
Abort
|
||||
notSilentWin:
|
||||
MessageBox MB_OK "${WAILS_WIN10_REQUIRED}"
|
||||
Quit
|
||||
${EndIf}
|
||||
|
||||
ok:
|
||||
!macroend
|
||||
|
||||
!macro wails.files
|
||||
!ifdef SUPPORTS_AMD64
|
||||
${if} ${IsNativeAMD64}
|
||||
File "/oname=${PRODUCT_EXECUTABLE}" "${ARG_WAILS_AMD64_BINARY}"
|
||||
${EndIf}
|
||||
!endif
|
||||
|
||||
!ifdef SUPPORTS_ARM64
|
||||
${if} ${IsNativeARM64}
|
||||
File "/oname=${PRODUCT_EXECUTABLE}" "${ARG_WAILS_ARM64_BINARY}"
|
||||
${EndIf}
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro wails.writeUninstaller
|
||||
WriteUninstaller "$INSTDIR\uninstall.exe"
|
||||
|
||||
SetRegView 64
|
||||
WriteRegStr HKLM "${UNINST_KEY}" "Publisher" "${INFO_COMPANYNAME}"
|
||||
WriteRegStr HKLM "${UNINST_KEY}" "DisplayName" "${INFO_PRODUCTNAME}"
|
||||
WriteRegStr HKLM "${UNINST_KEY}" "DisplayVersion" "${INFO_PRODUCTVERSION}"
|
||||
WriteRegStr HKLM "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\${PRODUCT_EXECUTABLE}"
|
||||
WriteRegStr HKLM "${UNINST_KEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
|
||||
WriteRegStr HKLM "${UNINST_KEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
|
||||
|
||||
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
|
||||
IntFmt $0 "0x%08X" $0
|
||||
WriteRegDWORD HKLM "${UNINST_KEY}" "EstimatedSize" "$0"
|
||||
!macroend
|
||||
|
||||
!macro wails.deleteUninstaller
|
||||
Delete "$INSTDIR\uninstall.exe"
|
||||
|
||||
SetRegView 64
|
||||
DeleteRegKey HKLM "${UNINST_KEY}"
|
||||
!macroend
|
||||
|
||||
!macro wails.setShellContext
|
||||
${If} ${REQUEST_EXECUTION_LEVEL} == "admin"
|
||||
SetShellVarContext all
|
||||
${else}
|
||||
SetShellVarContext current
|
||||
${EndIf}
|
||||
!macroend
|
||||
|
||||
# Install webview2 by launching the bootstrapper
|
||||
# See https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#online-only-deployment
|
||||
!macro wails.webview2runtime
|
||||
!ifndef WAILS_INSTALL_WEBVIEW_DETAILPRINT
|
||||
!define WAILS_INSTALL_WEBVIEW_DETAILPRINT "Installing: WebView2 Runtime"
|
||||
!endif
|
||||
|
||||
SetRegView 64
|
||||
# If the admin key exists and is not empty then webview2 is already installed
|
||||
ReadRegStr $0 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
|
||||
${If} $0 != ""
|
||||
Goto ok
|
||||
${EndIf}
|
||||
|
||||
${If} ${REQUEST_EXECUTION_LEVEL} == "user"
|
||||
# If the installer is run in user level, check the user specific key exists and is not empty then webview2 is already installed
|
||||
ReadRegStr $0 HKCU "Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
|
||||
${If} $0 != ""
|
||||
Goto ok
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
SetDetailsPrint both
|
||||
DetailPrint "${WAILS_INSTALL_WEBVIEW_DETAILPRINT}"
|
||||
SetDetailsPrint listonly
|
||||
|
||||
InitPluginsDir
|
||||
CreateDirectory "$pluginsdir\webview2bootstrapper"
|
||||
SetOutPath "$pluginsdir\webview2bootstrapper"
|
||||
File "tmp\MicrosoftEdgeWebview2Setup.exe"
|
||||
ExecWait '"$pluginsdir\webview2bootstrapper\MicrosoftEdgeWebview2Setup.exe" /silent /install'
|
||||
|
||||
SetDetailsPrint both
|
||||
ok:
|
||||
!macroend
|
||||
|
||||
# Copy of APP_ASSOCIATE and APP_UNASSOCIATE macros from here https://gist.github.com/nikku/281d0ef126dbc215dd58bfd5b3a5cd5b
|
||||
!macro APP_ASSOCIATE EXT FILECLASS DESCRIPTION ICON COMMANDTEXT COMMAND
|
||||
; Backup the previously associated file class
|
||||
ReadRegStr $R0 SHELL_CONTEXT "Software\Classes\.${EXT}" ""
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "${FILECLASS}_backup" "$R0"
|
||||
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "" "${FILECLASS}"
|
||||
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}" "" `${DESCRIPTION}`
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\DefaultIcon" "" `${ICON}`
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell" "" "open"
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell\open" "" `${COMMANDTEXT}`
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell\open\command" "" `${COMMAND}`
|
||||
!macroend
|
||||
|
||||
!macro APP_UNASSOCIATE EXT FILECLASS
|
||||
; Backup the previously associated file class
|
||||
ReadRegStr $R0 SHELL_CONTEXT "Software\Classes\.${EXT}" `${FILECLASS}_backup`
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "" "$R0"
|
||||
|
||||
DeleteRegKey SHELL_CONTEXT `Software\Classes\${FILECLASS}`
|
||||
!macroend
|
||||
|
||||
!macro wails.associateFiles
|
||||
; Create file associations
|
||||
{{range .Info.FileAssociations}}
|
||||
!insertmacro APP_ASSOCIATE "{{.Ext}}" "{{.Name}}" "{{.Description}}" "$INSTDIR\{{.IconName}}.ico" "Open with ${INFO_PRODUCTNAME}" "$INSTDIR\${PRODUCT_EXECUTABLE} $\"%1$\""
|
||||
|
||||
File "..\{{.IconName}}.ico"
|
||||
{{end}}
|
||||
!macroend
|
||||
|
||||
!macro wails.unassociateFiles
|
||||
; Delete app associations
|
||||
{{range .Info.FileAssociations}}
|
||||
!insertmacro APP_UNASSOCIATE "{{.Ext}}" "{{.Name}}"
|
||||
|
||||
Delete "$INSTDIR\{{.IconName}}.ico"
|
||||
{{end}}
|
||||
!macroend
|
||||
|
||||
!macro CUSTOM_PROTOCOL_ASSOCIATE PROTOCOL DESCRIPTION ICON COMMAND
|
||||
DeleteRegKey SHELL_CONTEXT "Software\Classes\${PROTOCOL}"
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}" "" "${DESCRIPTION}"
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}" "URL Protocol" ""
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\DefaultIcon" "" "${ICON}"
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell" "" ""
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell\open" "" ""
|
||||
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell\open\command" "" "${COMMAND}"
|
||||
!macroend
|
||||
|
||||
!macro CUSTOM_PROTOCOL_UNASSOCIATE PROTOCOL
|
||||
DeleteRegKey SHELL_CONTEXT "Software\Classes\${PROTOCOL}"
|
||||
!macroend
|
||||
|
||||
!macro wails.associateCustomProtocols
|
||||
; Create custom protocols associations
|
||||
{{range .Info.Protocols}}
|
||||
!insertmacro CUSTOM_PROTOCOL_ASSOCIATE "{{.Scheme}}" "{{.Description}}" "$INSTDIR\${PRODUCT_EXECUTABLE},0" "$INSTDIR\${PRODUCT_EXECUTABLE} $\"%1$\""
|
||||
|
||||
{{end}}
|
||||
!macroend
|
||||
|
||||
!macro wails.unassociateCustomProtocols
|
||||
; Delete app custom protocol associations
|
||||
{{range .Info.Protocols}}
|
||||
!insertmacro CUSTOM_PROTOCOL_UNASSOCIATE "{{.Scheme}}"
|
||||
{{end}}
|
||||
!macroend
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
|
||||
<assemblyIdentity type="win32" name="com.wails.{{.Name}}" version="{{.Info.ProductVersion}}.0" processorArchitecture="*"/>
|
||||
<dependency>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
|
||||
</dependentAssembly>
|
||||
</dependency>
|
||||
<asmv3:application>
|
||||
<asmv3:windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <!-- fallback for Windows 7 and 8 -->
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness> <!-- falls back to per-monitor if per-monitor v2 is not supported -->
|
||||
</asmv3:windowsSettings>
|
||||
</asmv3:application>
|
||||
</assembly>
|
||||
@@ -0,0 +1,14 @@
|
||||
// flush_frame.go provides a tiny helper that yields the current goroutine
|
||||
// long enough for the OS compositor to redraw after WindowHide / Unfullscreen.
|
||||
//
|
||||
// Without this, the screenshot can include the just-hidden overlay window
|
||||
// because Cocoa hasn't redrawn yet by the time we ask for the pixels.
|
||||
package main
|
||||
|
||||
import "time"
|
||||
|
||||
func flushFrame() {
|
||||
// 80ms is empirically enough on Apple Silicon at 120Hz; on slower devices
|
||||
// the worst case is a single redraw delay, still imperceptible to the user.
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Vue 3 + TypeScript + Vite
|
||||
|
||||
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue
|
||||
3 `<script setup>` SFCs, check out
|
||||
the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar)
|
||||
|
||||
## Type Support For `.vue` Imports in TS
|
||||
|
||||
Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type
|
||||
by default. In most cases this is fine if you don't really care about component prop types outside of templates.
|
||||
However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using
|
||||
manual `h(...)` calls), you can enable Volar's Take Over mode by following these steps:
|
||||
|
||||
1. Run `Extensions: Show Built-in Extensions` from VS Code's command palette, look
|
||||
for `TypeScript and JavaScript Language Features`, then right click and select `Disable (Workspace)`. By default,
|
||||
Take Over mode will enable itself if the default TypeScript extension is disabled.
|
||||
2. Reload the VS Code window by running `Developer: Reload Window` from the command palette.
|
||||
|
||||
You can learn more about Take Over mode [here](https://github.com/johnsoncodehk/volar/discussions/471).
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||
<title>SnapGo</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="./src/main.ts" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"test": "node --test tests/*.test.ts",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.2.37"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^3.0.3",
|
||||
"typescript": "^4.6.4",
|
||||
"vite": "^3.0.7",
|
||||
"vue-tsc": "^1.8.27",
|
||||
"@babel/types": "^7.18.10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
e2d56b98c3c8ae5968db0bbb461b5615
|
||||
@@ -0,0 +1,585 @@
|
||||
<script setup lang="ts">
|
||||
/*
|
||||
* App shell — switches between two distinct UI modes that share the same
|
||||
* Wails window:
|
||||
*
|
||||
* • "settings" : full settings UI (native title bar + sidebar + form).
|
||||
* • "overlay" : Snipaste-style region picker that fills the whole
|
||||
* primary display.
|
||||
*
|
||||
* The Go side resizes/positions/flag-flips the window for each mode and
|
||||
* emits a `capture:overlay` event with the screenshot payload so the
|
||||
* frontend knows when (and what) to render.
|
||||
*/
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import SettingsView from './views/SettingsView.vue'
|
||||
import Toast from './components/Toast.vue'
|
||||
import CaptureOverlay from './views/CaptureOverlay.vue'
|
||||
import { EventsOn, EventsOff } from '../wailsjs/runtime/runtime'
|
||||
import {
|
||||
RetryRegisterHotkey,
|
||||
ConfirmRegion,
|
||||
CopyRegionImage,
|
||||
SaveRegionImage,
|
||||
SaveRegionToRemote,
|
||||
UploadRegionToFTP,
|
||||
SummarizeRegion,
|
||||
ExtractTextRegion,
|
||||
CancelRegion,
|
||||
GetConfig,
|
||||
} from '../wailsjs/go/main/App'
|
||||
|
||||
type HotkeyStatus =
|
||||
| { state: 'unknown' }
|
||||
| { state: 'ok'; spec: string }
|
||||
| { state: 'error'; reason: string }
|
||||
const hotkeyStatus = ref<HotkeyStatus>({ state: 'unknown' })
|
||||
|
||||
type Mode = 'settings' | 'overlay'
|
||||
const mode = ref<Mode>('settings')
|
||||
|
||||
type ThemeMode = 'auto' | 'light' | 'dark'
|
||||
const themeMode = ref<ThemeMode>('auto')
|
||||
const appThemeClass = computed(() => `theme-${themeMode.value}`)
|
||||
|
||||
function normalizeTheme(theme: unknown): ThemeMode {
|
||||
return theme === 'light' || theme === 'dark' || theme === 'auto'
|
||||
? theme
|
||||
: 'auto'
|
||||
}
|
||||
|
||||
async function loadThemePreference() {
|
||||
try {
|
||||
const cfg = await GetConfig()
|
||||
themeMode.value = normalizeTheme((cfg as any)?.theme)
|
||||
} catch {
|
||||
themeMode.value = 'auto'
|
||||
}
|
||||
}
|
||||
|
||||
// `SettingsTab` is hoisted to the App shell so the sidebar (which lives
|
||||
// here) and the inner SettingsView (which renders the matching card) can
|
||||
// share a single source of truth without an event bus.
|
||||
type SettingsTab = 'general' | 's3' | 'ftp' | 'ssh' | 'llm' | 'ocr'
|
||||
const activeTab = ref<SettingsTab>('general')
|
||||
|
||||
// Sidebar entries are declarative so adding a destination type later is
|
||||
// a one-line change. The label values match the user-facing tab names.
|
||||
const sidebarItems: Array<{ id: SettingsTab; label: string }> = [
|
||||
{ id: 'general', label: '通用设置' },
|
||||
{ id: 's3', label: '对象存储' },
|
||||
{ id: 'ftp', label: '文件服务' },
|
||||
{ id: 'ssh', label: '远程主机' },
|
||||
{ id: 'llm', label: '智能识图' },
|
||||
{ id: 'ocr', label: '文字提取' },
|
||||
]
|
||||
|
||||
interface OverlayPayload {
|
||||
cssWidth: number
|
||||
cssHeight: number
|
||||
scale: number
|
||||
}
|
||||
const overlayPayload = ref<OverlayPayload | null>(null)
|
||||
|
||||
interface OverlayAnnotation {
|
||||
tool: string
|
||||
color: string
|
||||
points: Array<{ x: number; y: number }>
|
||||
text?: string
|
||||
strokeWidth?: number
|
||||
fontSize?: number
|
||||
}
|
||||
|
||||
interface OverlayResult {
|
||||
rect: {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
annotations: OverlayAnnotation[]
|
||||
}
|
||||
|
||||
const capturing = ref(false)
|
||||
|
||||
const toast = ref<{ kind: 'success' | 'error'; text: string } | null>(null)
|
||||
let toastTimer: number | undefined
|
||||
|
||||
const operationStatus = ref<{
|
||||
operation: string
|
||||
phase: string
|
||||
message: string
|
||||
state: 'running' | 'success' | 'error'
|
||||
} | null>(null)
|
||||
let operationTimer: number | undefined
|
||||
|
||||
function showToast(kind: 'success' | 'error', text: string) {
|
||||
toast.value = { kind, text }
|
||||
window.clearTimeout(toastTimer)
|
||||
toastTimer = window.setTimeout(() => {
|
||||
toast.value = null
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
function updateOperationStatus(payload: {
|
||||
operation: string
|
||||
phase: string
|
||||
message: string
|
||||
state: 'running' | 'success' | 'error'
|
||||
}) {
|
||||
operationStatus.value = payload
|
||||
window.clearTimeout(operationTimer)
|
||||
if (payload.state !== 'running') {
|
||||
operationTimer = window.setTimeout(() => {
|
||||
operationStatus.value = null
|
||||
}, payload.state === 'success' ? 1600 : 3200)
|
||||
}
|
||||
}
|
||||
|
||||
async function retryHotkey() {
|
||||
try {
|
||||
await RetryRegisterHotkey()
|
||||
} catch {
|
||||
/* Surfaced via hotkey:error */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlayConfirm(rect: OverlayResult) {
|
||||
// Optimistically swap back so the window does not visually lag the
|
||||
// Go-side hide. If upload fails, the toast surfaces the reason.
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await ConfirmRegion(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlayCopy(rect: OverlayResult) {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await CopyRegionImage(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlaySave(rect: OverlayResult) {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await SaveRegionImage(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlaySaveRemote(rect: OverlayResult) {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await SaveRegionToRemote(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlayUploadFTP(rect: OverlayResult) {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await UploadRegionToFTP(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlaySummarize(rect: OverlayResult) {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await SummarizeRegion(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlayOCR(rect: OverlayResult) {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await ExtractTextRegion(rect as any)
|
||||
} catch {
|
||||
/* Surfaced via upload:failure */
|
||||
}
|
||||
}
|
||||
|
||||
async function onOverlayCancel() {
|
||||
mode.value = 'settings'
|
||||
overlayPayload.value = null
|
||||
try {
|
||||
await CancelRegion()
|
||||
} catch {
|
||||
/* Best-effort */
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadThemePreference()
|
||||
EventsOn('capture:start', () => {
|
||||
capturing.value = true
|
||||
})
|
||||
EventsOn('capture:end', () => {
|
||||
capturing.value = false
|
||||
})
|
||||
EventsOn('capture:cancelled', () => {
|
||||
capturing.value = false
|
||||
})
|
||||
EventsOn('capture:overlay', (payload: OverlayPayload) => {
|
||||
overlayPayload.value = payload
|
||||
mode.value = 'overlay'
|
||||
capturing.value = false
|
||||
})
|
||||
EventsOn('upload:success', (url: string) => {
|
||||
showToast(
|
||||
'success',
|
||||
url === 'summary copied to clipboard'
|
||||
? 'Summary copied to clipboard'
|
||||
: url === 'ocr text copied to clipboard'
|
||||
? 'OCR text copied to clipboard'
|
||||
: `Copied: ${url}`
|
||||
)
|
||||
})
|
||||
EventsOn('upload:failure', (reason: string) => {
|
||||
showToast('error', reason)
|
||||
})
|
||||
EventsOn('hotkey:ready', (spec: string) => {
|
||||
hotkeyStatus.value = { state: 'ok', spec }
|
||||
})
|
||||
EventsOn('hotkey:error', (reason: string) => {
|
||||
hotkeyStatus.value = { state: 'error', reason }
|
||||
})
|
||||
EventsOn('operation:status', updateOperationStatus)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
EventsOff('capture:start')
|
||||
EventsOff('capture:end')
|
||||
EventsOff('capture:cancelled')
|
||||
EventsOff('capture:overlay')
|
||||
EventsOff('upload:success')
|
||||
EventsOff('upload:failure')
|
||||
EventsOff('hotkey:ready')
|
||||
EventsOff('hotkey:error')
|
||||
EventsOff('operation:status')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Overlay mode: full-screen Snipaste-style picker. -->
|
||||
<CaptureOverlay
|
||||
v-if="mode === 'overlay' && overlayPayload"
|
||||
:width="overlayPayload.cssWidth"
|
||||
:height="overlayPayload.cssHeight"
|
||||
@confirm="onOverlayConfirm"
|
||||
@copy="onOverlayCopy"
|
||||
@save="onOverlaySave"
|
||||
@save-remote="onOverlaySaveRemote"
|
||||
@upload-ftp="onOverlayUploadFTP"
|
||||
@summarize="onOverlaySummarize"
|
||||
@ocr="onOverlayOCR"
|
||||
@cancel="onOverlayCancel"
|
||||
/>
|
||||
|
||||
<!-- Settings mode: standard desktop window; macOS title bar is native. -->
|
||||
<div v-else class="app-root" :class="appThemeClass">
|
||||
<div v-if="hotkeyStatus.state === 'error'" class="permission-banner">
|
||||
<div>
|
||||
<strong>Global hotkey is not active.</strong>
|
||||
Reason: {{ hotkeyStatus.reason }}
|
||||
<br />
|
||||
On macOS open
|
||||
<em>System Settings → Privacy & Security → Accessibility</em>,
|
||||
enable <strong>SnapGo</strong>, then click "Retry".
|
||||
</div>
|
||||
<button class="btn" @click="retryHotkey">Retry</button>
|
||||
</div>
|
||||
|
||||
<main class="main">
|
||||
<aside class="sidebar">
|
||||
<div
|
||||
v-for="item in sidebarItems"
|
||||
:key="item.id"
|
||||
class="sidebar-item"
|
||||
:class="{ active: activeTab === item.id }"
|
||||
@click="activeTab = item.id"
|
||||
>
|
||||
<span class="dot" /> {{ item.label }}
|
||||
</div>
|
||||
</aside>
|
||||
<section class="content">
|
||||
<SettingsView
|
||||
:tab="activeTab"
|
||||
:theme="themeMode"
|
||||
@theme-change="themeMode = normalizeTheme($event)"
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<Toast v-if="toast" :kind="toast.kind" :text="toast.text" />
|
||||
<div
|
||||
v-if="operationStatus"
|
||||
class="operation-hud"
|
||||
:class="operationStatus.state"
|
||||
>
|
||||
<span v-if="operationStatus.state === 'running'" class="spinner" />
|
||||
<span v-else class="status-mark">
|
||||
{{ operationStatus.state === 'success' ? 'OK' : '!' }}
|
||||
</span>
|
||||
<div>
|
||||
<strong>{{ operationStatus.phase }}</strong>
|
||||
<p>{{ operationStatus.message }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background: #f6f7fa;
|
||||
color: #111827;
|
||||
font-size: 13px;
|
||||
}
|
||||
.app-root.theme-light {
|
||||
color-scheme: light;
|
||||
}
|
||||
.app-root.theme-dark {
|
||||
color-scheme: dark;
|
||||
}
|
||||
.app-root.theme-auto {
|
||||
color-scheme: light dark;
|
||||
}
|
||||
|
||||
.status-pill {
|
||||
font-size: 11px;
|
||||
padding: 3px 9px;
|
||||
border-radius: 999px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.status-pill.ok {
|
||||
color: #047857;
|
||||
background: rgba(16, 185, 129, 0.12);
|
||||
}
|
||||
.status-pill.err {
|
||||
color: #b91c1c;
|
||||
background: rgba(239, 68, 68, 0.14);
|
||||
cursor: help;
|
||||
}
|
||||
.status-pill.muted {
|
||||
color: #6b7280;
|
||||
background: rgba(107, 114, 128, 0.14);
|
||||
}
|
||||
|
||||
.permission-banner {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
margin: 12px 16px 0;
|
||||
padding: 10px 14px;
|
||||
background: #fff7ed;
|
||||
border: 1px solid #fdba74;
|
||||
border-radius: 8px;
|
||||
color: #7c2d12;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.permission-banner em {
|
||||
font-style: normal;
|
||||
background: rgba(124, 45, 18, 0.08);
|
||||
padding: 0 4px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.permission-banner .btn {
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid #fdba74;
|
||||
background: #fff;
|
||||
color: #7c2d12;
|
||||
border-radius: 6px;
|
||||
padding: 6px 12px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.permission-banner .btn:hover {
|
||||
background: #fed7aa;
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: 180px 1fr;
|
||||
min-height: 0;
|
||||
}
|
||||
.sidebar {
|
||||
border-right: 1px solid #e5e7eb;
|
||||
padding: 14px 8px;
|
||||
background: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
.sidebar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 12px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
color: #374151;
|
||||
cursor: pointer;
|
||||
}
|
||||
.sidebar-item:hover:not(.active) {
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
.sidebar-item.active {
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
color: #1d4ed8;
|
||||
font-weight: 500;
|
||||
}
|
||||
.sidebar-item .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
.content {
|
||||
overflow-y: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.operation-hud {
|
||||
position: fixed;
|
||||
right: 18px;
|
||||
bottom: 18px;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 260px;
|
||||
max-width: 360px;
|
||||
padding: 12px 14px;
|
||||
color: #f9fafb;
|
||||
background: rgba(17, 24, 39, 0.94);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 12px 34px rgba(15, 23, 42, 0.28);
|
||||
}
|
||||
.operation-hud strong {
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.operation-hud p {
|
||||
margin: 0;
|
||||
color: #d1d5db;
|
||||
font-size: 12px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spinner {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 2px solid rgba(255, 255, 255, 0.25);
|
||||
border-top-color: #60a5fa;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.75s linear infinite;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.status-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.operation-hud.success .status-mark {
|
||||
color: #052e16;
|
||||
background: #86efac;
|
||||
}
|
||||
.operation-hud.error .status-mark {
|
||||
color: #450a0a;
|
||||
background: #fca5a5;
|
||||
}
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.app-root.theme-dark {
|
||||
background: #1c1d22;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
.app-root.theme-dark .titlebar {
|
||||
background: rgba(28, 29, 34, 0.7);
|
||||
border-bottom-color: #2c2f36;
|
||||
}
|
||||
.app-root.theme-dark .titlebar-title {
|
||||
color: #f3f4f6;
|
||||
}
|
||||
.app-root.theme-dark .sidebar {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
border-right-color: #2c2f36;
|
||||
}
|
||||
.app-root.theme-dark .sidebar-item {
|
||||
color: #d1d5db;
|
||||
}
|
||||
.app-root.theme-dark .sidebar-item:hover:not(.active) {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.app-root.theme-dark .sidebar-item.active {
|
||||
background: rgba(59, 130, 246, 0.18);
|
||||
color: #93c5fd;
|
||||
}
|
||||
.app-root.theme-dark .permission-banner {
|
||||
background: rgba(120, 53, 15, 0.3);
|
||||
border-color: rgba(253, 186, 116, 0.4);
|
||||
color: #fed7aa;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.app-root.theme-auto {
|
||||
background: #1c1d22;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
.app-root.theme-auto .titlebar {
|
||||
background: rgba(28, 29, 34, 0.7);
|
||||
border-bottom-color: #2c2f36;
|
||||
}
|
||||
.app-root.theme-auto .titlebar-title {
|
||||
color: #f3f4f6;
|
||||
}
|
||||
.app-root.theme-auto .sidebar {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
border-right-color: #2c2f36;
|
||||
}
|
||||
.app-root.theme-auto .sidebar-item {
|
||||
color: #d1d5db;
|
||||
}
|
||||
.app-root.theme-auto .sidebar-item:hover:not(.active) {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.app-root.theme-auto .sidebar-item.active {
|
||||
background: rgba(59, 130, 246, 0.18);
|
||||
color: #93c5fd;
|
||||
}
|
||||
.app-root.theme-auto .permission-banner {
|
||||
background: rgba(120, 53, 15, 0.3);
|
||||
border-color: rgba(253, 186, 116, 0.4);
|
||||
color: #fed7aa;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2016 The Nunito Project Authors (contact@sansoxygen.com),
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M512 85.333333c235.648 0 426.666667 191.018667 426.666667 426.666667s-191.018667 426.666667-426.666667 426.666667S85.333333 747.648 85.333333 512 276.352 85.333333 512 85.333333zM170.666667 512a341.333333 341.333333 0 0 0 550.613333 269.653333L242.304 302.762667A339.84 339.84 0 0 0 170.666667 512z m341.333333-341.333333c-78.848 0-151.466667 26.752-209.28 71.68l478.976 478.933333A341.333333 341.333333 0 0 0 512 170.666667z" fill="currentColor"></path></svg>
|
||||
|
After Width: | Height: | Size: 534 B |
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M768 256a85.333333 85.333333 0 0 1 85.333333 85.333333v512a85.333333 85.333333 0 0 1-85.333333 85.333334h-341.333333a85.333333 85.333333 0 0 1-85.333334-85.333334V341.333333a85.333333 85.333333 0 0 1 85.333334-85.333333h341.333333z m0 85.333333h-341.333333v512h341.333333V341.333333z m-128-256a42.666667 42.666667 0 0 1 42.666667 42.666667l-0.042667 42.666667H256l-0.042667 597.333333H213.333333a42.666667 42.666667 0 0 1-42.666666-42.666667V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h384z" fill="currentColor"></path></svg>
|
||||
|
After Width: | Height: | Size: 612 B |
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M128 128h768v256H128V128zm64 64v128h640V192H192zm64 48h64v32h-64v-32zM128 448h416v64H192v192h352v64H128V448zm560-32 160 160-45.248 45.248L720 538.496V832h-64V538.496l-82.752 82.752L528 576l160-160z" fill="currentColor"></path></svg>
|
||||
|
After Width: | Height: | Size: 306 B |
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M896 810.666667a85.333333 85.333333 0 0 1-85.333333 85.333333H213.333333a85.333333 85.333333 0 0 1-85.333333-85.333333V213.333333a85.333333 85.333333 0 0 1 85.333333-85.333333h250.368a85.333333 85.333333 0 0 1 73.173334 41.429333L563.2 213.333333H810.666667a85.333333 85.333333 0 0 1 85.333333 85.333334v512z m-85.333333-341.333334H213.333333v341.333334h597.333334v-341.333334z m-346.965334-256H213.333333v170.666667h597.333334V298.666667h-271.616a42.666667 42.666667 0 0 1-36.608-20.736L463.701333 213.333333z" fill="currentColor"></path></svg>
|
||||
|
After Width: | Height: | Size: 619 B |
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M481.749333 353.792c16.682667-16.64 43.690667-16.64 60.373334 0l120.917333 120.832 3.541333 4.010667a42.666667 42.666667 0 0 1-63.872 56.32L554.666667 486.954667V896a42.666667 42.666667 0 0 1-85.333334 0v-409.173333l-48.170666 48.128a42.666667 42.666667 0 0 1-60.330667 0l-3.541333-4.010667a42.666667 42.666667 0 0 1 3.541333-56.32zM512 85.333333c122.538667 0 227.84 73.813333 273.92 179.370667A213.333333 213.333333 0 0 1 725.333333 682.666667a42.666667 42.666667 0 0 1-4.992-85.034667L725.333333 597.333333a128 128 0 0 0 36.394667-250.794666l-38.144-11.264-15.914667-36.437334a213.376 213.376 0 0 0-407.296 58.026667l-7.381333 58.368-57.173333 13.824A85.418667 85.418667 0 0 0 256 597.333333h42.666667a42.666667 42.666667 0 0 1 0 85.333334H256a170.666667 170.666667 0 0 1-40.277333-336.554667A298.709333 298.709333 0 0 1 512 85.333333z" fill="currentColor"></path></svg>
|
||||
|
After Width: | Height: | Size: 946 B |
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M550.528 544.128L640 539.776V678.4l178.005333-178.005333L640 322.389333v129.024l-72.618667 10.922667c-155.52 23.424-251.733333 73.557333-312.874666 164.437333 84.906667-50.602667 178.261333-76.928 296.021333-82.645333zM554.666667 629.376c-27.392 1.322667-53.034667 3.968-77.141334 7.808l-8.192 1.365333c-136.704 23.637333-224.810667 87.168-310.954666 176.128-26.154667 27.008-51.882667 59.648-51.882667 59.648-14.848 18.176-24.021333 14.037333-20.352-9.173333 0 0 4.394667-31.402667 11.690667-65.792C144.938667 577.066667 250.581333 423.68 554.666667 377.941333V209.066667a38.4 38.4 0 0 1 65.536-27.136l291.328 291.285333a38.4 38.4 0 0 1 0 54.314667l-291.328 291.285333A38.4 38.4 0 0 1 554.666667 791.637333v-162.261333z" fill="currentColor" p-id="2487"></path></svg>
|
||||
|
After Width: | Height: | Size: 841 B |
|
After Width: | Height: | Size: 136 KiB |
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
/*
|
||||
* Toast — bottom-right transient notification used for upload success /
|
||||
* failure messages. Self-managed lifecycle is owned by the parent App.vue,
|
||||
* which simply hides this component after a delay.
|
||||
*/
|
||||
defineProps<{
|
||||
kind: 'success' | 'error'
|
||||
text: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="toast" :class="kind">{{ text }}</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.toast {
|
||||
position: fixed;
|
||||
right: 18px;
|
||||
bottom: 18px;
|
||||
max-width: 380px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 6px;
|
||||
font-size: 12.5px;
|
||||
color: #fff;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
animation: toast-in 0.18s ease-out;
|
||||
}
|
||||
.toast.success {
|
||||
background: #10b981;
|
||||
}
|
||||
.toast.error {
|
||||
background: #ef4444;
|
||||
}
|
||||
@keyframes toast-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,5 @@
|
||||
import {createApp} from 'vue'
|
||||
import App from './App.vue'
|
||||
import './style.css';
|
||||
|
||||
createApp(App).mount('#app')
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Global styles for SnapGo.
|
||||
*
|
||||
* Design rationale:
|
||||
* - The native window/webview is transparent so the capture overlay can show
|
||||
* the live desktop through its selection cut-out.
|
||||
* - SettingsView remains opaque because App.vue paints `.app-root` across
|
||||
* the whole window.
|
||||
*/
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text",
|
||||
"Segoe UI Variable", "Inter", sans-serif;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
color: #111827;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html,
|
||||
body {
|
||||
background: transparent;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
}
|
||||
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
button {
|
||||
font-family: inherit;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export interface AnnotationPoint {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
interface PointCollection {
|
||||
points: AnnotationPoint[]
|
||||
}
|
||||
|
||||
// Annotations are stored relative to the selection origin. Resizing from the
|
||||
// top or left moves that origin, so offset the local points in the opposite
|
||||
// direction to keep them attached to the same screen pixels.
|
||||
export function preserveAnnotationScreenPositions(
|
||||
annotations: PointCollection[],
|
||||
previousOrigin: AnnotationPoint,
|
||||
nextOrigin: AnnotationPoint
|
||||
) {
|
||||
const dx = previousOrigin.x - nextOrigin.x
|
||||
const dy = previousOrigin.y - nextOrigin.y
|
||||
if (dx === 0 && dy === 0) return
|
||||
|
||||
for (const annotation of annotations) {
|
||||
for (const point of annotation.points) {
|
||||
point.x += dx
|
||||
point.y += dy
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.vue' {
|
||||
import type {DefineComponent} from 'vue'
|
||||
const component: DefineComponent<{}, {}, any>
|
||||
export default component
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { preserveAnnotationScreenPositions } from '../src/utils/annotationGeometry.ts'
|
||||
|
||||
test('keeps annotation points at the same screen position when the origin moves', () => {
|
||||
const annotations = [
|
||||
{ points: [{ x: 30, y: 40 }, { x: 80, y: 90 }] },
|
||||
{ points: [{ x: 12, y: 18 }] },
|
||||
]
|
||||
|
||||
preserveAnnotationScreenPositions(
|
||||
annotations,
|
||||
{ x: 100, y: 200 },
|
||||
{ x: 125, y: 230 }
|
||||
)
|
||||
|
||||
assert.deepEqual(annotations, [
|
||||
{ points: [{ x: 5, y: 10 }, { x: 55, y: 60 }] },
|
||||
{ points: [{ x: -13, y: -12 }] },
|
||||
])
|
||||
assert.deepEqual(
|
||||
annotations[0].points.map((point) => ({
|
||||
x: 125 + point.x,
|
||||
y: 230 + point.y,
|
||||
})),
|
||||
[{ x: 130, y: 240 }, { x: 180, y: 290 }]
|
||||
)
|
||||
})
|
||||
|
||||
test('does not move annotations when only the right or bottom edge changes', () => {
|
||||
const annotations = [{ points: [{ x: 30, y: 40 }] }]
|
||||
|
||||
preserveAnnotationScreenPositions(
|
||||
annotations,
|
||||
{ x: 100, y: 200 },
|
||||
{ x: 100, y: 200 }
|
||||
)
|
||||
|
||||
assert.deepEqual(annotations, [{ points: [{ x: 30, y: 40 }] }])
|
||||
})
|
||||
|
||||
test('preserves screen positions across repeated drags and an edge crossover', () => {
|
||||
const annotations = [{ points: [{ x: 50, y: 60 }] }]
|
||||
|
||||
preserveAnnotationScreenPositions(
|
||||
annotations,
|
||||
{ x: 100, y: 100 },
|
||||
{ x: 140, y: 130 }
|
||||
)
|
||||
preserveAnnotationScreenPositions(
|
||||
annotations,
|
||||
{ x: 140, y: 130 },
|
||||
{ x: 300, y: 150 }
|
||||
)
|
||||
|
||||
assert.deepEqual(annotations, [{ points: [{ x: -150, y: 10 }] }])
|
||||
assert.deepEqual(
|
||||
{
|
||||
x: 300 + annotations[0].points[0].x,
|
||||
y: 150 + annotations[0].points[0].y,
|
||||
},
|
||||
{ x: 150, y: 160 }
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"sourceMap": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"lib": [
|
||||
"ESNext",
|
||||
"DOM"
|
||||
],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts",
|
||||
"src/**/*.d.ts",
|
||||
"src/**/*.tsx",
|
||||
"src/**/*.vue"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": [
|
||||
"vite.config.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {defineConfig} from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [vue()]
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
import {main} from '../models';
|
||||
import {domain} from '../models';
|
||||
|
||||
export function CancelNativeRegion():Promise<void>;
|
||||
|
||||
export function CancelRegion():Promise<void>;
|
||||
|
||||
export function CaptureNow():Promise<void>;
|
||||
|
||||
export function ConfirmNativeRegion(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function ConfirmRegion(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function CopyNativeRegionImage(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function CopyRegionImage(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function ExtractTextNativeRegion(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function ExtractTextRegion(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function GetConfig():Promise<domain.AppConfig>;
|
||||
|
||||
export function QuitApp():Promise<void>;
|
||||
|
||||
export function RetryRegisterHotkey():Promise<void>;
|
||||
|
||||
export function SaveConfig(arg1:domain.AppConfig):Promise<void>;
|
||||
|
||||
export function SaveNativeRegionImage(arg1:main.CaptureResult):Promise<main.CaptureActionResult>;
|
||||
|
||||
export function SaveNativeRegionImageToDir(arg1:main.CaptureResult,arg2:string):Promise<main.CaptureActionResult>;
|
||||
|
||||
export function SaveNativeRegionToRemote(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function SaveRegionImage(arg1:main.CaptureResult):Promise<main.CaptureActionResult>;
|
||||
|
||||
export function SaveRegionToRemote(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function ShowWindow():Promise<void>;
|
||||
|
||||
export function SummarizeNativeRegion(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function SummarizeRegion(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function TestConnection(arg1:domain.S3Config):Promise<void>;
|
||||
|
||||
export function TestFTPConnection(arg1:domain.FTPConfig):Promise<void>;
|
||||
|
||||
export function TestSSHConnection(arg1:domain.SSHConfig):Promise<void>;
|
||||
|
||||
export function UploadNativeRegionToFTP(arg1:main.CaptureResult):Promise<void>;
|
||||
|
||||
export function UploadRegionToFTP(arg1:main.CaptureResult):Promise<void>;
|
||||
@@ -0,0 +1,107 @@
|
||||
// @ts-check
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export function CancelNativeRegion() {
|
||||
return window['go']['main']['App']['CancelNativeRegion']();
|
||||
}
|
||||
|
||||
export function CancelRegion() {
|
||||
return window['go']['main']['App']['CancelRegion']();
|
||||
}
|
||||
|
||||
export function CaptureNow() {
|
||||
return window['go']['main']['App']['CaptureNow']();
|
||||
}
|
||||
|
||||
export function ConfirmNativeRegion(arg1) {
|
||||
return window['go']['main']['App']['ConfirmNativeRegion'](arg1);
|
||||
}
|
||||
|
||||
export function ConfirmRegion(arg1) {
|
||||
return window['go']['main']['App']['ConfirmRegion'](arg1);
|
||||
}
|
||||
|
||||
export function CopyNativeRegionImage(arg1) {
|
||||
return window['go']['main']['App']['CopyNativeRegionImage'](arg1);
|
||||
}
|
||||
|
||||
export function CopyRegionImage(arg1) {
|
||||
return window['go']['main']['App']['CopyRegionImage'](arg1);
|
||||
}
|
||||
|
||||
export function ExtractTextNativeRegion(arg1) {
|
||||
return window['go']['main']['App']['ExtractTextNativeRegion'](arg1);
|
||||
}
|
||||
|
||||
export function ExtractTextRegion(arg1) {
|
||||
return window['go']['main']['App']['ExtractTextRegion'](arg1);
|
||||
}
|
||||
|
||||
export function GetConfig() {
|
||||
return window['go']['main']['App']['GetConfig']();
|
||||
}
|
||||
|
||||
export function QuitApp() {
|
||||
return window['go']['main']['App']['QuitApp']();
|
||||
}
|
||||
|
||||
export function RetryRegisterHotkey() {
|
||||
return window['go']['main']['App']['RetryRegisterHotkey']();
|
||||
}
|
||||
|
||||
export function SaveConfig(arg1) {
|
||||
return window['go']['main']['App']['SaveConfig'](arg1);
|
||||
}
|
||||
|
||||
export function SaveNativeRegionImage(arg1) {
|
||||
return window['go']['main']['App']['SaveNativeRegionImage'](arg1);
|
||||
}
|
||||
|
||||
export function SaveNativeRegionImageToDir(arg1, arg2) {
|
||||
return window['go']['main']['App']['SaveNativeRegionImageToDir'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function SaveNativeRegionToRemote(arg1) {
|
||||
return window['go']['main']['App']['SaveNativeRegionToRemote'](arg1);
|
||||
}
|
||||
|
||||
export function SaveRegionImage(arg1) {
|
||||
return window['go']['main']['App']['SaveRegionImage'](arg1);
|
||||
}
|
||||
|
||||
export function SaveRegionToRemote(arg1) {
|
||||
return window['go']['main']['App']['SaveRegionToRemote'](arg1);
|
||||
}
|
||||
|
||||
export function ShowWindow() {
|
||||
return window['go']['main']['App']['ShowWindow']();
|
||||
}
|
||||
|
||||
export function SummarizeNativeRegion(arg1) {
|
||||
return window['go']['main']['App']['SummarizeNativeRegion'](arg1);
|
||||
}
|
||||
|
||||
export function SummarizeRegion(arg1) {
|
||||
return window['go']['main']['App']['SummarizeRegion'](arg1);
|
||||
}
|
||||
|
||||
export function TestConnection(arg1) {
|
||||
return window['go']['main']['App']['TestConnection'](arg1);
|
||||
}
|
||||
|
||||
export function TestFTPConnection(arg1) {
|
||||
return window['go']['main']['App']['TestFTPConnection'](arg1);
|
||||
}
|
||||
|
||||
export function TestSSHConnection(arg1) {
|
||||
return window['go']['main']['App']['TestSSHConnection'](arg1);
|
||||
}
|
||||
|
||||
export function UploadNativeRegionToFTP(arg1) {
|
||||
return window['go']['main']['App']['UploadNativeRegionToFTP'](arg1);
|
||||
}
|
||||
|
||||
export function UploadRegionToFTP(arg1) {
|
||||
return window['go']['main']['App']['UploadRegionToFTP'](arg1);
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
export namespace application {
|
||||
|
||||
export class Point {
|
||||
x: number;
|
||||
y: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Point(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.x = source["x"];
|
||||
this.y = source["y"];
|
||||
}
|
||||
}
|
||||
export class Annotation {
|
||||
tool: string;
|
||||
color: string;
|
||||
points: Point[];
|
||||
text?: string;
|
||||
strokeWidth?: number;
|
||||
fontSize?: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Annotation(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.tool = source["tool"];
|
||||
this.color = source["color"];
|
||||
this.points = this.convertValues(source["points"], Point);
|
||||
this.text = source["text"];
|
||||
this.strokeWidth = source["strokeWidth"];
|
||||
this.fontSize = source["fontSize"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace domain {
|
||||
|
||||
export class OCRProviderConfig {
|
||||
label: string;
|
||||
endpoint: string;
|
||||
accessKeyId: string;
|
||||
accessKeySecret: string;
|
||||
region: string;
|
||||
service: string;
|
||||
action: string;
|
||||
version: string;
|
||||
timeoutSecs: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new OCRProviderConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.label = source["label"];
|
||||
this.endpoint = source["endpoint"];
|
||||
this.accessKeyId = source["accessKeyId"];
|
||||
this.accessKeySecret = source["accessKeySecret"];
|
||||
this.region = source["region"];
|
||||
this.service = source["service"];
|
||||
this.action = source["action"];
|
||||
this.version = source["version"];
|
||||
this.timeoutSecs = source["timeoutSecs"];
|
||||
}
|
||||
}
|
||||
export class OCRConfig {
|
||||
activeProvider: string;
|
||||
providers: Record<string, OCRProviderConfig>;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new OCRConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.activeProvider = source["activeProvider"];
|
||||
this.providers = this.convertValues(source["providers"], OCRProviderConfig, true);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class LLMProviderConfig {
|
||||
label: string;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model: string;
|
||||
maxTokens: number;
|
||||
temperature: number;
|
||||
timeoutSecs: number;
|
||||
maxInlineBytes: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new LLMProviderConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.label = source["label"];
|
||||
this.baseUrl = source["baseUrl"];
|
||||
this.apiKey = source["apiKey"];
|
||||
this.model = source["model"];
|
||||
this.maxTokens = source["maxTokens"];
|
||||
this.temperature = source["temperature"];
|
||||
this.timeoutSecs = source["timeoutSecs"];
|
||||
this.maxInlineBytes = source["maxInlineBytes"];
|
||||
}
|
||||
}
|
||||
export class LLMConfig {
|
||||
activeProvider: string;
|
||||
prompt: string;
|
||||
providers: Record<string, LLMProviderConfig>;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new LLMConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.activeProvider = source["activeProvider"];
|
||||
this.prompt = source["prompt"];
|
||||
this.providers = this.convertValues(source["providers"], LLMProviderConfig, true);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class FTPConfig {
|
||||
protocol: string;
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
authMethod: string;
|
||||
password: string;
|
||||
rootDirectory: string;
|
||||
pathPrefix: string;
|
||||
strictHostKey: boolean;
|
||||
knownHostsPath: string;
|
||||
connectTimeoutSecs: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new FTPConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.protocol = source["protocol"];
|
||||
this.host = source["host"];
|
||||
this.port = source["port"];
|
||||
this.user = source["user"];
|
||||
this.authMethod = source["authMethod"];
|
||||
this.password = source["password"];
|
||||
this.rootDirectory = source["rootDirectory"];
|
||||
this.pathPrefix = source["pathPrefix"];
|
||||
this.strictHostKey = source["strictHostKey"];
|
||||
this.knownHostsPath = source["knownHostsPath"];
|
||||
this.connectTimeoutSecs = source["connectTimeoutSecs"];
|
||||
}
|
||||
}
|
||||
export class SSHConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
authMethod: string;
|
||||
password: string;
|
||||
pathPrefix: string;
|
||||
strictHostKey: boolean;
|
||||
knownHostsPath: string;
|
||||
connectTimeoutSecs: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new SSHConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.host = source["host"];
|
||||
this.port = source["port"];
|
||||
this.user = source["user"];
|
||||
this.authMethod = source["authMethod"];
|
||||
this.password = source["password"];
|
||||
this.pathPrefix = source["pathPrefix"];
|
||||
this.strictHostKey = source["strictHostKey"];
|
||||
this.knownHostsPath = source["knownHostsPath"];
|
||||
this.connectTimeoutSecs = source["connectTimeoutSecs"];
|
||||
}
|
||||
}
|
||||
export class S3Config {
|
||||
endpoint: string;
|
||||
region: string;
|
||||
bucket: string;
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
pathPrefix: string;
|
||||
publicUrlBase: string;
|
||||
usePathStyle: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new S3Config(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.endpoint = source["endpoint"];
|
||||
this.region = source["region"];
|
||||
this.bucket = source["bucket"];
|
||||
this.accessKeyId = source["accessKeyId"];
|
||||
this.secretAccessKey = source["secretAccessKey"];
|
||||
this.pathPrefix = source["pathPrefix"];
|
||||
this.publicUrlBase = source["publicUrlBase"];
|
||||
this.usePathStyle = source["usePathStyle"];
|
||||
}
|
||||
}
|
||||
export class AppConfig {
|
||||
hotkey: string;
|
||||
theme: string;
|
||||
s3: S3Config;
|
||||
ssh: SSHConfig;
|
||||
ftp: FTPConfig;
|
||||
llm: LLMConfig;
|
||||
ocr: OCRConfig;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AppConfig(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.hotkey = source["hotkey"];
|
||||
this.theme = source["theme"];
|
||||
this.s3 = this.convertValues(source["s3"], S3Config);
|
||||
this.ssh = this.convertValues(source["ssh"], SSHConfig);
|
||||
this.ftp = this.convertValues(source["ftp"], FTPConfig);
|
||||
this.llm = this.convertValues(source["llm"], LLMConfig);
|
||||
this.ocr = this.convertValues(source["ocr"], OCRConfig);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
export namespace main {
|
||||
|
||||
export class CaptureActionResult {
|
||||
completed: boolean;
|
||||
path?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new CaptureActionResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.completed = source["completed"];
|
||||
this.path = source["path"];
|
||||
}
|
||||
}
|
||||
export class RegionRect {
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new RegionRect(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.x = source["x"];
|
||||
this.y = source["y"];
|
||||
this.w = source["w"];
|
||||
this.h = source["h"];
|
||||
}
|
||||
}
|
||||
export class CaptureResult {
|
||||
rect: RegionRect;
|
||||
annotations: application.Annotation[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new CaptureResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.rect = this.convertValues(source["rect"], RegionRect);
|
||||
this.annotations = this.convertValues(source["annotations"], application.Annotation);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@wailsapp/runtime",
|
||||
"version": "2.0.0",
|
||||
"description": "Wails Javascript runtime library",
|
||||
"main": "runtime.js",
|
||||
"types": "runtime.d.ts",
|
||||
"scripts": {
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/wailsapp/wails.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Wails",
|
||||
"Javascript",
|
||||
"Go"
|
||||
],
|
||||
"author": "Lea Anthony <lea.anthony@gmail.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/wailsapp/wails/issues"
|
||||
},
|
||||
"homepage": "https://github.com/wailsapp/wails#readme"
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
_ __ _ __
|
||||
| | / /___ _(_) /____
|
||||
| | /| / / __ `/ / / ___/
|
||||
| |/ |/ / /_/ / / (__ )
|
||||
|__/|__/\__,_/_/_/____/
|
||||
The electron alternative for Go
|
||||
(c) Lea Anthony 2019-present
|
||||
*/
|
||||
|
||||
export interface Position {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface Size {
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
export interface Screen {
|
||||
isCurrent: boolean;
|
||||
isPrimary: boolean;
|
||||
width : number
|
||||
height : number
|
||||
}
|
||||
|
||||
// Environment information such as platform, buildtype, ...
|
||||
export interface EnvironmentInfo {
|
||||
buildType: string;
|
||||
platform: string;
|
||||
arch: string;
|
||||
}
|
||||
|
||||
// [EventsEmit](https://wails.io/docs/reference/runtime/events#eventsemit)
|
||||
// emits the given event. Optional data may be passed with the event.
|
||||
// This will trigger any event listeners.
|
||||
export function EventsEmit(eventName: string, ...data: any): void;
|
||||
|
||||
// [EventsOn](https://wails.io/docs/reference/runtime/events#eventson) sets up a listener for the given event name.
|
||||
export function EventsOn(eventName: string, callback: (...data: any) => void): () => void;
|
||||
|
||||
// [EventsOnMultiple](https://wails.io/docs/reference/runtime/events#eventsonmultiple)
|
||||
// sets up a listener for the given event name, but will only trigger a given number times.
|
||||
export function EventsOnMultiple(eventName: string, callback: (...data: any) => void, maxCallbacks: number): () => void;
|
||||
|
||||
// [EventsOnce](https://wails.io/docs/reference/runtime/events#eventsonce)
|
||||
// sets up a listener for the given event name, but will only trigger once.
|
||||
export function EventsOnce(eventName: string, callback: (...data: any) => void): () => void;
|
||||
|
||||
// [EventsOff](https://wails.io/docs/reference/runtime/events#eventsoff)
|
||||
// unregisters the listener for the given event name.
|
||||
export function EventsOff(eventName: string, ...additionalEventNames: string[]): void;
|
||||
|
||||
// [EventsOffAll](https://wails.io/docs/reference/runtime/events#eventsoffall)
|
||||
// unregisters all listeners.
|
||||
export function EventsOffAll(): void;
|
||||
|
||||
// [LogPrint](https://wails.io/docs/reference/runtime/log#logprint)
|
||||
// logs the given message as a raw message
|
||||
export function LogPrint(message: string): void;
|
||||
|
||||
// [LogTrace](https://wails.io/docs/reference/runtime/log#logtrace)
|
||||
// logs the given message at the `trace` log level.
|
||||
export function LogTrace(message: string): void;
|
||||
|
||||
// [LogDebug](https://wails.io/docs/reference/runtime/log#logdebug)
|
||||
// logs the given message at the `debug` log level.
|
||||
export function LogDebug(message: string): void;
|
||||
|
||||
// [LogError](https://wails.io/docs/reference/runtime/log#logerror)
|
||||
// logs the given message at the `error` log level.
|
||||
export function LogError(message: string): void;
|
||||
|
||||
// [LogFatal](https://wails.io/docs/reference/runtime/log#logfatal)
|
||||
// logs the given message at the `fatal` log level.
|
||||
// The application will quit after calling this method.
|
||||
export function LogFatal(message: string): void;
|
||||
|
||||
// [LogInfo](https://wails.io/docs/reference/runtime/log#loginfo)
|
||||
// logs the given message at the `info` log level.
|
||||
export function LogInfo(message: string): void;
|
||||
|
||||
// [LogWarning](https://wails.io/docs/reference/runtime/log#logwarning)
|
||||
// logs the given message at the `warning` log level.
|
||||
export function LogWarning(message: string): void;
|
||||
|
||||
// [WindowReload](https://wails.io/docs/reference/runtime/window#windowreload)
|
||||
// Forces a reload by the main application as well as connected browsers.
|
||||
export function WindowReload(): void;
|
||||
|
||||
// [WindowReloadApp](https://wails.io/docs/reference/runtime/window#windowreloadapp)
|
||||
// Reloads the application frontend.
|
||||
export function WindowReloadApp(): void;
|
||||
|
||||
// [WindowSetAlwaysOnTop](https://wails.io/docs/reference/runtime/window#windowsetalwaysontop)
|
||||
// Sets the window AlwaysOnTop or not on top.
|
||||
export function WindowSetAlwaysOnTop(b: boolean): void;
|
||||
|
||||
// [WindowSetSystemDefaultTheme](https://wails.io/docs/next/reference/runtime/window#windowsetsystemdefaulttheme)
|
||||
// *Windows only*
|
||||
// Sets window theme to system default (dark/light).
|
||||
export function WindowSetSystemDefaultTheme(): void;
|
||||
|
||||
// [WindowSetLightTheme](https://wails.io/docs/next/reference/runtime/window#windowsetlighttheme)
|
||||
// *Windows only*
|
||||
// Sets window to light theme.
|
||||
export function WindowSetLightTheme(): void;
|
||||
|
||||
// [WindowSetDarkTheme](https://wails.io/docs/next/reference/runtime/window#windowsetdarktheme)
|
||||
// *Windows only*
|
||||
// Sets window to dark theme.
|
||||
export function WindowSetDarkTheme(): void;
|
||||
|
||||
// [WindowCenter](https://wails.io/docs/reference/runtime/window#windowcenter)
|
||||
// Centers the window on the monitor the window is currently on.
|
||||
export function WindowCenter(): void;
|
||||
|
||||
// [WindowSetTitle](https://wails.io/docs/reference/runtime/window#windowsettitle)
|
||||
// Sets the text in the window title bar.
|
||||
export function WindowSetTitle(title: string): void;
|
||||
|
||||
// [WindowFullscreen](https://wails.io/docs/reference/runtime/window#windowfullscreen)
|
||||
// Makes the window full screen.
|
||||
export function WindowFullscreen(): void;
|
||||
|
||||
// [WindowUnfullscreen](https://wails.io/docs/reference/runtime/window#windowunfullscreen)
|
||||
// Restores the previous window dimensions and position prior to full screen.
|
||||
export function WindowUnfullscreen(): void;
|
||||
|
||||
// [WindowIsFullscreen](https://wails.io/docs/reference/runtime/window#windowisfullscreen)
|
||||
// Returns the state of the window, i.e. whether the window is in full screen mode or not.
|
||||
export function WindowIsFullscreen(): Promise<boolean>;
|
||||
|
||||
// [WindowSetSize](https://wails.io/docs/reference/runtime/window#windowsetsize)
|
||||
// Sets the width and height of the window.
|
||||
export function WindowSetSize(width: number, height: number): void;
|
||||
|
||||
// [WindowGetSize](https://wails.io/docs/reference/runtime/window#windowgetsize)
|
||||
// Gets the width and height of the window.
|
||||
export function WindowGetSize(): Promise<Size>;
|
||||
|
||||
// [WindowSetMaxSize](https://wails.io/docs/reference/runtime/window#windowsetmaxsize)
|
||||
// Sets the maximum window size. Will resize the window if the window is currently larger than the given dimensions.
|
||||
// Setting a size of 0,0 will disable this constraint.
|
||||
export function WindowSetMaxSize(width: number, height: number): void;
|
||||
|
||||
// [WindowSetMinSize](https://wails.io/docs/reference/runtime/window#windowsetminsize)
|
||||
// Sets the minimum window size. Will resize the window if the window is currently smaller than the given dimensions.
|
||||
// Setting a size of 0,0 will disable this constraint.
|
||||
export function WindowSetMinSize(width: number, height: number): void;
|
||||
|
||||
// [WindowSetPosition](https://wails.io/docs/reference/runtime/window#windowsetposition)
|
||||
// Sets the window position relative to the monitor the window is currently on.
|
||||
export function WindowSetPosition(x: number, y: number): void;
|
||||
|
||||
// [WindowGetPosition](https://wails.io/docs/reference/runtime/window#windowgetposition)
|
||||
// Gets the window position relative to the monitor the window is currently on.
|
||||
export function WindowGetPosition(): Promise<Position>;
|
||||
|
||||
// [WindowHide](https://wails.io/docs/reference/runtime/window#windowhide)
|
||||
// Hides the window.
|
||||
export function WindowHide(): void;
|
||||
|
||||
// [WindowShow](https://wails.io/docs/reference/runtime/window#windowshow)
|
||||
// Shows the window, if it is currently hidden.
|
||||
export function WindowShow(): void;
|
||||
|
||||
// [WindowMaximise](https://wails.io/docs/reference/runtime/window#windowmaximise)
|
||||
// Maximises the window to fill the screen.
|
||||
export function WindowMaximise(): void;
|
||||
|
||||
// [WindowToggleMaximise](https://wails.io/docs/reference/runtime/window#windowtogglemaximise)
|
||||
// Toggles between Maximised and UnMaximised.
|
||||
export function WindowToggleMaximise(): void;
|
||||
|
||||
// [WindowUnmaximise](https://wails.io/docs/reference/runtime/window#windowunmaximise)
|
||||
// Restores the window to the dimensions and position prior to maximising.
|
||||
export function WindowUnmaximise(): void;
|
||||
|
||||
// [WindowIsMaximised](https://wails.io/docs/reference/runtime/window#windowismaximised)
|
||||
// Returns the state of the window, i.e. whether the window is maximised or not.
|
||||
export function WindowIsMaximised(): Promise<boolean>;
|
||||
|
||||
// [WindowMinimise](https://wails.io/docs/reference/runtime/window#windowminimise)
|
||||
// Minimises the window.
|
||||
export function WindowMinimise(): void;
|
||||
|
||||
// [WindowUnminimise](https://wails.io/docs/reference/runtime/window#windowunminimise)
|
||||
// Restores the window to the dimensions and position prior to minimising.
|
||||
export function WindowUnminimise(): void;
|
||||
|
||||
// [WindowIsMinimised](https://wails.io/docs/reference/runtime/window#windowisminimised)
|
||||
// Returns the state of the window, i.e. whether the window is minimised or not.
|
||||
export function WindowIsMinimised(): Promise<boolean>;
|
||||
|
||||
// [WindowIsNormal](https://wails.io/docs/reference/runtime/window#windowisnormal)
|
||||
// Returns the state of the window, i.e. whether the window is normal or not.
|
||||
export function WindowIsNormal(): Promise<boolean>;
|
||||
|
||||
// [WindowSetBackgroundColour](https://wails.io/docs/reference/runtime/window#windowsetbackgroundcolour)
|
||||
// Sets the background colour of the window to the given RGBA colour definition. This colour will show through for all transparent pixels.
|
||||
export function WindowSetBackgroundColour(R: number, G: number, B: number, A: number): void;
|
||||
|
||||
// [ScreenGetAll](https://wails.io/docs/reference/runtime/window#screengetall)
|
||||
// Gets the all screens. Call this anew each time you want to refresh data from the underlying windowing system.
|
||||
export function ScreenGetAll(): Promise<Screen[]>;
|
||||
|
||||
// [BrowserOpenURL](https://wails.io/docs/reference/runtime/browser#browseropenurl)
|
||||
// Opens the given URL in the system browser.
|
||||
export function BrowserOpenURL(url: string): void;
|
||||
|
||||
// [Environment](https://wails.io/docs/reference/runtime/intro#environment)
|
||||
// Returns information about the environment
|
||||
export function Environment(): Promise<EnvironmentInfo>;
|
||||
|
||||
// [Quit](https://wails.io/docs/reference/runtime/intro#quit)
|
||||
// Quits the application.
|
||||
export function Quit(): void;
|
||||
|
||||
// [Hide](https://wails.io/docs/reference/runtime/intro#hide)
|
||||
// Hides the application.
|
||||
export function Hide(): void;
|
||||
|
||||
// [Show](https://wails.io/docs/reference/runtime/intro#show)
|
||||
// Shows the application.
|
||||
export function Show(): void;
|
||||
|
||||
// [ClipboardGetText](https://wails.io/docs/reference/runtime/clipboard#clipboardgettext)
|
||||
// Returns the current text stored on clipboard
|
||||
export function ClipboardGetText(): Promise<string>;
|
||||
|
||||
// [ClipboardSetText](https://wails.io/docs/reference/runtime/clipboard#clipboardsettext)
|
||||
// Sets a text on the clipboard
|
||||
export function ClipboardSetText(text: string): Promise<boolean>;
|
||||
|
||||
// [OnFileDrop](https://wails.io/docs/reference/runtime/draganddrop#onfiledrop)
|
||||
// OnFileDrop listens to drag and drop events and calls the callback with the coordinates of the drop and an array of path strings.
|
||||
export function OnFileDrop(callback: (x: number, y: number ,paths: string[]) => void, useDropTarget: boolean) :void
|
||||
|
||||
// [OnFileDropOff](https://wails.io/docs/reference/runtime/draganddrop#dragandddropoff)
|
||||
// OnFileDropOff removes the drag and drop listeners and handlers.
|
||||
export function OnFileDropOff() :void
|
||||
|
||||
// Check if the file path resolver is available
|
||||
export function CanResolveFilePaths(): boolean;
|
||||
|
||||
// Resolves file paths for an array of files
|
||||
export function ResolveFilePaths(files: File[]): void
|
||||
|
||||
// Notification types
|
||||
export interface NotificationOptions {
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle?: string; // macOS and Linux only
|
||||
body?: string;
|
||||
categoryId?: string;
|
||||
data?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface NotificationAction {
|
||||
id?: string;
|
||||
title?: string;
|
||||
destructive?: boolean; // macOS-specific
|
||||
}
|
||||
|
||||
export interface NotificationCategory {
|
||||
id?: string;
|
||||
actions?: NotificationAction[];
|
||||
hasReplyField?: boolean;
|
||||
replyPlaceholder?: string;
|
||||
replyButtonTitle?: string;
|
||||
}
|
||||
|
||||
// [InitializeNotifications](https://wails.io/docs/reference/runtime/notification#initializenotifications)
|
||||
// Initializes the notification service for the application.
|
||||
// This must be called before sending any notifications.
|
||||
export function InitializeNotifications(): Promise<void>;
|
||||
|
||||
// [CleanupNotifications](https://wails.io/docs/reference/runtime/notification#cleanupnotifications)
|
||||
// Cleans up notification resources and releases any held connections.
|
||||
export function CleanupNotifications(): Promise<void>;
|
||||
|
||||
// [IsNotificationAvailable](https://wails.io/docs/reference/runtime/notification#isnotificationavailable)
|
||||
// Checks if notifications are available on the current platform.
|
||||
export function IsNotificationAvailable(): Promise<boolean>;
|
||||
|
||||
// [RequestNotificationAuthorization](https://wails.io/docs/reference/runtime/notification#requestnotificationauthorization)
|
||||
// Requests notification authorization from the user (macOS only).
|
||||
export function RequestNotificationAuthorization(): Promise<boolean>;
|
||||
|
||||
// [CheckNotificationAuthorization](https://wails.io/docs/reference/runtime/notification#checknotificationauthorization)
|
||||
// Checks the current notification authorization status (macOS only).
|
||||
export function CheckNotificationAuthorization(): Promise<boolean>;
|
||||
|
||||
// [SendNotification](https://wails.io/docs/reference/runtime/notification#sendnotification)
|
||||
// Sends a basic notification with the given options.
|
||||
export function SendNotification(options: NotificationOptions): Promise<void>;
|
||||
|
||||
// [SendNotificationWithActions](https://wails.io/docs/reference/runtime/notification#sendnotificationwithactions)
|
||||
// Sends a notification with action buttons. Requires a registered category.
|
||||
export function SendNotificationWithActions(options: NotificationOptions): Promise<void>;
|
||||
|
||||
// [RegisterNotificationCategory](https://wails.io/docs/reference/runtime/notification#registernotificationcategory)
|
||||
// Registers a notification category that can be used with SendNotificationWithActions.
|
||||
export function RegisterNotificationCategory(category: NotificationCategory): Promise<void>;
|
||||
|
||||
// [RemoveNotificationCategory](https://wails.io/docs/reference/runtime/notification#removenotificationcategory)
|
||||
// Removes a previously registered notification category.
|
||||
export function RemoveNotificationCategory(categoryId: string): Promise<void>;
|
||||
|
||||
// [RemoveAllPendingNotifications](https://wails.io/docs/reference/runtime/notification#removeallpendingnotifications)
|
||||
// Removes all pending notifications from the notification center.
|
||||
export function RemoveAllPendingNotifications(): Promise<void>;
|
||||
|
||||
// [RemovePendingNotification](https://wails.io/docs/reference/runtime/notification#removependingnotification)
|
||||
// Removes a specific pending notification by its identifier.
|
||||
export function RemovePendingNotification(identifier: string): Promise<void>;
|
||||
|
||||
// [RemoveAllDeliveredNotifications](https://wails.io/docs/reference/runtime/notification#removealldeliverednotifications)
|
||||
// Removes all delivered notifications from the notification center.
|
||||
export function RemoveAllDeliveredNotifications(): Promise<void>;
|
||||
|
||||
// [RemoveDeliveredNotification](https://wails.io/docs/reference/runtime/notification#removedeliverednotification)
|
||||
// Removes a specific delivered notification by its identifier.
|
||||
export function RemoveDeliveredNotification(identifier: string): Promise<void>;
|
||||
|
||||
// [RemoveNotification](https://wails.io/docs/reference/runtime/notification#removenotification)
|
||||
// Removes a notification by its identifier (cross-platform convenience function).
|
||||
export function RemoveNotification(identifier: string): Promise<void>;
|
||||
@@ -0,0 +1,298 @@
|
||||
/*
|
||||
_ __ _ __
|
||||
| | / /___ _(_) /____
|
||||
| | /| / / __ `/ / / ___/
|
||||
| |/ |/ / /_/ / / (__ )
|
||||
|__/|__/\__,_/_/_/____/
|
||||
The electron alternative for Go
|
||||
(c) Lea Anthony 2019-present
|
||||
*/
|
||||
|
||||
export function LogPrint(message) {
|
||||
window.runtime.LogPrint(message);
|
||||
}
|
||||
|
||||
export function LogTrace(message) {
|
||||
window.runtime.LogTrace(message);
|
||||
}
|
||||
|
||||
export function LogDebug(message) {
|
||||
window.runtime.LogDebug(message);
|
||||
}
|
||||
|
||||
export function LogInfo(message) {
|
||||
window.runtime.LogInfo(message);
|
||||
}
|
||||
|
||||
export function LogWarning(message) {
|
||||
window.runtime.LogWarning(message);
|
||||
}
|
||||
|
||||
export function LogError(message) {
|
||||
window.runtime.LogError(message);
|
||||
}
|
||||
|
||||
export function LogFatal(message) {
|
||||
window.runtime.LogFatal(message);
|
||||
}
|
||||
|
||||
export function EventsOnMultiple(eventName, callback, maxCallbacks) {
|
||||
return window.runtime.EventsOnMultiple(eventName, callback, maxCallbacks);
|
||||
}
|
||||
|
||||
export function EventsOn(eventName, callback) {
|
||||
return EventsOnMultiple(eventName, callback, -1);
|
||||
}
|
||||
|
||||
export function EventsOff(eventName, ...additionalEventNames) {
|
||||
return window.runtime.EventsOff(eventName, ...additionalEventNames);
|
||||
}
|
||||
|
||||
export function EventsOffAll() {
|
||||
return window.runtime.EventsOffAll();
|
||||
}
|
||||
|
||||
export function EventsOnce(eventName, callback) {
|
||||
return EventsOnMultiple(eventName, callback, 1);
|
||||
}
|
||||
|
||||
export function EventsEmit(eventName) {
|
||||
let args = [eventName].slice.call(arguments);
|
||||
return window.runtime.EventsEmit.apply(null, args);
|
||||
}
|
||||
|
||||
export function WindowReload() {
|
||||
window.runtime.WindowReload();
|
||||
}
|
||||
|
||||
export function WindowReloadApp() {
|
||||
window.runtime.WindowReloadApp();
|
||||
}
|
||||
|
||||
export function WindowSetAlwaysOnTop(b) {
|
||||
window.runtime.WindowSetAlwaysOnTop(b);
|
||||
}
|
||||
|
||||
export function WindowSetSystemDefaultTheme() {
|
||||
window.runtime.WindowSetSystemDefaultTheme();
|
||||
}
|
||||
|
||||
export function WindowSetLightTheme() {
|
||||
window.runtime.WindowSetLightTheme();
|
||||
}
|
||||
|
||||
export function WindowSetDarkTheme() {
|
||||
window.runtime.WindowSetDarkTheme();
|
||||
}
|
||||
|
||||
export function WindowCenter() {
|
||||
window.runtime.WindowCenter();
|
||||
}
|
||||
|
||||
export function WindowSetTitle(title) {
|
||||
window.runtime.WindowSetTitle(title);
|
||||
}
|
||||
|
||||
export function WindowFullscreen() {
|
||||
window.runtime.WindowFullscreen();
|
||||
}
|
||||
|
||||
export function WindowUnfullscreen() {
|
||||
window.runtime.WindowUnfullscreen();
|
||||
}
|
||||
|
||||
export function WindowIsFullscreen() {
|
||||
return window.runtime.WindowIsFullscreen();
|
||||
}
|
||||
|
||||
export function WindowGetSize() {
|
||||
return window.runtime.WindowGetSize();
|
||||
}
|
||||
|
||||
export function WindowSetSize(width, height) {
|
||||
window.runtime.WindowSetSize(width, height);
|
||||
}
|
||||
|
||||
export function WindowSetMaxSize(width, height) {
|
||||
window.runtime.WindowSetMaxSize(width, height);
|
||||
}
|
||||
|
||||
export function WindowSetMinSize(width, height) {
|
||||
window.runtime.WindowSetMinSize(width, height);
|
||||
}
|
||||
|
||||
export function WindowSetPosition(x, y) {
|
||||
window.runtime.WindowSetPosition(x, y);
|
||||
}
|
||||
|
||||
export function WindowGetPosition() {
|
||||
return window.runtime.WindowGetPosition();
|
||||
}
|
||||
|
||||
export function WindowHide() {
|
||||
window.runtime.WindowHide();
|
||||
}
|
||||
|
||||
export function WindowShow() {
|
||||
window.runtime.WindowShow();
|
||||
}
|
||||
|
||||
export function WindowMaximise() {
|
||||
window.runtime.WindowMaximise();
|
||||
}
|
||||
|
||||
export function WindowToggleMaximise() {
|
||||
window.runtime.WindowToggleMaximise();
|
||||
}
|
||||
|
||||
export function WindowUnmaximise() {
|
||||
window.runtime.WindowUnmaximise();
|
||||
}
|
||||
|
||||
export function WindowIsMaximised() {
|
||||
return window.runtime.WindowIsMaximised();
|
||||
}
|
||||
|
||||
export function WindowMinimise() {
|
||||
window.runtime.WindowMinimise();
|
||||
}
|
||||
|
||||
export function WindowUnminimise() {
|
||||
window.runtime.WindowUnminimise();
|
||||
}
|
||||
|
||||
export function WindowSetBackgroundColour(R, G, B, A) {
|
||||
window.runtime.WindowSetBackgroundColour(R, G, B, A);
|
||||
}
|
||||
|
||||
export function ScreenGetAll() {
|
||||
return window.runtime.ScreenGetAll();
|
||||
}
|
||||
|
||||
export function WindowIsMinimised() {
|
||||
return window.runtime.WindowIsMinimised();
|
||||
}
|
||||
|
||||
export function WindowIsNormal() {
|
||||
return window.runtime.WindowIsNormal();
|
||||
}
|
||||
|
||||
export function BrowserOpenURL(url) {
|
||||
window.runtime.BrowserOpenURL(url);
|
||||
}
|
||||
|
||||
export function Environment() {
|
||||
return window.runtime.Environment();
|
||||
}
|
||||
|
||||
export function Quit() {
|
||||
window.runtime.Quit();
|
||||
}
|
||||
|
||||
export function Hide() {
|
||||
window.runtime.Hide();
|
||||
}
|
||||
|
||||
export function Show() {
|
||||
window.runtime.Show();
|
||||
}
|
||||
|
||||
export function ClipboardGetText() {
|
||||
return window.runtime.ClipboardGetText();
|
||||
}
|
||||
|
||||
export function ClipboardSetText(text) {
|
||||
return window.runtime.ClipboardSetText(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback for OnFileDrop returns a slice of file path strings when a drop is finished.
|
||||
*
|
||||
* @export
|
||||
* @callback OnFileDropCallback
|
||||
* @param {number} x - x coordinate of the drop
|
||||
* @param {number} y - y coordinate of the drop
|
||||
* @param {string[]} paths - A list of file paths.
|
||||
*/
|
||||
|
||||
/**
|
||||
* OnFileDrop listens to drag and drop events and calls the callback with the coordinates of the drop and an array of path strings.
|
||||
*
|
||||
* @export
|
||||
* @param {OnFileDropCallback} callback - Callback for OnFileDrop returns a slice of file path strings when a drop is finished.
|
||||
* @param {boolean} [useDropTarget=true] - Only call the callback when the drop finished on an element that has the drop target style. (--wails-drop-target)
|
||||
*/
|
||||
export function OnFileDrop(callback, useDropTarget) {
|
||||
return window.runtime.OnFileDrop(callback, useDropTarget);
|
||||
}
|
||||
|
||||
/**
|
||||
* OnFileDropOff removes the drag and drop listeners and handlers.
|
||||
*/
|
||||
export function OnFileDropOff() {
|
||||
return window.runtime.OnFileDropOff();
|
||||
}
|
||||
|
||||
export function CanResolveFilePaths() {
|
||||
return window.runtime.CanResolveFilePaths();
|
||||
}
|
||||
|
||||
export function ResolveFilePaths(files) {
|
||||
return window.runtime.ResolveFilePaths(files);
|
||||
}
|
||||
|
||||
export function InitializeNotifications() {
|
||||
return window.runtime.InitializeNotifications();
|
||||
}
|
||||
|
||||
export function CleanupNotifications() {
|
||||
return window.runtime.CleanupNotifications();
|
||||
}
|
||||
|
||||
export function IsNotificationAvailable() {
|
||||
return window.runtime.IsNotificationAvailable();
|
||||
}
|
||||
|
||||
export function RequestNotificationAuthorization() {
|
||||
return window.runtime.RequestNotificationAuthorization();
|
||||
}
|
||||
|
||||
export function CheckNotificationAuthorization() {
|
||||
return window.runtime.CheckNotificationAuthorization();
|
||||
}
|
||||
|
||||
export function SendNotification(options) {
|
||||
return window.runtime.SendNotification(options);
|
||||
}
|
||||
|
||||
export function SendNotificationWithActions(options) {
|
||||
return window.runtime.SendNotificationWithActions(options);
|
||||
}
|
||||
|
||||
export function RegisterNotificationCategory(category) {
|
||||
return window.runtime.RegisterNotificationCategory(category);
|
||||
}
|
||||
|
||||
export function RemoveNotificationCategory(categoryId) {
|
||||
return window.runtime.RemoveNotificationCategory(categoryId);
|
||||
}
|
||||
|
||||
export function RemoveAllPendingNotifications() {
|
||||
return window.runtime.RemoveAllPendingNotifications();
|
||||
}
|
||||
|
||||
export function RemovePendingNotification(identifier) {
|
||||
return window.runtime.RemovePendingNotification(identifier);
|
||||
}
|
||||
|
||||
export function RemoveAllDeliveredNotifications() {
|
||||
return window.runtime.RemoveAllDeliveredNotifications();
|
||||
}
|
||||
|
||||
export function RemoveDeliveredNotification(identifier) {
|
||||
return window.runtime.RemoveDeliveredNotification(identifier);
|
||||
}
|
||||
|
||||
export function RemoveNotification(identifier) {
|
||||
return window.runtime.RemoveNotification(identifier);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
module github.com/mmmy/snapgo
|
||||
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
fyne.io/systray v1.12.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.30.3
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.17.27
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2
|
||||
github.com/jlaffaye/ftp v0.2.0
|
||||
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237
|
||||
github.com/pkg/sftp v1.13.10
|
||||
github.com/wailsapp/wails/v2 v2.12.0
|
||||
golang.design/x/clipboard v0.7.0
|
||||
golang.design/x/hotkey v0.4.1
|
||||
golang.org/x/crypto v0.41.0
|
||||
golang.org/x/image v0.12.0
|
||||
)
|
||||
|
||||
require (
|
||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect
|
||||
github.com/aws/smithy-go v1.20.3 // indirect
|
||||
github.com/bep/debounce v1.2.1 // indirect
|
||||
github.com/gen2brain/shm v0.0.0-20230802011745-f2460f5984f7 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/hashicorp/errwrap v1.0.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
|
||||
github.com/jezek/xgb v1.1.0 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
github.com/labstack/echo/v4 v4.13.3 // indirect
|
||||
github.com/labstack/gommon v0.4.2 // indirect
|
||||
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
|
||||
github.com/leaanthony/gosod v1.0.4 // indirect
|
||||
github.com/leaanthony/slicer v1.6.0 // indirect
|
||||
github.com/leaanthony/u v1.1.1 // indirect
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/samber/lo v1.49.1 // indirect
|
||||
github.com/tkrajina/go-reflector v0.5.8 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/wailsapp/go-webview2 v1.0.22 // indirect
|
||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect
|
||||
golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect
|
||||
golang.org/x/net v0.42.0 // indirect
|
||||
golang.org/x/sys v0.35.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,179 @@
|
||||
fyne.io/systray v1.12.1 h1:ygBD6aZXwiOmZoY5N+ukbH9pih0Kq6fYgVeMYbr5skQ=
|
||||
fyne.io/systray v1.12.1/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
|
||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
|
||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/aws/aws-sdk-go-v2 v1.30.3 h1:jUeBtG0Ih+ZIFH0F4UkmL9w3cSpaMv9tYYDbzILP8dY=
|
||||
github.com/aws/aws-sdk-go-v2 v1.30.3/go.mod h1:nIQjQVp5sfpQcTc9mPSr1B0PaWK5ByX9MOoDadSN4lc=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 h1:Z5r7SycxmSllHYmaAZPpmN8GviDrSGhMS6bldqtXZPw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15/go.mod h1:CetW7bDE00QoGEmPUoZuRog07SGVAUVW6LFpNP0YfIg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 h1:YPYe6ZmvUfDDDELqEKtAd6bo8zxhkm+XEFEzQisqUIE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17/go.mod h1:oBtcnYua/CgzCWYN7NZ5j7PotFDaFSUjCYVTtfyn7vw=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 h1:246A4lSTXWJw/rmlQI+TT2OcqeDMKBdyjEQrafMaQdA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15/go.mod h1:haVfg3761/WF7YPuJOER2MP0k4UAXyHaLclKXB6usDg=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2 h1:sZXIzO38GZOU+O0C+INqbH7C2yALwfMWpd64tONS/NE=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2/go.mod h1:Lcxzg5rojyVPU/0eFwLtcyTaek/6Mtic5B1gJo7e/zE=
|
||||
github.com/aws/smithy-go v1.20.3 h1:ryHwveWzPV5BIof6fyDvor6V3iUL7nTfiTKXHiW05nE=
|
||||
github.com/aws/smithy-go v1.20.3/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E=
|
||||
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gen2brain/shm v0.0.0-20230802011745-f2460f5984f7 h1:VLEKvjGJYAMCXw0/32r9io61tEXnMWDRxMk+peyRVFc=
|
||||
github.com/gen2brain/shm v0.0.0-20230802011745-f2460f5984f7/go.mod h1:uF6rMu/1nvu+5DpiRLwusA6xB8zlkNoGzKn8lmYONUo=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
|
||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||
github.com/jezek/xgb v1.1.0 h1:wnpxJzP1+rkbGclEkmwpVFQWpuE2PUGNUzP8SbfFobk=
|
||||
github.com/jezek/xgb v1.1.0/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk=
|
||||
github.com/jlaffaye/ftp v0.2.0 h1:lXNvW7cBu7R/68bknOX3MrRIIqZ61zELs1P2RAiA3lg=
|
||||
github.com/jlaffaye/ftp v0.2.0/go.mod h1:is2Ds5qkhceAPy2xD6RLI6hmp/qysSoymZ+Z2uTnspI=
|
||||
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237 h1:YOp8St+CM/AQ9Vp4XYm4272E77MptJDHkwypQHIRl9Q=
|
||||
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237/go.mod h1:e7qQlOY68wOz4b82D7n+DdaptZAi+SHW0+yKiWZzEYE=
|
||||
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
|
||||
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc=
|
||||
github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA=
|
||||
github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A=
|
||||
github.com/leaanthony/go-ansi-parser v1.6.1/go.mod h1:+vva/2y4alzVmmIEpk9QDhA7vLC5zKDTRwfZGOp3IWU=
|
||||
github.com/leaanthony/gosod v1.0.4 h1:YLAbVyd591MRffDgxUOU1NwLhT9T1/YiwjKZpkNFeaI=
|
||||
github.com/leaanthony/gosod v1.0.4/go.mod h1:GKuIL0zzPj3O1SdWQOdgURSuhkF+Urizzxh26t9f1cw=
|
||||
github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/Js=
|
||||
github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8=
|
||||
github.com/leaanthony/u v1.1.1 h1:TUFjwDGlNX+WuwVEzDqQwC2lOv0P4uhTQw7CMFdiK7M=
|
||||
github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
|
||||
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
|
||||
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU=
|
||||
github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew=
|
||||
github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/wailsapp/go-webview2 v1.0.22 h1:YT61F5lj+GGaat5OB96Aa3b4QA+mybD0Ggq6NZijQ58=
|
||||
github.com/wailsapp/go-webview2 v1.0.22/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
|
||||
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
|
||||
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
||||
github.com/wailsapp/wails/v2 v2.12.0 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c=
|
||||
github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.design/x/clipboard v0.7.0 h1:4Je8M/ys9AJumVnl8m+rZnIvstSnYj1fvzqYrU3TXvo=
|
||||
golang.design/x/clipboard v0.7.0/go.mod h1:PQIvqYO9GP29yINEfsEn5zSQKAz3UgXmZKzDA6dnq2E=
|
||||
golang.design/x/hotkey v0.4.1 h1:zLP/2Pztl4WjyxURdW84GoZ5LUrr6hr69CzJFJ5U1go=
|
||||
golang.design/x/hotkey v0.4.1/go.mod h1:M8SGcwFYHnKRa83FpTFQoZvPO5vVT+kWPztFqTQKmXA=
|
||||
golang.design/x/mainthread v0.3.0 h1:UwFus0lcPodNpMOGoQMe87jSFwbSsEY//CA7yVmu4j8=
|
||||
golang.design/x/mainthread v0.3.0/go.mod h1:vYX7cF2b3pTJMGM/hc13NmN6kblKnf4/IyvHeu259L0=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 h1:estk1glOnSVeJ9tdEZZc5mAMDZk5lNJNyJ6DvrBkTEU=
|
||||
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
|
||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||
golang.org/x/image v0.12.0 h1:w13vZbU4o5rKOFFR8y7M+c4A5jXDC0uXTdHYRP8X2DQ=
|
||||
golang.org/x/image v0.12.0/go.mod h1:Lu90jvHG7GfemOIcldsh9A2hS01ocl6oNO7ype5mEnk=
|
||||
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
|
||||
golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c h1:Gk61ECugwEHL6IiyyNLXNzmu8XslmRP2dS0xjIYhbb4=
|
||||
golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c/go.mod h1:aAjjkJNdrh3PMckS4B10TGS2nag27cbKR1y2BpUxsiY=
|
||||
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
|
||||
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,422 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
xfont "golang.org/x/image/font"
|
||||
"golang.org/x/image/font/basicfont"
|
||||
"golang.org/x/image/font/opentype"
|
||||
"golang.org/x/image/math/fixed"
|
||||
)
|
||||
|
||||
// Annotation describes a user-drawn mark relative to the selected screenshot.
|
||||
// Coordinates are logical pixels in the same coordinate system as the overlay.
|
||||
type Annotation struct {
|
||||
Tool string `json:"tool"`
|
||||
Color string `json:"color"`
|
||||
Points []Point `json:"points"`
|
||||
Text string `json:"text,omitempty"`
|
||||
StrokeWidth float64 `json:"strokeWidth,omitempty"`
|
||||
FontSize float64 `json:"fontSize,omitempty"`
|
||||
}
|
||||
|
||||
type Point struct {
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
}
|
||||
|
||||
// ApplyAnnotations decodes a PNG, draws all annotations, and re-encodes it.
|
||||
func ApplyAnnotations(pngBytes []byte, annotations []Annotation, scale float64) ([]byte, error) {
|
||||
return ApplyAnnotationsWithScale(pngBytes, annotations, scale, scale)
|
||||
}
|
||||
|
||||
// ApplyAnnotationsWithScale decodes a PNG, draws all annotations using the
|
||||
// actual device-pixel scale of the captured image, and re-encodes it.
|
||||
func ApplyAnnotationsWithScale(pngBytes []byte, annotations []Annotation, scaleX, scaleY float64) ([]byte, error) {
|
||||
if len(annotations) == 0 {
|
||||
return pngBytes, nil
|
||||
}
|
||||
if scaleX <= 0 {
|
||||
scaleX = 1
|
||||
}
|
||||
if scaleY <= 0 {
|
||||
scaleY = scaleX
|
||||
}
|
||||
strokeScale := math.Max(scaleX, scaleY)
|
||||
|
||||
src, err := png.Decode(bytes.NewReader(pngBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode annotated png: %w", err)
|
||||
}
|
||||
bounds := src.Bounds()
|
||||
dst := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
|
||||
draw.Draw(dst, dst.Bounds(), src, bounds.Min, draw.Src)
|
||||
|
||||
for _, ann := range annotations {
|
||||
c, err := parseHexColor(ann.Color)
|
||||
if err != nil {
|
||||
c = color.RGBA{R: 59, G: 130, B: 246, A: 255}
|
||||
}
|
||||
strokeWidth := ann.StrokeWidth
|
||||
if strokeWidth <= 0 {
|
||||
strokeWidth = 3
|
||||
}
|
||||
width := int(math.Max(1, math.Round(strokeWidth*strokeScale)))
|
||||
switch ann.Tool {
|
||||
case "pen":
|
||||
drawPolyline(dst, ann.Points, scaleX, scaleY, width, c)
|
||||
case "line":
|
||||
drawStraightLine(dst, ann.Points, scaleX, scaleY, width, c)
|
||||
case "arrow":
|
||||
drawArrow(dst, ann.Points, scaleX, scaleY, width, c)
|
||||
case "rect":
|
||||
drawRectOutline(dst, ann.Points, scaleX, scaleY, width, c)
|
||||
case "ellipse":
|
||||
drawEllipseOutline(dst, ann.Points, scaleX, scaleY, width, c)
|
||||
case "text":
|
||||
drawTextAnnotation(dst, ann, scaleX, scaleY, c)
|
||||
case "mosaic-brush":
|
||||
applyMosaicBrush(dst, ann.Points, scaleX, scaleY, width)
|
||||
case "mosaic-rect":
|
||||
applyMosaicRect(dst, ann.Points, scaleX, scaleY)
|
||||
}
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, dst); err != nil {
|
||||
return nil, fmt.Errorf("encode annotated png: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func drawStraightLine(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||
if len(points) < 2 {
|
||||
return
|
||||
}
|
||||
drawLine(img, scalePoint(points[0], scaleX, scaleY), scalePoint(points[len(points)-1], scaleX, scaleY), width, c)
|
||||
}
|
||||
|
||||
func drawArrow(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||
if len(points) < 2 {
|
||||
return
|
||||
}
|
||||
start := scalePoint(points[0], scaleX, scaleY)
|
||||
end := scalePoint(points[len(points)-1], scaleX, scaleY)
|
||||
dx, dy := end.X-start.X, end.Y-start.Y
|
||||
length := math.Hypot(dx, dy)
|
||||
if length < 1 {
|
||||
return
|
||||
}
|
||||
drawLine(img, start, end, width, c)
|
||||
headLength := math.Min(length*0.45, math.Max(10*math.Max(scaleX, scaleY), float64(width)*4))
|
||||
angle := math.Atan2(dy, dx)
|
||||
spread := math.Pi / 6
|
||||
left := Point{X: end.X - headLength*math.Cos(angle-spread), Y: end.Y - headLength*math.Sin(angle-spread)}
|
||||
right := Point{X: end.X - headLength*math.Cos(angle+spread), Y: end.Y - headLength*math.Sin(angle+spread)}
|
||||
drawLine(img, end, left, width, c)
|
||||
drawLine(img, end, right, width, c)
|
||||
}
|
||||
|
||||
const mosaicBlockSize = 10
|
||||
|
||||
func applyMosaicBrush(img *image.RGBA, points []Point, scaleX, scaleY float64, width int) {
|
||||
if len(points) == 0 {
|
||||
return
|
||||
}
|
||||
mask := image.NewAlpha(img.Bounds())
|
||||
maskColor := color.RGBA{A: 255}
|
||||
if len(points) == 1 {
|
||||
drawDotMask(mask, scalePoint(points[0], scaleX, scaleY), width, maskColor)
|
||||
} else {
|
||||
for i := 1; i < len(points); i++ {
|
||||
drawMaskLine(mask, scalePoint(points[i-1], scaleX, scaleY), scalePoint(points[i], scaleX, scaleY), width, maskColor)
|
||||
}
|
||||
}
|
||||
applyPixelation(img, img.Bounds(), mask)
|
||||
}
|
||||
|
||||
func applyMosaicRect(img *image.RGBA, points []Point, scaleX, scaleY float64) {
|
||||
if len(points) < 2 {
|
||||
return
|
||||
}
|
||||
a := scalePoint(points[0], scaleX, scaleY)
|
||||
b := scalePoint(points[len(points)-1], scaleX, scaleY)
|
||||
x1, x2 := ordered(a.X, b.X)
|
||||
y1, y2 := ordered(a.Y, b.Y)
|
||||
r := image.Rect(int(math.Floor(x1)), int(math.Floor(y1)), int(math.Ceil(x2)), int(math.Ceil(y2))).Intersect(img.Bounds())
|
||||
applyPixelation(img, r, nil)
|
||||
}
|
||||
|
||||
func applyPixelation(img *image.RGBA, region image.Rectangle, mask *image.Alpha) {
|
||||
if region.Empty() {
|
||||
return
|
||||
}
|
||||
for y := region.Min.Y; y < region.Max.Y; y += mosaicBlockSize {
|
||||
for x := region.Min.X; x < region.Max.X; x += mosaicBlockSize {
|
||||
block := image.Rect(x, y, min(x+mosaicBlockSize, region.Max.X), min(y+mosaicBlockSize, region.Max.Y))
|
||||
var r, g, b, a, count uint64
|
||||
for py := block.Min.Y; py < block.Max.Y; py++ {
|
||||
for px := block.Min.X; px < block.Max.X; px++ {
|
||||
c := img.RGBAAt(px, py)
|
||||
r += uint64(c.R)
|
||||
g += uint64(c.G)
|
||||
b += uint64(c.B)
|
||||
a += uint64(c.A)
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
avg := color.RGBA{uint8(r / count), uint8(g / count), uint8(b / count), uint8(a / count)}
|
||||
for py := block.Min.Y; py < block.Max.Y; py++ {
|
||||
for px := block.Min.X; px < block.Max.X; px++ {
|
||||
if mask == nil || mask.AlphaAt(px, py).A > 0 {
|
||||
img.SetRGBA(px, py, avg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func drawMaskLine(mask *image.Alpha, a, b Point, width int, c color.RGBA) {
|
||||
dx, dy := b.X-a.X, b.Y-a.Y
|
||||
steps := int(math.Max(math.Abs(dx), math.Abs(dy)))
|
||||
if steps == 0 {
|
||||
drawDotMask(mask, a, width, c)
|
||||
return
|
||||
}
|
||||
for i := 0; i <= steps; i++ {
|
||||
t := float64(i) / float64(steps)
|
||||
drawDotMask(mask, Point{X: a.X + dx*t, Y: a.Y + dy*t}, width, c)
|
||||
}
|
||||
}
|
||||
|
||||
func drawDotMask(mask *image.Alpha, p Point, width int, c color.RGBA) {
|
||||
radius := float64(width) / 2
|
||||
for y := int(math.Floor(p.Y - radius)); y <= int(math.Ceil(p.Y+radius)); y++ {
|
||||
for x := int(math.Floor(p.X - radius)); x <= int(math.Ceil(p.X+radius)); x++ {
|
||||
if image.Pt(x, y).In(mask.Bounds()) && math.Hypot(float64(x)-p.X, float64(y)-p.Y) <= radius {
|
||||
mask.SetAlpha(x, y, color.Alpha{A: c.A})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseHexColor(hex string) (color.RGBA, error) {
|
||||
value := strings.TrimPrefix(strings.TrimSpace(hex), "#")
|
||||
if len(value) != 6 {
|
||||
return color.RGBA{}, fmt.Errorf("invalid color %q", hex)
|
||||
}
|
||||
n, err := strconv.ParseUint(value, 16, 32)
|
||||
if err != nil {
|
||||
return color.RGBA{}, err
|
||||
}
|
||||
return color.RGBA{
|
||||
R: uint8(n >> 16),
|
||||
G: uint8(n >> 8),
|
||||
B: uint8(n),
|
||||
A: 255,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func drawPolyline(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||
if len(points) == 1 {
|
||||
drawDot(img, scalePoint(points[0], scaleX, scaleY), width, c)
|
||||
return
|
||||
}
|
||||
for i := 1; i < len(points); i++ {
|
||||
drawLine(img, scalePoint(points[i-1], scaleX, scaleY), scalePoint(points[i], scaleX, scaleY), width, c)
|
||||
}
|
||||
}
|
||||
|
||||
func drawRectOutline(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||
if len(points) < 2 {
|
||||
return
|
||||
}
|
||||
a := scalePoint(points[0], scaleX, scaleY)
|
||||
b := scalePoint(points[len(points)-1], scaleX, scaleY)
|
||||
x1, x2 := ordered(a.X, b.X)
|
||||
y1, y2 := ordered(a.Y, b.Y)
|
||||
drawLine(img, Point{X: x1, Y: y1}, Point{X: x2, Y: y1}, width, c)
|
||||
drawLine(img, Point{X: x2, Y: y1}, Point{X: x2, Y: y2}, width, c)
|
||||
drawLine(img, Point{X: x2, Y: y2}, Point{X: x1, Y: y2}, width, c)
|
||||
drawLine(img, Point{X: x1, Y: y2}, Point{X: x1, Y: y1}, width, c)
|
||||
}
|
||||
|
||||
func drawEllipseOutline(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||
if len(points) < 2 {
|
||||
return
|
||||
}
|
||||
a := scalePoint(points[0], scaleX, scaleY)
|
||||
b := scalePoint(points[len(points)-1], scaleX, scaleY)
|
||||
x1, x2 := ordered(a.X, b.X)
|
||||
y1, y2 := ordered(a.Y, b.Y)
|
||||
rx := (x2 - x1) / 2
|
||||
ry := (y2 - y1) / 2
|
||||
if rx <= 0 || ry <= 0 {
|
||||
return
|
||||
}
|
||||
cx := x1 + rx
|
||||
cy := y1 + ry
|
||||
steps := int(math.Max(48, math.Ceil(2*math.Pi*math.Max(rx, ry)/4)))
|
||||
prev := Point{
|
||||
X: cx + rx,
|
||||
Y: cy,
|
||||
}
|
||||
for i := 1; i <= steps; i++ {
|
||||
theta := 2 * math.Pi * float64(i) / float64(steps)
|
||||
next := Point{
|
||||
X: cx + rx*math.Cos(theta),
|
||||
Y: cy + ry*math.Sin(theta),
|
||||
}
|
||||
drawLine(img, prev, next, width, c)
|
||||
prev = next
|
||||
}
|
||||
}
|
||||
|
||||
func drawLine(img *image.RGBA, a, b Point, width int, c color.RGBA) {
|
||||
dx := b.X - a.X
|
||||
dy := b.Y - a.Y
|
||||
steps := int(math.Max(math.Abs(dx), math.Abs(dy)))
|
||||
if steps == 0 {
|
||||
drawDot(img, a, width, c)
|
||||
return
|
||||
}
|
||||
for i := 0; i <= steps; i++ {
|
||||
t := float64(i) / float64(steps)
|
||||
drawDot(img, Point{X: a.X + dx*t, Y: a.Y + dy*t}, width, c)
|
||||
}
|
||||
}
|
||||
|
||||
func drawDot(img *image.RGBA, p Point, width int, c color.RGBA) {
|
||||
radius := float64(width) / 2
|
||||
minX := int(math.Floor(p.X - radius))
|
||||
maxX := int(math.Ceil(p.X + radius))
|
||||
minY := int(math.Floor(p.Y - radius))
|
||||
maxY := int(math.Ceil(p.Y + radius))
|
||||
bounds := img.Bounds()
|
||||
for y := minY; y <= maxY; y++ {
|
||||
for x := minX; x <= maxX; x++ {
|
||||
if !image.Pt(x, y).In(bounds) {
|
||||
continue
|
||||
}
|
||||
if math.Hypot(float64(x)-p.X, float64(y)-p.Y) <= radius {
|
||||
img.SetRGBA(x, y, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func scalePoint(p Point, scaleX, scaleY float64) Point {
|
||||
return Point{X: p.X * scaleX, Y: p.Y * scaleY}
|
||||
}
|
||||
|
||||
func ordered(a, b float64) (float64, float64) {
|
||||
if a < b {
|
||||
return a, b
|
||||
}
|
||||
return b, a
|
||||
}
|
||||
|
||||
func drawTextAnnotation(img *image.RGBA, ann Annotation, scaleX, scaleY float64, c color.RGBA) {
|
||||
if len(ann.Points) == 0 {
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(ann.Text)
|
||||
if text == "" {
|
||||
return
|
||||
}
|
||||
fontSize := ann.FontSize
|
||||
if fontSize <= 0 {
|
||||
fontSize = 20
|
||||
}
|
||||
face := annotationFontFace(fontSize * scaleY)
|
||||
if face == nil {
|
||||
face = basicfont.Face7x13
|
||||
}
|
||||
|
||||
origin := scalePoint(ann.Points[0], scaleX, scaleY)
|
||||
metrics := face.Metrics()
|
||||
lineHeight := metrics.Height
|
||||
if lineHeight <= 0 {
|
||||
lineHeight = fixed.I(int(math.Ceil(fontSize * 1.2 * scaleY)))
|
||||
}
|
||||
d := &xfont.Drawer{
|
||||
Dst: img,
|
||||
Src: image.NewUniform(c),
|
||||
Face: face,
|
||||
}
|
||||
baselineY := fixed.I(int(math.Round(origin.Y))) + metrics.Ascent
|
||||
x := fixed.I(int(math.Round(origin.X)))
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
if line != "" {
|
||||
d.Dot = fixed.Point26_6{X: x, Y: baselineY}
|
||||
d.DrawString(line)
|
||||
}
|
||||
baselineY += lineHeight
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
annotationFontOnce sync.Once
|
||||
annotationFont *opentype.Font
|
||||
)
|
||||
|
||||
func annotationFontFace(size float64) xfont.Face {
|
||||
if size <= 0 {
|
||||
size = 20
|
||||
}
|
||||
annotationFontOnce.Do(func() {
|
||||
annotationFont = loadAnnotationFont()
|
||||
})
|
||||
if annotationFont == nil {
|
||||
return basicfont.Face7x13
|
||||
}
|
||||
face, err := opentype.NewFace(annotationFont, &opentype.FaceOptions{
|
||||
Size: size,
|
||||
DPI: 72,
|
||||
Hinting: xfont.HintingFull,
|
||||
})
|
||||
if err != nil {
|
||||
return basicfont.Face7x13
|
||||
}
|
||||
return face
|
||||
}
|
||||
|
||||
func loadAnnotationFont() *opentype.Font {
|
||||
paths := []string{
|
||||
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
|
||||
"/Library/Fonts/Arial Unicode.ttf",
|
||||
"/System/Library/Fonts/Hiragino Sans GB.ttc",
|
||||
"/System/Library/Fonts/PingFang.ttc",
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
}
|
||||
for _, path := range paths {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if collection, err := opentype.ParseCollection(data); err == nil && collection.NumFonts() > 0 {
|
||||
if font, err := collection.Font(0); err == nil {
|
||||
return font
|
||||
}
|
||||
}
|
||||
if font, err := opentype.Parse(data); err == nil {
|
||||
return font
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApplyAnnotationsDrawsIntoPNG(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 40, 40))
|
||||
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{
|
||||
{
|
||||
Tool: "rect",
|
||||
Color: "#ef4444",
|
||||
Points: []Point{
|
||||
{X: 5, Y: 5},
|
||||
{X: 30, Y: 30},
|
||||
},
|
||||
},
|
||||
}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
if got := color.RGBAModel.Convert(img.At(5, 5)).(color.RGBA); got.R != 0xef || got.G != 0x44 || got.B != 0x44 {
|
||||
t.Fatalf("expected annotated pixel at rectangle edge, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsNoAnnotationsReturnsOriginalBytes(t *testing.T) {
|
||||
original := []byte("not decoded when no annotations")
|
||||
out, err := ApplyAnnotations(original, nil, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
if !bytes.Equal(out, original) {
|
||||
t.Fatalf("expected original bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsDrawsTextIntoPNG(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 120, 80))
|
||||
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{
|
||||
{
|
||||
Tool: "text",
|
||||
Color: "#ef4444",
|
||||
Points: []Point{
|
||||
{X: 10, Y: 10},
|
||||
},
|
||||
Text: "T",
|
||||
},
|
||||
}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
found := false
|
||||
for y := 8; y < 40 && !found; y++ {
|
||||
for x := 8; x < 40; x++ {
|
||||
got := color.RGBAModel.Convert(img.At(x, y)).(color.RGBA)
|
||||
if got.R > 180 && got.G < 180 && got.B < 180 {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected red text pixels near annotation point")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsWithScaleDrawsTextAtDevicePosition(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 220, 120))
|
||||
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
|
||||
out, err := ApplyAnnotationsWithScale(buf.Bytes(), []Annotation{
|
||||
{
|
||||
Tool: "text",
|
||||
Color: "#ef4444",
|
||||
Points: []Point{{X: 50, Y: 20}},
|
||||
Text: "T",
|
||||
FontSize: 20,
|
||||
},
|
||||
}, 2, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
minX := 999
|
||||
found := false
|
||||
for y := 0; y < img.Bounds().Dy(); y++ {
|
||||
for x := 0; x < img.Bounds().Dx(); x++ {
|
||||
got := color.RGBAModel.Convert(img.At(x, y)).(color.RGBA)
|
||||
if got.R > 180 && got.G < 180 && got.B < 180 {
|
||||
found = true
|
||||
if x < minX {
|
||||
minX = x
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected red text pixels")
|
||||
}
|
||||
if minX < 90 {
|
||||
t.Fatalf("expected text to be drawn near scaled x=100, min red x=%d", minX)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsUsesStrokeWidth(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 80, 80))
|
||||
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{
|
||||
{
|
||||
Tool: "rect",
|
||||
Color: "#ef4444",
|
||||
Points: []Point{{X: 20, Y: 20}, {X: 60, Y: 60}},
|
||||
StrokeWidth: 8,
|
||||
},
|
||||
}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
got := color.RGBAModel.Convert(img.At(20, 24)).(color.RGBA)
|
||||
if got.R < 180 || got.G > 180 || got.B > 180 {
|
||||
t.Fatalf("expected thick rectangle stroke to cover y=24, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsPixelatesMosaicRectangle(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 40, 30))
|
||||
for y := 0; y < 30; y++ {
|
||||
for x := 0; x < 40; x++ {
|
||||
src.SetRGBA(x, y, color.RGBA{R: uint8(x * 6), G: uint8(y * 8), B: uint8((x + y) * 3), A: 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{{
|
||||
Tool: "mosaic-rect", Points: []Point{{X: 10, Y: 5}, {X: 30, Y: 25}},
|
||||
}}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
if img.At(12, 7) != img.At(18, 13) {
|
||||
t.Fatalf("expected pixels in one mosaic block to share a color")
|
||||
}
|
||||
if img.At(5, 5) != src.At(5, 5) {
|
||||
t.Fatalf("expected pixels outside mosaic rectangle to remain unchanged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsPixelatesOnlyMosaicBrushStroke(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 50, 30))
|
||||
for y := 0; y < 30; y++ {
|
||||
for x := 0; x < 50; x++ {
|
||||
src.SetRGBA(x, y, color.RGBA{R: uint8(x * 5), G: uint8(y * 8), A: 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{{
|
||||
Tool: "mosaic-brush", StrokeWidth: 12, Points: []Point{{X: 5, Y: 15}, {X: 45, Y: 15}},
|
||||
}}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
if img.At(12, 15) == src.At(12, 15) {
|
||||
t.Fatalf("expected brush path to be pixelated")
|
||||
}
|
||||
if img.At(12, 2) != src.At(12, 2) {
|
||||
t.Fatalf("expected pixels outside brush path to remain unchanged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsDrawsStraightLine(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 60, 40))
|
||||
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{{
|
||||
Tool: "line", Color: "#ef4444", StrokeWidth: 4,
|
||||
Points: []Point{{X: 5, Y: 20}, {X: 50, Y: 20}},
|
||||
}}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
got := color.RGBAModel.Convert(img.At(30, 20)).(color.RGBA)
|
||||
if got.R < 180 || got.G > 180 || got.B > 180 {
|
||||
t.Fatalf("expected red line at center, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAnnotationsDrawsArrowHead(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 80, 60))
|
||||
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, src); err != nil {
|
||||
t.Fatalf("encode source: %v", err)
|
||||
}
|
||||
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{{
|
||||
Tool: "arrow", Color: "#3b82f6", StrokeWidth: 3,
|
||||
Points: []Point{{X: 10, Y: 30}, {X: 60, Y: 30}},
|
||||
}}, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("apply annotations: %v", err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatalf("decode output: %v", err)
|
||||
}
|
||||
shaft := color.RGBAModel.Convert(img.At(35, 30)).(color.RGBA)
|
||||
head := color.RGBAModel.Convert(img.At(52, 25)).(color.RGBA)
|
||||
if shaft.B < 180 || shaft.R > 140 || head.B < 180 || head.R > 140 {
|
||||
t.Fatalf("expected blue arrow shaft and head, got shaft=%#v head=%#v", shaft, head)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||
)
|
||||
|
||||
// CaptureActionsService handles non-upload actions on already-produced PNG
|
||||
// screenshots. Keeping these actions here makes save/copy available across
|
||||
// overlay implementations without binding them to Wails or a specific OS.
|
||||
type CaptureActionsService struct {
|
||||
Clipboard clipboard.Writer
|
||||
Notifier Notifier
|
||||
}
|
||||
|
||||
func (s *CaptureActionsService) CopyImage(_ context.Context, pngBytes []byte) error {
|
||||
if len(pngBytes) == 0 {
|
||||
err := fmt.Errorf("empty screenshot")
|
||||
s.notifyFailure(err.Error())
|
||||
return err
|
||||
}
|
||||
if s.Clipboard == nil {
|
||||
err := fmt.Errorf("clipboard is not configured")
|
||||
s.notifyFailure(err.Error())
|
||||
return err
|
||||
}
|
||||
if err := s.Clipboard.WriteImage(pngBytes); err != nil {
|
||||
s.notifyFailure("clipboard write failed: " + err.Error())
|
||||
return err
|
||||
}
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifySuccess("image copied to clipboard")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CaptureActionsService) SaveImage(_ context.Context, pngBytes []byte, dir string) (string, error) {
|
||||
if len(pngBytes) == 0 {
|
||||
err := fmt.Errorf("empty screenshot")
|
||||
s.notifyFailure(err.Error())
|
||||
return "", err
|
||||
}
|
||||
dir = strings.TrimSpace(dir)
|
||||
if dir == "" {
|
||||
err := fmt.Errorf("save directory is empty")
|
||||
s.notifyFailure(err.Error())
|
||||
return "", err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
s.notifyFailure("create save directory failed: " + err.Error())
|
||||
return "", err
|
||||
}
|
||||
path := uniquePNGPath(dir, time.Now())
|
||||
if err := os.WriteFile(path, pngBytes, 0o644); err != nil {
|
||||
s.notifyFailure("save failed: " + err.Error())
|
||||
return "", err
|
||||
}
|
||||
// Copy the saved path to the clipboard so the user can paste it right
|
||||
// away, mirroring how the upload/summary flows copy their result. A
|
||||
// clipboard failure must not fail the save itself.
|
||||
if s.Clipboard != nil {
|
||||
if err := s.Clipboard.WriteText(path); err != nil {
|
||||
s.notifyFailure("clipboard write failed: " + err.Error())
|
||||
}
|
||||
}
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifySuccess(path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func (s *CaptureActionsService) notifyFailure(reason string) {
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifyFailure(reason)
|
||||
}
|
||||
}
|
||||
|
||||
func uniquePNGPath(dir string, now time.Time) string {
|
||||
base := now.Format("20060102-150405")
|
||||
path := filepath.Join(dir, base+".png")
|
||||
for i := 1; fileExists(path); i++ {
|
||||
path = filepath.Join(dir, fmt.Sprintf("%s-%02d.png", base, i))
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeClipboard struct {
|
||||
text string
|
||||
image []byte
|
||||
}
|
||||
|
||||
func (f *fakeClipboard) WriteText(s string) error {
|
||||
f.text = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeClipboard) WriteImage(pngBytes []byte) error {
|
||||
f.image = append([]byte(nil), pngBytes...)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeNotifier struct {
|
||||
success string
|
||||
failure string
|
||||
}
|
||||
|
||||
func (f *fakeNotifier) NotifySuccess(value string) { f.success = value }
|
||||
func (f *fakeNotifier) NotifyFailure(reason string) { f.failure = reason }
|
||||
|
||||
func TestCaptureActionsCopyImageWritesPNGToClipboard(t *testing.T) {
|
||||
clip := &fakeClipboard{}
|
||||
notifier := &fakeNotifier{}
|
||||
svc := &CaptureActionsService{Clipboard: clip, Notifier: notifier}
|
||||
|
||||
err := svc.CopyImage(context.Background(), []byte("png"))
|
||||
if err != nil {
|
||||
t.Fatalf("copy image: %v", err)
|
||||
}
|
||||
if string(clip.image) != "png" {
|
||||
t.Fatalf("expected image bytes copied, got %q", string(clip.image))
|
||||
}
|
||||
if notifier.success != "image copied to clipboard" {
|
||||
t.Fatalf("expected copy success notification, got %q", notifier.success)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureActionsSaveImageWritesUniquePNG(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
svc := &CaptureActionsService{Notifier: &fakeNotifier{}}
|
||||
|
||||
path, err := svc.SaveImage(context.Background(), []byte("png"), dir)
|
||||
if err != nil {
|
||||
t.Fatalf("save image: %v", err)
|
||||
}
|
||||
if filepath.Dir(path) != dir {
|
||||
t.Fatalf("expected save in %q, got %q", dir, path)
|
||||
}
|
||||
if data, err := os.ReadFile(path); err != nil || string(data) != "png" {
|
||||
t.Fatalf("expected saved bytes, data=%q err=%v", string(data), err)
|
||||
}
|
||||
|
||||
next, err := svc.SaveImage(context.Background(), []byte("png2"), dir)
|
||||
if err != nil {
|
||||
t.Fatalf("save second image: %v", err)
|
||||
}
|
||||
if next == path {
|
||||
t.Fatalf("expected unique path for second save")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// capture_ftp.go — application-level FTP/SFTP upload orchestration.
|
||||
//
|
||||
// Design rationale:
|
||||
// - FTP/SFTP returns a remote filesystem path, not necessarily a public URL,
|
||||
// so this flow stays separate from the OSSProvider-based S3 pipeline.
|
||||
// - A tiny uploader interface keeps protocol libraries out of the
|
||||
// application layer and makes the upload/copy/notify sequence unit-testable.
|
||||
// - The dated filename layout is shared with SSH/SCP while FTP-specific path
|
||||
// validation prevents an invalid prefix from escaping the login root.
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||
)
|
||||
|
||||
// ftpSvcLog returns an application-layer FTP logger bound to the current
|
||||
// default slog handler.
|
||||
func ftpSvcLog() *slog.Logger { return slog.Default().With("component", "application.ftp") }
|
||||
|
||||
// FTPUploader abstracts both FTP and SFTP adapters.
|
||||
type FTPUploader interface {
|
||||
// Upload stores data at remoteRelPath, relative to the authenticated
|
||||
// account's login root.
|
||||
Upload(ctx context.Context, remoteRelPath string, data []byte) error
|
||||
}
|
||||
|
||||
// CaptureAndFTPService wires captured PNG bytes → FTP/SFTP → clipboard →
|
||||
// notification.
|
||||
type CaptureAndFTPService struct {
|
||||
Uploader FTPUploader
|
||||
Clipboard clipboard.Writer
|
||||
Notifier Notifier
|
||||
Cfg domain.FTPConfig
|
||||
}
|
||||
|
||||
// ExecuteWithBytes uploads previously captured PNG bytes and copies a display
|
||||
// path built from the configured root directory plus the uploaded relative
|
||||
// path. RootDirectory deliberately does not affect the upload destination.
|
||||
func (s *CaptureAndFTPService) ExecuteWithBytes(ctx context.Context, pngBytes []byte) error {
|
||||
if s.Uploader == nil {
|
||||
s.notifyFailure("FTP/SFTP not configured")
|
||||
return fmt.Errorf("ftp uploader is nil")
|
||||
}
|
||||
if len(pngBytes) == 0 {
|
||||
s.notifyFailure("empty screenshot")
|
||||
return fmt.Errorf("empty screenshot")
|
||||
}
|
||||
|
||||
relPath, err := buildFTPRemotePath(s.Cfg.PathPrefix)
|
||||
if err != nil {
|
||||
s.notifyFailure(err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
protocol := normalizedFTPProtocol(s.Cfg.Protocol)
|
||||
start := time.Now()
|
||||
ftpSvcLog().Info("file-transfer pipeline start",
|
||||
"protocol", protocol,
|
||||
"host", s.Cfg.Host,
|
||||
"user", s.Cfg.User,
|
||||
"port", s.Cfg.Port,
|
||||
"size", len(pngBytes),
|
||||
"remote_path", relPath,
|
||||
"strict_host_key", s.Cfg.StrictHostKey)
|
||||
|
||||
if err := s.Uploader.Upload(ctx, relPath, pngBytes); err != nil {
|
||||
ftpSvcLog().Error("file-transfer upload failed",
|
||||
"protocol", protocol,
|
||||
"remote_path", relPath,
|
||||
"elapsed", time.Since(start),
|
||||
"err", err)
|
||||
s.notifyFailure(strings.ToUpper(protocol) + " upload failed: " + err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
clipText := ftpShareText(protocol, s.Cfg.RootDirectory, relPath)
|
||||
if s.Clipboard != nil {
|
||||
if err := s.Clipboard.WriteText(clipText); err != nil {
|
||||
s.notifyFailure("clipboard write failed: " + err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifySuccess(clipText)
|
||||
}
|
||||
ftpSvcLog().Info("file-transfer pipeline done",
|
||||
"protocol", protocol,
|
||||
"remote_path", relPath,
|
||||
"total_elapsed", time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildFTPRemotePath validates the user-controlled prefix before reusing the
|
||||
// existing dated remote-path generator shared with SSH/SCP.
|
||||
func buildFTPRemotePath(prefix string) (string, error) {
|
||||
if err := validateFTPPathPrefix(prefix); err != nil {
|
||||
return "", err
|
||||
}
|
||||
prefix = strings.TrimSpace(prefix)
|
||||
prefix = strings.TrimPrefix(prefix, "~")
|
||||
prefix = strings.TrimLeft(prefix, "/")
|
||||
return buildRemoteRelPath(prefix), nil
|
||||
}
|
||||
|
||||
func validateFTPPathPrefix(prefix string) error {
|
||||
if strings.ContainsAny(prefix, "\x00\r\n\\") {
|
||||
return fmt.Errorf("FTP/SFTP path contains an invalid character")
|
||||
}
|
||||
prefix = strings.TrimSpace(prefix)
|
||||
prefix = strings.TrimPrefix(prefix, "~")
|
||||
prefix = strings.TrimLeft(prefix, "/")
|
||||
for _, segment := range strings.Split(prefix, "/") {
|
||||
if segment == ".." {
|
||||
return fmt.Errorf("FTP/SFTP path must stay inside the login directory")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizedFTPProtocol(protocol string) string {
|
||||
if protocol == domain.FTPProtocolSFTP {
|
||||
return domain.FTPProtocolSFTP
|
||||
}
|
||||
return domain.FTPProtocolFTP
|
||||
}
|
||||
|
||||
func ftpShareText(protocol, rootDirectory, relPath string) string {
|
||||
rootDirectory = strings.TrimSpace(rootDirectory)
|
||||
if rootDirectory == "" {
|
||||
if protocol == domain.FTPProtocolSFTP {
|
||||
rootDirectory = "~/"
|
||||
} else {
|
||||
rootDirectory = "/"
|
||||
}
|
||||
}
|
||||
return strings.TrimRight(rootDirectory, "/") + "/" + strings.TrimLeft(relPath, "/")
|
||||
}
|
||||
|
||||
func (s *CaptureAndFTPService) notifyFailure(reason string) {
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifyFailure(reason)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
type fakeFTPUploader struct {
|
||||
path string
|
||||
data []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeFTPUploader) Upload(_ context.Context, remoteRelPath string, data []byte) error {
|
||||
f.path = remoteRelPath
|
||||
f.data = append([]byte(nil), data...)
|
||||
return f.err
|
||||
}
|
||||
|
||||
func TestCaptureAndFTPServiceUploadsAndCopiesFTPPath(t *testing.T) {
|
||||
uploader := &fakeFTPUploader{}
|
||||
clip := &fakeClipboard{}
|
||||
notifier := &fakeNotifier{}
|
||||
svc := &CaptureAndFTPService{
|
||||
Uploader: uploader,
|
||||
Clipboard: clip,
|
||||
Notifier: notifier,
|
||||
Cfg: domain.FTPConfig{
|
||||
Protocol: domain.FTPProtocolFTP,
|
||||
PathPrefix: "snapgo/",
|
||||
},
|
||||
}
|
||||
|
||||
if err := svc.ExecuteWithBytes(context.Background(), []byte("png")); err != nil {
|
||||
t.Fatalf("upload FTP screenshot: %v", err)
|
||||
}
|
||||
if string(uploader.data) != "png" {
|
||||
t.Fatalf("expected PNG bytes, got %q", string(uploader.data))
|
||||
}
|
||||
if !strings.HasPrefix(uploader.path, "snapgo/") || !strings.HasSuffix(uploader.path, ".png") {
|
||||
t.Fatalf("unexpected remote path %q", uploader.path)
|
||||
}
|
||||
if clip.text != "/"+uploader.path {
|
||||
t.Fatalf("expected FTP root path copied, got %q", clip.text)
|
||||
}
|
||||
if notifier.success != clip.text {
|
||||
t.Fatalf("expected success notification %q, got %q", clip.text, notifier.success)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureAndFTPServiceCopiesConfiguredRootPath(t *testing.T) {
|
||||
uploader := &fakeFTPUploader{}
|
||||
clip := &fakeClipboard{}
|
||||
svc := &CaptureAndFTPService{
|
||||
Uploader: uploader,
|
||||
Clipboard: clip,
|
||||
Cfg: domain.FTPConfig{
|
||||
Protocol: domain.FTPProtocolSFTP,
|
||||
RootDirectory: "~/ftp/",
|
||||
PathPrefix: "images",
|
||||
},
|
||||
}
|
||||
|
||||
if err := svc.ExecuteWithBytes(context.Background(), []byte("png")); err != nil {
|
||||
t.Fatalf("upload SFTP screenshot: %v", err)
|
||||
}
|
||||
if clip.text != "~/ftp/"+uploader.path {
|
||||
t.Fatalf("expected configured SFTP root path copied, got %q", clip.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFTPShareTextJoinsConfiguredRootAndRemoteDirectory(t *testing.T) {
|
||||
const relPath = "snapgo/2026/07/20260713-110413-18lnbx.png"
|
||||
const want = "~/ftp/snapgo/2026/07/20260713-110413-18lnbx.png"
|
||||
if got := ftpShareText(domain.FTPProtocolSFTP, "~/ftp/", relPath); got != want {
|
||||
t.Fatalf("ftpShareText() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFTPShareTextUsesProtocolDefaultWhenRootDirectoryIsEmpty(t *testing.T) {
|
||||
const relPath = "snapgo/2026/07/image.png"
|
||||
tests := []struct {
|
||||
name string
|
||||
protocol string
|
||||
want string
|
||||
}{
|
||||
{name: "FTP", protocol: domain.FTPProtocolFTP, want: "/" + relPath},
|
||||
{name: "SFTP", protocol: domain.FTPProtocolSFTP, want: "~/" + relPath},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := ftpShareText(tt.protocol, "", relPath); got != tt.want {
|
||||
t.Fatalf("ftpShareText() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureAndFTPServiceRejectsTraversalBeforeUpload(t *testing.T) {
|
||||
uploader := &fakeFTPUploader{}
|
||||
notifier := &fakeNotifier{}
|
||||
svc := &CaptureAndFTPService{
|
||||
Uploader: uploader,
|
||||
Notifier: notifier,
|
||||
Cfg: domain.FTPConfig{
|
||||
Protocol: domain.FTPProtocolSFTP,
|
||||
PathPrefix: "../../outside",
|
||||
},
|
||||
}
|
||||
|
||||
err := svc.ExecuteWithBytes(context.Background(), []byte("png"))
|
||||
if err == nil {
|
||||
t.Fatal("expected traversal prefix to fail")
|
||||
}
|
||||
if uploader.path != "" {
|
||||
t.Fatalf("uploader should not run, got path %q", uploader.path)
|
||||
}
|
||||
if notifier.failure == "" {
|
||||
t.Fatal("expected failure notification")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureAndFTPServiceSurfacesUploadFailure(t *testing.T) {
|
||||
want := errors.New("server unavailable")
|
||||
uploader := &fakeFTPUploader{err: want}
|
||||
clip := &fakeClipboard{}
|
||||
notifier := &fakeNotifier{}
|
||||
svc := &CaptureAndFTPService{
|
||||
Uploader: uploader,
|
||||
Clipboard: clip,
|
||||
Notifier: notifier,
|
||||
Cfg: domain.FTPConfig{Protocol: domain.FTPProtocolFTP},
|
||||
}
|
||||
|
||||
err := svc.ExecuteWithBytes(context.Background(), []byte("png"))
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("expected %v, got %v", want, err)
|
||||
}
|
||||
if clip.text != "" {
|
||||
t.Fatalf("clipboard should remain empty, got %q", clip.text)
|
||||
}
|
||||
if !strings.Contains(notifier.failure, "server unavailable") {
|
||||
t.Fatalf("unexpected failure notification %q", notifier.failure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildFTPRemotePathNormalizesLoginRootMarkers(t *testing.T) {
|
||||
remotePath, err := buildFTPRemotePath(" ~////snapgo/ ")
|
||||
if err != nil {
|
||||
t.Fatalf("build remote path: %v", err)
|
||||
}
|
||||
if strings.HasPrefix(remotePath, "/") || !strings.HasPrefix(remotePath, "snapgo/") {
|
||||
t.Fatalf("expected relative snapgo path, got %q", remotePath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||
)
|
||||
|
||||
// OCRRecognizer describes a provider capable of extracting text from a PNG
|
||||
// screenshot.
|
||||
type OCRRecognizer interface {
|
||||
RecognizeText(ctx context.Context, pngBytes []byte) (string, error)
|
||||
}
|
||||
|
||||
// CaptureOCRService wires screenshot bytes -> OCR provider -> clipboard. It
|
||||
// leaves progress reporting to the caller so native and web overlays can share
|
||||
// the same status HUD.
|
||||
type CaptureOCRService struct {
|
||||
Recognizer OCRRecognizer
|
||||
Clipboard clipboard.Writer
|
||||
}
|
||||
|
||||
// Recognize asks the configured OCR provider to extract text from the PNG.
|
||||
func (s *CaptureOCRService) Recognize(ctx context.Context, pngBytes []byte) (string, error) {
|
||||
if s.Recognizer == nil {
|
||||
return "", fmt.Errorf("ocr is not configured")
|
||||
}
|
||||
if len(pngBytes) == 0 {
|
||||
return "", fmt.Errorf("empty screenshot")
|
||||
}
|
||||
text, err := s.Recognizer.RecognizeText(ctx, pngBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return "", fmt.Errorf("ocr result is empty")
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// CopyText writes the extracted text to the clipboard.
|
||||
func (s *CaptureOCRService) CopyText(_ context.Context, text string) error {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return fmt.Errorf("empty ocr text")
|
||||
}
|
||||
if s.Clipboard == nil {
|
||||
return fmt.Errorf("clipboard is not configured")
|
||||
}
|
||||
if err := s.Clipboard.WriteText(text); err != nil {
|
||||
return fmt.Errorf("clipboard write failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeOCRRecognizer struct {
|
||||
image []byte
|
||||
text string
|
||||
}
|
||||
|
||||
func (f *fakeOCRRecognizer) RecognizeText(_ context.Context, pngBytes []byte) (string, error) {
|
||||
f.image = append([]byte(nil), pngBytes...)
|
||||
if f.text == "" {
|
||||
return "extracted text", nil
|
||||
}
|
||||
return f.text, nil
|
||||
}
|
||||
|
||||
func TestCaptureOCRServiceRecognizesAndCopies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
recognizer := &fakeOCRRecognizer{}
|
||||
clip := &fakeClipboard{}
|
||||
svc := &CaptureOCRService{Recognizer: recognizer, Clipboard: clip}
|
||||
|
||||
text, err := svc.Recognize(ctx, []byte("png"))
|
||||
if err != nil {
|
||||
t.Fatalf("recognize: %v", err)
|
||||
}
|
||||
if string(recognizer.image) != "png" {
|
||||
t.Fatalf("expected screenshot bytes forwarded, got %q", string(recognizer.image))
|
||||
}
|
||||
if text != "extracted text" {
|
||||
t.Fatalf("expected extracted text, got %q", text)
|
||||
}
|
||||
if err := svc.CopyText(ctx, text); err != nil {
|
||||
t.Fatalf("copy text: %v", err)
|
||||
}
|
||||
if clip.text != "extracted text" {
|
||||
t.Fatalf("expected ocr text copied, got %q", clip.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureOCRServiceRejectsEmptyResult(t *testing.T) {
|
||||
svc := &CaptureOCRService{Recognizer: &fakeOCRRecognizer{text: " \n "}}
|
||||
if _, err := svc.Recognize(context.Background(), []byte("png")); err == nil {
|
||||
t.Fatalf("expected empty OCR result to fail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// capture_ssh.go — application-level service that uploads a screenshot to
|
||||
// a remote host via SSH/SCP.
|
||||
//
|
||||
// Design rationale:
|
||||
// - Mirrors CaptureAndUploadService so the UI layer can call a single
|
||||
// well-defined entrypoint per destination kind.
|
||||
// - Depends on a small Uploader interface rather than the concrete SSH
|
||||
// adapter so the service is unit-testable without a real SSH server.
|
||||
// - The remote object key is generated through the same date-based
|
||||
// scheme used for S3 uploads (see buildObjectKey in capture_upload.go)
|
||||
// so users get a consistent layout regardless of destination.
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||
)
|
||||
|
||||
// sshSvcLog returns an application-layer SSH logger bound to the CURRENT
|
||||
// default handler.
|
||||
//
|
||||
// 为什么是函数而非包级 slog.With 变量: 包级变量会在 main() 调用
|
||||
// logging.Init() 之前被初始化, 捕获到 bootstrap handler, 之后 SetDefault
|
||||
// 切换 handler 时会产生双前缀日志. 惰性读取 slog.Default() 可避免该问题.
|
||||
func sshSvcLog() *slog.Logger { return slog.Default().With("component", "application.ssh") }
|
||||
|
||||
// SSHUploader abstracts the SSH/SCP adapter so this layer does not depend
|
||||
// on golang.org/x/crypto/ssh directly. The infrastructure package wires a
|
||||
// concrete implementation through a small adapter below.
|
||||
type SSHUploader interface {
|
||||
// Upload writes `data` to remoteRelPath (relative to the user's $HOME)
|
||||
// with the given file mode and returns once the remote has acknowledged
|
||||
// the transfer.
|
||||
Upload(ctx context.Context, remoteRelPath string, data []byte, mode os.FileMode) error
|
||||
}
|
||||
|
||||
// CaptureAndSSHService wires capture-bytes → SCP → clipboard → notify.
|
||||
type CaptureAndSSHService struct {
|
||||
Uploader SSHUploader
|
||||
Clipboard clipboard.Writer
|
||||
Notifier Notifier
|
||||
|
||||
// Cfg is the active SSH configuration; we keep a copy on the service
|
||||
// so PathPrefix and PublicURLBase are explicitly part of the contract
|
||||
// rather than reaching into a shared global.
|
||||
Cfg domain.SSHConfig
|
||||
}
|
||||
|
||||
// ExecuteWithBytes uploads previously-captured PNG bytes via SCP and copies
|
||||
// either a public URL (if configured) or the remote-relative path to the
|
||||
// clipboard. Either is useful: a URL for sharing, a path so the user can
|
||||
// inspect / scp it manually.
|
||||
func (s *CaptureAndSSHService) ExecuteWithBytes(ctx context.Context, pngBytes []byte) error {
|
||||
if s.Uploader == nil {
|
||||
sshSvcLog().Warn("ExecuteWithBytes aborted: uploader nil")
|
||||
s.notifyFailure("SSH not configured")
|
||||
return fmt.Errorf("ssh uploader is nil")
|
||||
}
|
||||
if len(pngBytes) == 0 {
|
||||
sshSvcLog().Warn("ExecuteWithBytes aborted: empty screenshot")
|
||||
s.notifyFailure("empty screenshot")
|
||||
return fmt.Errorf("empty screenshot")
|
||||
}
|
||||
relPath := buildRemoteRelPath(s.Cfg.PathPrefix)
|
||||
sshSvcLog().Info("save-remote pipeline start",
|
||||
"host", s.Cfg.Host, "user", s.Cfg.User, "port", s.Cfg.Port,
|
||||
"size", len(pngBytes), "remote_path", relPath,
|
||||
"strict_host_key", s.Cfg.StrictHostKey)
|
||||
start := time.Now()
|
||||
if err := s.Uploader.Upload(ctx, relPath, pngBytes, 0o644); err != nil {
|
||||
sshSvcLog().Error("save-remote upload failed",
|
||||
"remote_path", relPath, "elapsed", time.Since(start), "err", err)
|
||||
s.notifyFailure("ssh upload failed: " + err.Error())
|
||||
return err
|
||||
}
|
||||
sshSvcLog().Info("save-remote upload ok",
|
||||
"remote_path", relPath, "elapsed", time.Since(start))
|
||||
|
||||
clipText := remoteShareText(relPath)
|
||||
if s.Clipboard != nil {
|
||||
if err := s.Clipboard.WriteText(clipText); err != nil {
|
||||
sshSvcLog().Error("save-remote clipboard write failed", "err", err)
|
||||
s.notifyFailure("clipboard write failed: " + err.Error())
|
||||
return err
|
||||
}
|
||||
sshSvcLog().Debug("save-remote clipboard write ok", "text", clipText)
|
||||
}
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifySuccess(clipText)
|
||||
}
|
||||
sshSvcLog().Info("save-remote pipeline done",
|
||||
"remote_path", relPath, "total_elapsed", time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
// remoteShareText returns the clipboard string for an SSH upload.
|
||||
//
|
||||
// 设计理由: 用户反馈只需要远端机器上的路径 (方便登录后直接定位文件),
|
||||
// 不需要 user@host 前缀, 也不再支持 Public URL Base. 这里统一返回
|
||||
// "~/<relPath>", 即相对远端 $HOME 的可读路径.
|
||||
func remoteShareText(relPath string) string {
|
||||
return "~/" + relPath
|
||||
}
|
||||
|
||||
// buildRemoteRelPath produces the remote-relative target path with the
|
||||
// same date-grouped layout used by the S3 pipeline.
|
||||
func buildRemoteRelPath(prefix string) string {
|
||||
prefix = strings.TrimSpace(prefix)
|
||||
prefix = strings.TrimPrefix(prefix, "~")
|
||||
prefix = strings.TrimPrefix(prefix, "/")
|
||||
if prefix != "" && !strings.HasSuffix(prefix, "/") {
|
||||
prefix += "/"
|
||||
}
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("%s%s/%s/%s-%s.png",
|
||||
prefix,
|
||||
now.Format("2006"),
|
||||
now.Format("01"),
|
||||
now.Format("20060102-150405"),
|
||||
randomSuffix(6),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *CaptureAndSSHService) notifyFailure(reason string) {
|
||||
if s.Notifier != nil {
|
||||
s.Notifier.NotifyFailure(reason)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||
)
|
||||
|
||||
// VisionSummarizer describes a multimodal model capable of reading an image
|
||||
// reference (either a public https URL or an inline base64 data URL) and
|
||||
// returning a textual summary.
|
||||
type VisionSummarizer interface {
|
||||
SummarizeImage(ctx context.Context, prompt string, imageURL string) (string, error)
|
||||
}
|
||||
|
||||
// ObjectDeleter is an optional capability an OSSProvider may implement so the
|
||||
// summary pipeline can delete the temporary screenshot it uploaded purely so a
|
||||
// remote model could fetch it. It is kept separate from domain.OSSProvider to
|
||||
// avoid forcing every provider (or test fake) to implement deletion.
|
||||
type ObjectDeleter interface {
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
// CaptureSummaryService wires screenshot bytes -> multimodal LLM summary ->
|
||||
// clipboard. It prefers sending the image inline as a base64 data URL and only
|
||||
// falls back to an S3 upload (public URL) when the payload exceeds the
|
||||
// provider's inline size limit. It intentionally does not notify UI state
|
||||
// itself: the caller emits fine-grained "uploading / recognizing / done"
|
||||
// progress.
|
||||
type CaptureSummaryService struct {
|
||||
Provider domain.OSSProvider
|
||||
Summarizer VisionSummarizer
|
||||
Clipboard clipboard.Writer
|
||||
Prompt string
|
||||
PathPrefix string
|
||||
// MaxInlineBytes caps the PNG size eligible for inline base64. Payloads
|
||||
// larger than this must go through S3. A value <= 0 disables the inline
|
||||
// path entirely (always upload).
|
||||
MaxInlineBytes int
|
||||
// HTTPClient is used for the public-URL reachability probe. Defaults to a
|
||||
// short-timeout client when nil.
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
// CanInline reports whether the screenshot is small enough to be embedded
|
||||
// directly in the request as a base64 data URL.
|
||||
func (s *CaptureSummaryService) CanInline(pngBytes []byte) bool {
|
||||
return s.MaxInlineBytes > 0 && len(pngBytes) <= s.MaxInlineBytes
|
||||
}
|
||||
|
||||
// InlineDataURL encodes the PNG as an RFC 2397 data URL suitable for the
|
||||
// image_url field of an OpenAI-compatible request.
|
||||
func (s *CaptureSummaryService) InlineDataURL(pngBytes []byte) string {
|
||||
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngBytes)
|
||||
}
|
||||
|
||||
// UploadImage uploads the screenshot and returns the public URL visible to
|
||||
// the multimodal provider. Used only when the image is too large to inline.
|
||||
func (s *CaptureSummaryService) UploadImage(ctx context.Context, pngBytes []byte) (*domain.UploadResult, error) {
|
||||
if s.Provider == nil {
|
||||
return nil, fmt.Errorf("s3 is not configured")
|
||||
}
|
||||
if len(pngBytes) == 0 {
|
||||
return nil, fmt.Errorf("empty screenshot")
|
||||
}
|
||||
key := buildObjectKey(s.PathPrefix)
|
||||
start := time.Now()
|
||||
url, err := s.Provider.Upload(ctx, key, pngBytes, "image/png")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 put object: %w", err)
|
||||
}
|
||||
return &domain.UploadResult{
|
||||
URL: url,
|
||||
Key: key,
|
||||
Provider: s.Provider.Name(),
|
||||
Elapsed: time.Since(start),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// EnsureReachable verifies the public URL can actually be fetched, so we can
|
||||
// surface a clear "link not reachable" message instead of an opaque provider
|
||||
// error when the bucket is private or fronted by an inaccessible CDN.
|
||||
func (s *CaptureSummaryService) EnsureReachable(ctx context.Context, imageURL string) error {
|
||||
client := s.HTTPClient
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 10 * time.Second}
|
||||
}
|
||||
probe := func(method string) (int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, method, imageURL, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode, nil
|
||||
}
|
||||
status, err := probe(http.MethodHead)
|
||||
// Some S3-compatible endpoints reject HEAD; retry with GET before failing.
|
||||
if err != nil || status == http.StatusMethodNotAllowed || status == http.StatusForbidden {
|
||||
if s, gerr := probe(http.MethodGet); gerr == nil {
|
||||
status, err = s, nil
|
||||
} else if err == nil {
|
||||
err = gerr
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("图片链接不可达(模型无法读取上传的截图):%w", err)
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
return fmt.Errorf("图片链接不可达:HTTP %d,请确认对象存储 bucket 公网可读或已正确配置 PublicURLBase", status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUploaded removes the temporary object from S3 if the provider supports
|
||||
// deletion. It is best-effort: a nil return means either success or that the
|
||||
// provider cannot delete.
|
||||
func (s *CaptureSummaryService) DeleteUploaded(ctx context.Context, key string) error {
|
||||
if key == "" {
|
||||
return nil
|
||||
}
|
||||
deleter, ok := s.Provider.(ObjectDeleter)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return deleter.Delete(ctx, key)
|
||||
}
|
||||
|
||||
// Summarize asks the configured model to summarize the image reference, which
|
||||
// may be a public URL or an inline base64 data URL.
|
||||
func (s *CaptureSummaryService) Summarize(ctx context.Context, imageURL string) (string, error) {
|
||||
if s.Summarizer == nil {
|
||||
return "", fmt.Errorf("llm is not configured")
|
||||
}
|
||||
return s.Summarizer.SummarizeImage(ctx, s.Prompt, imageURL)
|
||||
}
|
||||
|
||||
// CopySummary writes the final summary text to the clipboard.
|
||||
func (s *CaptureSummaryService) CopySummary(_ context.Context, summary string) error {
|
||||
if summary == "" {
|
||||
return fmt.Errorf("empty summary")
|
||||
}
|
||||
if s.Clipboard == nil {
|
||||
return fmt.Errorf("clipboard is not configured")
|
||||
}
|
||||
if err := s.Clipboard.WriteText(summary); err != nil {
|
||||
return fmt.Errorf("clipboard write failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeOSSProvider struct {
|
||||
key string
|
||||
data []byte
|
||||
contentType string
|
||||
url string
|
||||
deletedKey string
|
||||
}
|
||||
|
||||
func (f *fakeOSSProvider) Upload(_ context.Context, key string, data []byte, contentType string) (string, error) {
|
||||
f.key = key
|
||||
f.data = append([]byte(nil), data...)
|
||||
f.contentType = contentType
|
||||
if f.url == "" {
|
||||
return "https://cdn.example.com/" + key, nil
|
||||
}
|
||||
return f.url, nil
|
||||
}
|
||||
|
||||
func (f *fakeOSSProvider) Name() string { return "fake" }
|
||||
|
||||
func (f *fakeOSSProvider) Delete(_ context.Context, key string) error {
|
||||
f.deletedKey = key
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeSummarizer struct {
|
||||
prompt string
|
||||
url string
|
||||
text string
|
||||
}
|
||||
|
||||
func (f *fakeSummarizer) SummarizeImage(_ context.Context, prompt string, imageURL string) (string, error) {
|
||||
f.prompt = prompt
|
||||
f.url = imageURL
|
||||
if f.text == "" {
|
||||
return "summary text", nil
|
||||
}
|
||||
return f.text, nil
|
||||
}
|
||||
|
||||
func TestCaptureSummaryServiceUploadsSummarizesAndCopies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := &fakeOSSProvider{}
|
||||
summarizer := &fakeSummarizer{}
|
||||
clip := &fakeClipboard{}
|
||||
svc := &CaptureSummaryService{
|
||||
Provider: provider,
|
||||
Summarizer: summarizer,
|
||||
Clipboard: clip,
|
||||
Prompt: "describe screenshot",
|
||||
PathPrefix: "snapgo/",
|
||||
}
|
||||
|
||||
uploaded, err := svc.UploadImage(ctx, []byte("png"))
|
||||
if err != nil {
|
||||
t.Fatalf("upload image: %v", err)
|
||||
}
|
||||
if provider.contentType != "image/png" {
|
||||
t.Fatalf("expected image/png content type, got %q", provider.contentType)
|
||||
}
|
||||
if string(provider.data) != "png" {
|
||||
t.Fatalf("expected uploaded png bytes, got %q", string(provider.data))
|
||||
}
|
||||
|
||||
summary, err := svc.Summarize(ctx, uploaded.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("summarize: %v", err)
|
||||
}
|
||||
if summarizer.prompt != "describe screenshot" {
|
||||
t.Fatalf("expected prompt forwarded, got %q", summarizer.prompt)
|
||||
}
|
||||
if summarizer.url != uploaded.URL {
|
||||
t.Fatalf("expected uploaded url forwarded, got %q", summarizer.url)
|
||||
}
|
||||
if summary != "summary text" {
|
||||
t.Fatalf("expected summary text, got %q", summary)
|
||||
}
|
||||
|
||||
if err := svc.CopySummary(ctx, summary); err != nil {
|
||||
t.Fatalf("copy summary: %v", err)
|
||||
}
|
||||
if clip.text != "summary text" {
|
||||
t.Fatalf("expected summary copied, got %q", clip.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureSummaryServiceInlineDataURL(t *testing.T) {
|
||||
svc := &CaptureSummaryService{MaxInlineBytes: 10}
|
||||
|
||||
if !svc.CanInline([]byte("small")) {
|
||||
t.Fatalf("expected 5-byte payload to be inlinable under 10-byte cap")
|
||||
}
|
||||
if svc.CanInline([]byte("this is definitely too big")) {
|
||||
t.Fatalf("expected oversized payload to be rejected for inlining")
|
||||
}
|
||||
|
||||
url := svc.InlineDataURL([]byte("png"))
|
||||
if !strings.HasPrefix(url, "data:image/png;base64,") {
|
||||
t.Fatalf("expected base64 data URL prefix, got %q", url)
|
||||
}
|
||||
if strings.Contains(url, "https://") {
|
||||
t.Fatalf("inline URL must not be a remote URL, got %q", url)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureSummaryServiceDeleteUploadedUsesDeleter(t *testing.T) {
|
||||
provider := &fakeOSSProvider{}
|
||||
svc := &CaptureSummaryService{Provider: provider}
|
||||
|
||||
if err := svc.DeleteUploaded(context.Background(), "snapgo/a.png"); err != nil {
|
||||
t.Fatalf("delete uploaded: %v", err)
|
||||
}
|
||||
if provider.deletedKey != "snapgo/a.png" {
|
||||
t.Fatalf("expected object deleted, got %q", provider.deletedKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureSummaryServiceDeleteUploadedNoDeleterIsNoop(t *testing.T) {
|
||||
// A provider without Delete must not error when cleanup is requested.
|
||||
svc := &CaptureSummaryService{Provider: nonDeletingProvider{}}
|
||||
if err := svc.DeleteUploaded(context.Background(), "snapgo/a.png"); err != nil {
|
||||
t.Fatalf("expected no-op delete, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type nonDeletingProvider struct{}
|
||||
|
||||
func (nonDeletingProvider) Upload(_ context.Context, _ string, _ []byte, _ string) (string, error) {
|
||||
return "https://cdn.example.com/x.png", nil
|
||||
}
|
||||
|
||||
func (nonDeletingProvider) Name() string { return "no-delete" }
|
||||
@@ -0,0 +1,147 @@
|
||||
// Package application contains use-case orchestrators that the presentation
|
||||
// layer (Wails bindings, frontend) calls into.
|
||||
//
|
||||
// Design rationale:
|
||||
// - Application code only depends on domain interfaces; concrete adapters
|
||||
// are injected from main.go. This keeps the layer easy to unit test and
|
||||
// future-proofs us against swapping providers.
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||
"github.com/mmmy/snapgo/internal/infrastructure/screencapture"
|
||||
)
|
||||
|
||||
// Notifier sends user-facing UI notifications. We define it as an interface
|
||||
// so the application package does not depend on the Wails runtime.
|
||||
type Notifier interface {
|
||||
NotifySuccess(url string)
|
||||
NotifyFailure(reason string)
|
||||
}
|
||||
|
||||
// CaptureAndUploadService wires capture → upload → clipboard → notify.
|
||||
type CaptureAndUploadService struct {
|
||||
Capturer screencapture.Capturer
|
||||
Provider domain.OSSProvider
|
||||
Clipboard clipboard.Writer
|
||||
Notifier Notifier
|
||||
// FallbackDir is the directory where PNGs are saved when upload fails.
|
||||
FallbackDir string
|
||||
// PathPrefix is prepended to every generated object key.
|
||||
PathPrefix string
|
||||
}
|
||||
|
||||
// Execute runs the full pipeline for a single screenshot region.
|
||||
//
|
||||
// On any failure after capture, the PNG is written to FallbackDir and the
|
||||
// local file path is copied to the clipboard so the user can still recover
|
||||
// the image manually.
|
||||
func (s *CaptureAndUploadService) Execute(ctx context.Context, rect image.Rectangle) (*domain.UploadResult, error) {
|
||||
if s.Provider == nil {
|
||||
s.Notifier.NotifyFailure("OSS not configured")
|
||||
return nil, fmt.Errorf("oss provider is nil")
|
||||
}
|
||||
|
||||
pngBytes, err := s.Capturer.CaptureRegion(rect)
|
||||
if err != nil {
|
||||
s.Notifier.NotifyFailure("capture failed: " + err.Error())
|
||||
return nil, err
|
||||
}
|
||||
return s.uploadAndCopy(ctx, pngBytes)
|
||||
}
|
||||
|
||||
// ExecuteWithBytes runs only the upload-clipboard-notify portion of the
|
||||
// pipeline using PNG bytes that have already been produced by an upstream
|
||||
// capture step (e.g. macOS's interactive picker). Splitting this out keeps
|
||||
// the service free of any knowledge about how the pixels were obtained.
|
||||
func (s *CaptureAndUploadService) ExecuteWithBytes(ctx context.Context, pngBytes []byte) error {
|
||||
if s.Provider == nil {
|
||||
s.Notifier.NotifyFailure("OSS not configured")
|
||||
return fmt.Errorf("oss provider is nil")
|
||||
}
|
||||
if len(pngBytes) == 0 {
|
||||
s.Notifier.NotifyFailure("empty screenshot")
|
||||
return fmt.Errorf("empty screenshot")
|
||||
}
|
||||
_, err := s.uploadAndCopy(ctx, pngBytes)
|
||||
return err
|
||||
}
|
||||
|
||||
// uploadAndCopy is the shared tail of Execute / ExecuteWithBytes. Extracting
|
||||
// this avoids duplicating the failure-handling and clipboard logic.
|
||||
func (s *CaptureAndUploadService) uploadAndCopy(ctx context.Context, pngBytes []byte) (*domain.UploadResult, error) {
|
||||
key := buildObjectKey(s.PathPrefix)
|
||||
start := time.Now()
|
||||
url, uploadErr := s.Provider.Upload(ctx, key, pngBytes, "image/png")
|
||||
if uploadErr != nil {
|
||||
path := s.fallback(pngBytes)
|
||||
_ = s.Clipboard.WriteText(path)
|
||||
s.Notifier.NotifyFailure("upload failed: " + uploadErr.Error())
|
||||
return nil, uploadErr
|
||||
}
|
||||
|
||||
if err := s.Clipboard.WriteText(url); err != nil {
|
||||
s.Notifier.NotifyFailure("clipboard write failed: " + err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.Notifier.NotifySuccess(url)
|
||||
|
||||
return &domain.UploadResult{
|
||||
URL: url,
|
||||
Key: key,
|
||||
Provider: s.Provider.Name(),
|
||||
Elapsed: time.Since(start),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// fallback persists the PNG locally and returns the absolute path.
|
||||
// Errors are swallowed because the caller has already failed once and we
|
||||
// must not mask the original failure with a secondary error.
|
||||
func (s *CaptureAndUploadService) fallback(data []byte) string {
|
||||
if s.FallbackDir == "" {
|
||||
s.FallbackDir = filepath.Join(os.TempDir(), "SnapGo")
|
||||
}
|
||||
_ = os.MkdirAll(s.FallbackDir, 0o755)
|
||||
name := fmt.Sprintf("%s.png", time.Now().Format("20060102-150405"))
|
||||
path := filepath.Join(s.FallbackDir, name)
|
||||
_ = os.WriteFile(path, data, 0o644)
|
||||
return path
|
||||
}
|
||||
|
||||
// buildObjectKey produces a date-grouped object key with a 6-char random
|
||||
// suffix to avoid collisions when many screenshots happen in the same second.
|
||||
//
|
||||
// The template is intentionally hard-coded for the MVP; making it user-
|
||||
// configurable is left to a follow-up spec.
|
||||
func buildObjectKey(prefix string) string {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("%s%s/%s/%s-%s.png",
|
||||
prefix,
|
||||
now.Format("2006"),
|
||||
now.Format("01"),
|
||||
now.Format("20060102-150405"),
|
||||
randomSuffix(6),
|
||||
)
|
||||
}
|
||||
|
||||
const suffixAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
|
||||
// randomSuffix produces a short non-cryptographic identifier sufficient for
|
||||
// avoiding key collisions among consecutive captures.
|
||||
func randomSuffix(n int) string {
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = suffixAlphabet[rand.Intn(len(suffixAlphabet))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
// Package domain — configuration types.
|
||||
//
|
||||
// S3Config, SSHConfig, and FTPConfig are intentionally split into their own
|
||||
// structs so future providers can introduce configuration types side-by-side
|
||||
// without polluting the core domain types file.
|
||||
package domain
|
||||
|
||||
// S3Config describes the connection parameters for any S3-compatible
|
||||
// endpoint (AWS S3, MinIO, Cloudflare R2, Backblaze B2, Aliyun OSS S3
|
||||
// endpoint, etc.).
|
||||
//
|
||||
// Field design notes:
|
||||
// - PathPrefix supports object name templating so users can group screenshots
|
||||
// by date.
|
||||
// - PublicURLBase is optional to support CDN-fronted buckets; otherwise the
|
||||
// adapter falls back to "{Endpoint}/{Bucket}/{Key}" (path-style).
|
||||
// - UsePathStyle defaults to true because many self-hosted MinIO / R2
|
||||
// deployments do not support virtual-hosted-style addressing.
|
||||
type S3Config struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Region string `json:"region"`
|
||||
Bucket string `json:"bucket"`
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
PathPrefix string `json:"pathPrefix"`
|
||||
PublicURLBase string `json:"publicUrlBase"`
|
||||
UsePathStyle bool `json:"usePathStyle"`
|
||||
}
|
||||
|
||||
// SSHConfig describes the parameters required to upload a screenshot via
|
||||
// SSH/SCP to a remote host.
|
||||
//
|
||||
// Field design notes:
|
||||
// - Host / Port form the destination endpoint. Port defaults to 22 when 0.
|
||||
// - User is the SSH login name.
|
||||
// - AuthMethod selects how the connection authenticates:
|
||||
// "password" → password only, via the in-process Go SSH client.
|
||||
// "key" → ssh-agent + ~/.ssh/id_* key files (no password),
|
||||
// via the in-process Go SSH client.
|
||||
// "kerberos" → delegate to the system /usr/bin/ssh binary so the
|
||||
// existing Kerberos (GSSAPI) credential cache from
|
||||
// `kinit` is reused. Native GSSAPI is required here
|
||||
// because macOS stores tickets in an API: ccache
|
||||
// that pure-Go SSH libraries cannot read.
|
||||
// "" / "builtin" → legacy combined behaviour (password → agent → key
|
||||
// files) kept only for backward compatibility with
|
||||
// configs written before the method was split.
|
||||
// - Password is optional; when empty the implementation falls back to the
|
||||
// local SSH agent or ~/.ssh/id_* keys (i.e. the user is responsible for
|
||||
// having password-less access already configured on this machine).
|
||||
// It is ignored entirely when AuthMethod is "kerberos".
|
||||
// - PathPrefix is interpreted *relative to the remote user's $HOME*. The
|
||||
// UI presents it as "~/<PathPrefix>" so the user cannot escape the home
|
||||
// directory by writing absolute paths. Leading "/" or "~" markers are
|
||||
// stripped before the path is used.
|
||||
// - StrictHostKey toggles host key verification. When false the client
|
||||
// uses ssh.InsecureIgnoreHostKey() to mimic `scp -o StrictHostKeyChecking=no`,
|
||||
// trading some security for first-launch usability on personal LANs.
|
||||
// - KnownHostsPath defaults to ~/.ssh/known_hosts when empty and is only
|
||||
// used while StrictHostKey is true.
|
||||
// - ConnectTimeoutSecs caps the network handshake duration so a wrong
|
||||
// endpoint does not hang the capture flow indefinitely.
|
||||
type SSHConfig struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
User string `json:"user"`
|
||||
AuthMethod string `json:"authMethod"`
|
||||
Password string `json:"password"`
|
||||
PathPrefix string `json:"pathPrefix"`
|
||||
StrictHostKey bool `json:"strictHostKey"`
|
||||
KnownHostsPath string `json:"knownHostsPath"`
|
||||
ConnectTimeoutSecs int `json:"connectTimeoutSecs"`
|
||||
}
|
||||
|
||||
// FTPConfig describes a file-transfer destination reached through FTP or
|
||||
// SFTP. It is intentionally separate from SSHConfig: SFTP uses the SSH
|
||||
// transport, but it is a different file-transfer protocol from the existing
|
||||
// SCP action and has its own remote-root semantics.
|
||||
//
|
||||
// Field design notes:
|
||||
// - Protocol is either "ftp" or "sftp". Their default ports are 21 and 22.
|
||||
// - AuthMethod is used only by SFTP. "password" uses Password, while "key"
|
||||
// reuses the local ssh-agent and ~/.ssh/id_* discovery used by SSH/SCP.
|
||||
// - PathPrefix is relative to the account's login root. The application
|
||||
// rejects absolute paths and traversal segments before uploading.
|
||||
// - RootDirectory is only used to build the path copied to the clipboard.
|
||||
// Keeping it separate from PathPrefix lets the server expose a login root
|
||||
// such as "~/ftp/" while uploads still target a relative directory such
|
||||
// as "snapgo/".
|
||||
// - StrictHostKey and KnownHostsPath apply only to SFTP. Plain FTP has no
|
||||
// host-key mechanism and sends credentials and data without encryption.
|
||||
type FTPConfig struct {
|
||||
Protocol string `json:"protocol"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
User string `json:"user"`
|
||||
AuthMethod string `json:"authMethod"`
|
||||
Password string `json:"password"`
|
||||
RootDirectory string `json:"rootDirectory"`
|
||||
PathPrefix string `json:"pathPrefix"`
|
||||
StrictHostKey bool `json:"strictHostKey"`
|
||||
KnownHostsPath string `json:"knownHostsPath"`
|
||||
ConnectTimeoutSecs int `json:"connectTimeoutSecs"`
|
||||
}
|
||||
|
||||
// LLMProviderConfig stores one OpenAI-compatible multimodal chat endpoint.
|
||||
//
|
||||
// The three built-in providers (Qwen, Doubao/Ark, OpenAI-compatible) all use
|
||||
// the same request shape: chat/completions with a user content array that
|
||||
// contains text plus an image_url item. Keeping them as provider records lets
|
||||
// users switch between credentials/models without retyping every field.
|
||||
type LLMProviderConfig struct {
|
||||
Label string `json:"label"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Model string `json:"model"`
|
||||
MaxTokens int `json:"maxTokens"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
TimeoutSecs int `json:"timeoutSecs"`
|
||||
// MaxInlineBytes caps the screenshot size (in bytes of the PNG payload)
|
||||
// that may be sent inline as a base64 data URL. Above this threshold the
|
||||
// summary pipeline falls back to uploading the image to S3 and passing a
|
||||
// public URL instead, because most providers reject oversized inline
|
||||
// images. A value <= 0 means "use the built-in default".
|
||||
MaxInlineBytes int `json:"maxInlineBytes"`
|
||||
}
|
||||
|
||||
// DefaultMaxInlineBytes is the fallback inline-image cap (~4 MiB) used when a
|
||||
// provider config does not specify MaxInlineBytes. It is a conservative bound
|
||||
// that keeps a single base64 data URL within the request-size limits accepted
|
||||
// by the common OpenAI-compatible multimodal endpoints.
|
||||
const DefaultMaxInlineBytes = 4 << 20
|
||||
|
||||
// LLMConfig controls screenshot summarisation.
|
||||
type LLMConfig struct {
|
||||
ActiveProvider string `json:"activeProvider"`
|
||||
Prompt string `json:"prompt"`
|
||||
Providers map[string]LLMProviderConfig `json:"providers"`
|
||||
}
|
||||
|
||||
// OCRProviderConfig stores one cloud OCR endpoint that accepts a screenshot
|
||||
// image and returns extracted text. Aliyun and Volcengine both authenticate
|
||||
// with an AccessKey pair, but their signing schemes use slightly different
|
||||
// endpoint metadata; keeping Region/Service/Action/Version configurable lets
|
||||
// the presets track official API changes without a schema rewrite.
|
||||
type OCRProviderConfig struct {
|
||||
Label string `json:"label"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
AccessKeySecret string `json:"accessKeySecret"`
|
||||
Region string `json:"region"`
|
||||
Service string `json:"service"`
|
||||
Action string `json:"action"`
|
||||
Version string `json:"version"`
|
||||
TimeoutSecs int `json:"timeoutSecs"`
|
||||
}
|
||||
|
||||
// OCRConfig controls screenshot text extraction.
|
||||
type OCRConfig struct {
|
||||
ActiveProvider string `json:"activeProvider"`
|
||||
Providers map[string]OCRProviderConfig `json:"providers"`
|
||||
}
|
||||
|
||||
// SSH authentication method identifiers stored in SSHConfig.AuthMethod.
|
||||
const (
|
||||
// SSHAuthBuiltin is the legacy combined method (password → agent → key
|
||||
// files). Retained for backward compatibility with older config files;
|
||||
// new configs use the explicit methods below.
|
||||
SSHAuthBuiltin = "builtin"
|
||||
// SSHAuthPassword authenticates with the password field only.
|
||||
SSHAuthPassword = "password"
|
||||
// SSHAuthKey authenticates with ssh-agent / ~/.ssh/id_* key files only.
|
||||
SSHAuthKey = "key"
|
||||
// SSHAuthKerberos delegates to the system ssh binary so an existing
|
||||
// Kerberos credential cache (populated by `kinit`) is reused via GSSAPI.
|
||||
SSHAuthKerberos = "kerberos"
|
||||
)
|
||||
|
||||
// File-transfer protocol identifiers stored in FTPConfig.Protocol.
|
||||
const (
|
||||
FTPProtocolFTP = "ftp"
|
||||
FTPProtocolSFTP = "sftp"
|
||||
)
|
||||
|
||||
// Built-in LLM provider identifiers.
|
||||
const (
|
||||
LLMProviderQwen = "qwen"
|
||||
LLMProviderDoubao = "doubao"
|
||||
LLMProviderOpenAI = "openai"
|
||||
)
|
||||
|
||||
// Built-in OCR provider identifiers.
|
||||
const (
|
||||
OCRProviderAliyun = "aliyun"
|
||||
OCRProviderVolcengine = "volcengine"
|
||||
)
|
||||
|
||||
// Theme preference identifiers stored in AppConfig.Theme.
|
||||
const (
|
||||
ThemeAuto = "auto"
|
||||
ThemeLight = "light"
|
||||
ThemeDark = "dark"
|
||||
)
|
||||
|
||||
const DefaultSummaryPrompt = `你是一个截图内容总结助手。请阅读截图,并用中文输出一段适合直接粘贴到聊天、工单、Issue 或 PR 中的说明。
|
||||
|
||||
要求:
|
||||
- 先说明截图中最重要的信息和用户可能想表达的意图。
|
||||
- 如果截图包含报错、异常状态、表格、代码、界面控件或关键数字,请准确提取。
|
||||
- 如果截图内容不足以判断,不要编造;直接说明不确定点。
|
||||
- 输出尽量简洁,默认 3 到 6 条要点。
|
||||
- 不要输出 Markdown 标题,不要寒暄。`
|
||||
|
||||
// IsKerberos reports whether this config requests Kerberos/GSSAPI auth.
|
||||
func (c SSHConfig) IsKerberos() bool {
|
||||
return c.AuthMethod == SSHAuthKerberos
|
||||
}
|
||||
|
||||
// AppConfig is the top-level on-disk configuration document.
|
||||
//
|
||||
// We keep S3 / SSH / FTP nested so adding another provider later only requires
|
||||
// a new sibling field rather than a schema rewrite.
|
||||
type AppConfig struct {
|
||||
// Hotkey describes the global shortcut that triggers a capture.
|
||||
// Stored as a human-readable string like "cmd+shift+a"; parsing happens
|
||||
// in the infrastructure hotkey adapter.
|
||||
Hotkey string `json:"hotkey"`
|
||||
|
||||
// Theme controls the settings UI appearance: "auto", "light", or "dark".
|
||||
Theme string `json:"theme"`
|
||||
|
||||
// S3 holds the active S3-compatible storage configuration.
|
||||
S3 S3Config `json:"s3"`
|
||||
|
||||
// SSH holds the configuration for the optional "save to remote via scp"
|
||||
// destination triggered by the save-remote toolbar button.
|
||||
SSH SSHConfig `json:"ssh"`
|
||||
|
||||
// FTP holds the destination used by the dedicated FTP/SFTP toolbar action.
|
||||
FTP FTPConfig `json:"ftp"`
|
||||
|
||||
// LLM holds provider settings for the "copy summary" screenshot action.
|
||||
LLM LLMConfig `json:"llm"`
|
||||
|
||||
// OCR holds provider settings for the "extract text" screenshot action.
|
||||
OCR OCRConfig `json:"ocr"`
|
||||
}
|
||||
|
||||
// DefaultAppConfig returns sane zero-value defaults used on first launch.
|
||||
func DefaultAppConfig() AppConfig {
|
||||
cfg := AppConfig{
|
||||
Hotkey: "cmd+shift+a",
|
||||
Theme: ThemeAuto,
|
||||
S3: S3Config{
|
||||
PathPrefix: "snapgo/",
|
||||
UsePathStyle: true,
|
||||
},
|
||||
SSH: SSHConfig{
|
||||
Port: 22,
|
||||
PathPrefix: "snapgo/",
|
||||
ConnectTimeoutSecs: 10,
|
||||
StrictHostKey: false,
|
||||
},
|
||||
FTP: FTPConfig{
|
||||
Protocol: FTPProtocolFTP,
|
||||
Port: 21,
|
||||
AuthMethod: SSHAuthPassword,
|
||||
RootDirectory: "/",
|
||||
PathPrefix: "snapgo/",
|
||||
ConnectTimeoutSecs: 10,
|
||||
StrictHostKey: false,
|
||||
},
|
||||
LLM: DefaultLLMConfig(),
|
||||
OCR: DefaultOCRConfig(),
|
||||
}
|
||||
cfg.Normalize()
|
||||
return cfg
|
||||
}
|
||||
|
||||
// DefaultLLMConfig returns the built-in provider presets. API keys and exact
|
||||
// models remain user-editable because each provider account may expose
|
||||
// different model names / endpoint IDs.
|
||||
func DefaultLLMConfig() LLMConfig {
|
||||
return LLMConfig{
|
||||
ActiveProvider: LLMProviderOpenAI,
|
||||
Prompt: DefaultSummaryPrompt,
|
||||
Providers: map[string]LLMProviderConfig{
|
||||
LLMProviderQwen: {
|
||||
Label: "阿里千问多模态",
|
||||
BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
Model: "qwen-vl-plus",
|
||||
MaxTokens: 600,
|
||||
Temperature: 0.2,
|
||||
TimeoutSecs: 60,
|
||||
MaxInlineBytes: DefaultMaxInlineBytes,
|
||||
},
|
||||
LLMProviderDoubao: {
|
||||
Label: "火山方舟豆包多模态",
|
||||
BaseURL: "https://ark.cn-beijing.volces.com/api/v3",
|
||||
Model: "",
|
||||
MaxTokens: 600,
|
||||
Temperature: 0.2,
|
||||
TimeoutSecs: 60,
|
||||
MaxInlineBytes: DefaultMaxInlineBytes,
|
||||
},
|
||||
LLMProviderOpenAI: {
|
||||
Label: "ChatGPT / OpenAI-compatible",
|
||||
BaseURL: "https://api.openai.com/v1",
|
||||
Model: "gpt-5.5",
|
||||
MaxTokens: 600,
|
||||
Temperature: 0.2,
|
||||
TimeoutSecs: 60,
|
||||
MaxInlineBytes: DefaultMaxInlineBytes,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultOCRConfig returns the built-in OCR provider presets. Users only need
|
||||
// to fill AccessKey credentials for the common regions/actions, while advanced
|
||||
// accounts can still override endpoint metadata from the settings UI.
|
||||
func DefaultOCRConfig() OCRConfig {
|
||||
return OCRConfig{
|
||||
ActiveProvider: OCRProviderAliyun,
|
||||
Providers: map[string]OCRProviderConfig{
|
||||
OCRProviderAliyun: {
|
||||
Label: "阿里云文字识别",
|
||||
Endpoint: "https://ocr-api.cn-hangzhou.aliyuncs.com",
|
||||
Action: "RecognizeGeneral",
|
||||
Version: "2021-07-07",
|
||||
TimeoutSecs: 30,
|
||||
},
|
||||
OCRProviderVolcengine: {
|
||||
Label: "火山引擎文字识别",
|
||||
Endpoint: "https://visual.volcengineapi.com",
|
||||
Region: "cn-north-1",
|
||||
Service: "cv",
|
||||
Action: "OCRNormal",
|
||||
Version: "2020-08-26",
|
||||
TimeoutSecs: 30,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize fills defaults into configs written by older app versions while
|
||||
// preserving any user-provided provider fields.
|
||||
func (c *AppConfig) Normalize() {
|
||||
if c.Hotkey == "" {
|
||||
c.Hotkey = "cmd+shift+a"
|
||||
}
|
||||
if c.Theme != ThemeLight && c.Theme != ThemeDark && c.Theme != ThemeAuto {
|
||||
c.Theme = ThemeAuto
|
||||
}
|
||||
if c.S3.PathPrefix == "" {
|
||||
c.S3.PathPrefix = "snapgo/"
|
||||
}
|
||||
if c.SSH.Port == 0 {
|
||||
c.SSH.Port = 22
|
||||
}
|
||||
if c.SSH.PathPrefix == "" {
|
||||
c.SSH.PathPrefix = "snapgo/"
|
||||
}
|
||||
if c.SSH.ConnectTimeoutSecs == 0 {
|
||||
c.SSH.ConnectTimeoutSecs = 10
|
||||
}
|
||||
if c.FTP.Protocol != FTPProtocolFTP && c.FTP.Protocol != FTPProtocolSFTP {
|
||||
c.FTP.Protocol = FTPProtocolFTP
|
||||
}
|
||||
if c.FTP.Port == 0 {
|
||||
if c.FTP.Protocol == FTPProtocolSFTP {
|
||||
c.FTP.Port = 22
|
||||
} else {
|
||||
c.FTP.Port = 21
|
||||
}
|
||||
}
|
||||
if c.FTP.AuthMethod != SSHAuthPassword && c.FTP.AuthMethod != SSHAuthKey {
|
||||
c.FTP.AuthMethod = SSHAuthPassword
|
||||
}
|
||||
if c.FTP.RootDirectory == "" {
|
||||
if c.FTP.Protocol == FTPProtocolSFTP {
|
||||
c.FTP.RootDirectory = "~/"
|
||||
} else {
|
||||
c.FTP.RootDirectory = "/"
|
||||
}
|
||||
}
|
||||
if c.FTP.PathPrefix == "" {
|
||||
c.FTP.PathPrefix = "snapgo/"
|
||||
}
|
||||
if c.FTP.ConnectTimeoutSecs == 0 {
|
||||
c.FTP.ConnectTimeoutSecs = 10
|
||||
}
|
||||
|
||||
defaultLLM := DefaultLLMConfig()
|
||||
if c.LLM.ActiveProvider == "" {
|
||||
c.LLM.ActiveProvider = defaultLLM.ActiveProvider
|
||||
}
|
||||
if c.LLM.Prompt == "" {
|
||||
c.LLM.Prompt = defaultLLM.Prompt
|
||||
}
|
||||
if c.LLM.Providers == nil {
|
||||
c.LLM.Providers = map[string]LLMProviderConfig{}
|
||||
}
|
||||
for id, def := range defaultLLM.Providers {
|
||||
current, ok := c.LLM.Providers[id]
|
||||
if !ok {
|
||||
c.LLM.Providers[id] = def
|
||||
continue
|
||||
}
|
||||
if current.Label == "" {
|
||||
current.Label = def.Label
|
||||
}
|
||||
if current.BaseURL == "" {
|
||||
current.BaseURL = def.BaseURL
|
||||
}
|
||||
if current.Model == "" && id != LLMProviderDoubao {
|
||||
current.Model = def.Model
|
||||
}
|
||||
if current.MaxTokens == 0 {
|
||||
current.MaxTokens = def.MaxTokens
|
||||
}
|
||||
if current.Temperature < 0 {
|
||||
current.Temperature = def.Temperature
|
||||
}
|
||||
if current.TimeoutSecs == 0 {
|
||||
current.TimeoutSecs = def.TimeoutSecs
|
||||
}
|
||||
if current.MaxInlineBytes <= 0 {
|
||||
current.MaxInlineBytes = DefaultMaxInlineBytes
|
||||
}
|
||||
c.LLM.Providers[id] = current
|
||||
}
|
||||
|
||||
defaultOCR := DefaultOCRConfig()
|
||||
if c.OCR.ActiveProvider == "" {
|
||||
c.OCR.ActiveProvider = defaultOCR.ActiveProvider
|
||||
}
|
||||
if c.OCR.Providers == nil {
|
||||
c.OCR.Providers = map[string]OCRProviderConfig{}
|
||||
}
|
||||
for id, def := range defaultOCR.Providers {
|
||||
current, ok := c.OCR.Providers[id]
|
||||
if !ok {
|
||||
c.OCR.Providers[id] = def
|
||||
continue
|
||||
}
|
||||
if current.Label == "" {
|
||||
current.Label = def.Label
|
||||
}
|
||||
if current.Endpoint == "" {
|
||||
current.Endpoint = def.Endpoint
|
||||
}
|
||||
if current.Region == "" {
|
||||
current.Region = def.Region
|
||||
}
|
||||
if current.Service == "" {
|
||||
current.Service = def.Service
|
||||
}
|
||||
if current.Action == "" {
|
||||
current.Action = def.Action
|
||||
}
|
||||
if current.Version == "" {
|
||||
current.Version = def.Version
|
||||
}
|
||||
if current.TimeoutSecs == 0 {
|
||||
current.TimeoutSecs = def.TimeoutSecs
|
||||
}
|
||||
c.OCR.Providers[id] = current
|
||||
}
|
||||
}
|
||||
|
||||
// IsS3Configured reports whether the user has filled the mandatory S3 fields.
|
||||
func (c AppConfig) IsS3Configured() bool {
|
||||
return c.S3.Endpoint != "" &&
|
||||
c.S3.Bucket != "" &&
|
||||
c.S3.AccessKeyID != "" &&
|
||||
c.S3.SecretAccessKey != ""
|
||||
}
|
||||
|
||||
// IsSSHConfigured reports whether the SSH destination has the minimum
|
||||
// fields required to attempt a connection. Password is intentionally NOT
|
||||
// checked because empty password means "use agent / key auth".
|
||||
func (c AppConfig) IsSSHConfigured() bool {
|
||||
return c.SSH.Host != "" && c.SSH.User != ""
|
||||
}
|
||||
|
||||
// IsFTPConfigured reports whether the FTP/SFTP destination has the minimum
|
||||
// fields required to attempt a connection. Password is not required because
|
||||
// SFTP key authentication and password-less FTP accounts are both valid.
|
||||
func (c AppConfig) IsFTPConfigured() bool {
|
||||
return (c.FTP.Protocol == FTPProtocolFTP || c.FTP.Protocol == FTPProtocolSFTP) &&
|
||||
c.FTP.Host != "" && c.FTP.User != ""
|
||||
}
|
||||
|
||||
// ActiveLLMProvider returns the selected provider config plus a boolean
|
||||
// indicating whether the selection exists.
|
||||
func (c AppConfig) ActiveLLMProvider() (string, LLMProviderConfig, bool) {
|
||||
id := c.LLM.ActiveProvider
|
||||
if id == "" {
|
||||
id = LLMProviderOpenAI
|
||||
}
|
||||
provider, ok := c.LLM.Providers[id]
|
||||
return id, provider, ok
|
||||
}
|
||||
|
||||
// IsLLMConfigured reports whether the selected multimodal provider has the
|
||||
// fields required to make a request.
|
||||
func (c AppConfig) IsLLMConfigured() bool {
|
||||
_, provider, ok := c.ActiveLLMProvider()
|
||||
return ok && provider.BaseURL != "" && provider.APIKey != "" && provider.Model != ""
|
||||
}
|
||||
|
||||
// ActiveOCRProvider returns the selected OCR provider config plus a boolean
|
||||
// indicating whether the selection exists.
|
||||
func (c AppConfig) ActiveOCRProvider() (string, OCRProviderConfig, bool) {
|
||||
id := c.OCR.ActiveProvider
|
||||
if id == "" {
|
||||
id = OCRProviderAliyun
|
||||
}
|
||||
provider, ok := c.OCR.Providers[id]
|
||||
return id, provider, ok
|
||||
}
|
||||
|
||||
// IsOCRConfigured reports whether the selected OCR provider has the fields
|
||||
// required to sign and send a request.
|
||||
func (c AppConfig) IsOCRConfigured() bool {
|
||||
id, provider, ok := c.ActiveOCRProvider()
|
||||
if !ok ||
|
||||
provider.Endpoint == "" ||
|
||||
provider.AccessKeyID == "" ||
|
||||
provider.AccessKeySecret == "" ||
|
||||
provider.Action == "" ||
|
||||
provider.Version == "" {
|
||||
return false
|
||||
}
|
||||
if id == OCRProviderVolcengine && (provider.Region == "" || provider.Service == "") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package domain
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDefaultAppConfigIncludesFTPDefaults(t *testing.T) {
|
||||
cfg := DefaultAppConfig()
|
||||
if cfg.FTP.Protocol != FTPProtocolFTP {
|
||||
t.Fatalf("expected default FTP protocol, got %q", cfg.FTP.Protocol)
|
||||
}
|
||||
if cfg.FTP.Port != 21 {
|
||||
t.Fatalf("expected default FTP port 21, got %d", cfg.FTP.Port)
|
||||
}
|
||||
if cfg.FTP.PathPrefix != "snapgo/" {
|
||||
t.Fatalf("expected default path prefix, got %q", cfg.FTP.PathPrefix)
|
||||
}
|
||||
if cfg.FTP.RootDirectory != "/" {
|
||||
t.Fatalf("expected default root directory, got %q", cfg.FTP.RootDirectory)
|
||||
}
|
||||
if cfg.FTP.ConnectTimeoutSecs != 10 {
|
||||
t.Fatalf("expected 10 second timeout, got %d", cfg.FTP.ConnectTimeoutSecs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeUsesSFTPDefaultPort(t *testing.T) {
|
||||
cfg := AppConfig{
|
||||
FTP: FTPConfig{
|
||||
Protocol: FTPProtocolSFTP,
|
||||
},
|
||||
}
|
||||
cfg.Normalize()
|
||||
if cfg.FTP.Port != 22 {
|
||||
t.Fatalf("expected SFTP port 22, got %d", cfg.FTP.Port)
|
||||
}
|
||||
if cfg.FTP.AuthMethod != SSHAuthPassword {
|
||||
t.Fatalf("expected password auth default, got %q", cfg.FTP.AuthMethod)
|
||||
}
|
||||
if cfg.FTP.RootDirectory != "~/" {
|
||||
t.Fatalf("expected SFTP home root directory, got %q", cfg.FTP.RootDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsFTPConfiguredRequiresProtocolHostAndUser(t *testing.T) {
|
||||
cfg := DefaultAppConfig()
|
||||
if cfg.IsFTPConfigured() {
|
||||
t.Fatal("empty FTP destination should not be configured")
|
||||
}
|
||||
cfg.FTP.Host = "files.example.com"
|
||||
cfg.FTP.User = "snapgo"
|
||||
if !cfg.IsFTPConfigured() {
|
||||
t.Fatal("host and user should be enough for a normalized FTP config")
|
||||
}
|
||||
cfg.FTP.Protocol = "invalid"
|
||||
if cfg.IsFTPConfigured() {
|
||||
t.Fatal("invalid protocol should not be configured")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package domain defines the core business types of SnapGo.
|
||||
//
|
||||
// Design rationale:
|
||||
// - Keep this layer free of any third-party SDK or OS API.
|
||||
// - Higher layers (application, infrastructure) depend on these types,
|
||||
// but this package depends on nothing except the Go standard library.
|
||||
// - Encapsulating data here makes the upgrade path to multiple OSS providers
|
||||
// (Aliyun OSS, Qiniu, Tencent COS, etc.) trivial — only a new infra adapter
|
||||
// is needed.
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"image"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Screenshot represents a single captured image in PNG-encoded byte form.
|
||||
//
|
||||
// We hold the encoded bytes (not image.Image) because:
|
||||
// 1. Uploaders need a byte stream;
|
||||
// 2. Local fallback writes the same bytes to disk;
|
||||
// 3. Avoids re-encoding cost.
|
||||
type Screenshot struct {
|
||||
PNG []byte // PNG-encoded payload
|
||||
Region image.Rectangle // The captured region in virtual screen coords
|
||||
Width int // Logical width of the region
|
||||
Height int // Logical height of the region
|
||||
CreatedAt time.Time // When the capture happened
|
||||
}
|
||||
|
||||
// UploadResult describes the outcome of a successful upload.
|
||||
type UploadResult struct {
|
||||
URL string // Public URL that was copied to the clipboard
|
||||
Key string // Object key on the remote storage
|
||||
Provider string // Provider name, e.g. "s3"
|
||||
Elapsed time.Duration // How long the upload took
|
||||
}
|
||||
|
||||
// OSSProvider is the abstraction every storage adapter MUST implement.
|
||||
//
|
||||
// Why an interface:
|
||||
// - Allows the application layer to remain agnostic of the concrete SDK.
|
||||
// - Future providers (Aliyun OSS / COS / Qiniu) only need a new adapter
|
||||
// without touching the service layer.
|
||||
type OSSProvider interface {
|
||||
// Upload pushes data with the given key and content-type to remote storage,
|
||||
// returning the publicly accessible URL on success.
|
||||
Upload(ctx context.Context, key string, data []byte, contentType string) (publicURL string, err error)
|
||||
|
||||
// Name returns a stable identifier of the provider implementation
|
||||
// (used in logs, telemetry, history records).
|
||||
Name() string
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Package clipboard wraps golang.design/x/clipboard with lazy initialization.
|
||||
//
|
||||
// Why a wrapper:
|
||||
// - The upstream library requires a one-time clipboard.Init() call. Hiding it
|
||||
// here keeps the application service free of init concerns.
|
||||
// - Allows future swap to a different backend (e.g. atotto/clipboard) without
|
||||
// changing callers.
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
// Writer abstracts clipboard writes for testability.
|
||||
type Writer interface {
|
||||
WriteText(s string) error
|
||||
WriteImage(pngBytes []byte) error
|
||||
}
|
||||
|
||||
type clipWriter struct {
|
||||
once sync.Once
|
||||
initErr error
|
||||
}
|
||||
|
||||
// New returns a process-wide clipboard writer. Initialization is lazy.
|
||||
func New() Writer {
|
||||
return &clipWriter{}
|
||||
}
|
||||
|
||||
func (w *clipWriter) ensureInit() error {
|
||||
w.once.Do(func() {
|
||||
w.initErr = clipboard.Init()
|
||||
})
|
||||
return w.initErr
|
||||
}
|
||||
|
||||
// WriteText replaces the clipboard contents with the supplied UTF-8 string.
|
||||
func (w *clipWriter) WriteText(s string) error {
|
||||
if err := w.ensureInit(); err != nil {
|
||||
return fmt.Errorf("clipboard init: %w", err)
|
||||
}
|
||||
clipboard.Write(clipboard.FmtText, []byte(s))
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteImage replaces the clipboard contents with PNG-encoded image data.
|
||||
func (w *clipWriter) WriteImage(pngBytes []byte) error {
|
||||
if err := w.ensureInit(); err != nil {
|
||||
return fmt.Errorf("clipboard init: %w", err)
|
||||
}
|
||||
clipboard.Write(clipboard.FmtImage, pngBytes)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Package config provides JSON-file backed persistence for AppConfig.
|
||||
//
|
||||
// Design rationale:
|
||||
// - JSON keeps the file human-readable, which is useful while the MVP has
|
||||
// no settings UI for every option.
|
||||
// - Storage location follows os.UserConfigDir() so each platform places it
|
||||
// in the canonical spot (macOS: ~/Library/Application Support/SnapGo).
|
||||
// - File mode 0600 / dir mode 0700 mitigate accidental leakage of access
|
||||
// keys before we wire up the OS keychain (deferred to a later spec).
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// FileStore implements load/save of AppConfig on the local filesystem.
|
||||
//
|
||||
// All methods are safe for concurrent use.
|
||||
type FileStore struct {
|
||||
mu sync.RWMutex
|
||||
path string
|
||||
}
|
||||
|
||||
// NewFileStore resolves the on-disk path and creates the parent directory
|
||||
// with permissions 0700 if missing.
|
||||
func NewFileStore() (*FileStore, error) {
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve user config dir: %w", err)
|
||||
}
|
||||
appDir := filepath.Join(dir, "SnapGo")
|
||||
if err := os.MkdirAll(appDir, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("ensure config dir: %w", err)
|
||||
}
|
||||
return &FileStore{path: filepath.Join(appDir, "config.json")}, nil
|
||||
}
|
||||
|
||||
// Path exposes the absolute config file path (mainly for diagnostics / UI).
|
||||
func (s *FileStore) Path() string {
|
||||
return s.path
|
||||
}
|
||||
|
||||
// Load reads the config file. If the file does not exist OR cannot be parsed,
|
||||
// the default config is returned with a non-nil error so the caller can decide
|
||||
// whether to surface the parse failure to the user.
|
||||
func (s *FileStore) Load() (domain.AppConfig, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
cfg := domain.DefaultAppConfig()
|
||||
data, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return cfg, nil
|
||||
}
|
||||
return cfg, fmt.Errorf("read config: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||
return domain.DefaultAppConfig(), fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
cfg.Normalize()
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Save persists the supplied config atomically (write-temp + rename) so
|
||||
// crashes mid-write cannot leave a half-written file.
|
||||
func (s *FileStore) Save(cfg domain.AppConfig) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
cfg.Normalize()
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal config: %w", err)
|
||||
}
|
||||
tmp := s.path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return fmt.Errorf("write tmp config: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmp, s.path); err != nil {
|
||||
return fmt.Errorf("commit config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Package cursor exposes the current mouse pointer position in a
|
||||
// platform-agnostic way. We use it to anchor the post-capture toolbar near
|
||||
// the location where the user released the mouse — on macOS that point is
|
||||
// effectively the bottom-right corner of the screencapture selection.
|
||||
package cursor
|
||||
|
||||
// Point is a screen-space pointer location, in *logical* pixels (i.e. the
|
||||
// coordinate system Wails uses for window placement).
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//go:build darwin
|
||||
|
||||
// cursor_darwin.go reads the global cursor position via Quartz Event
|
||||
// Services. This API is preferable to NSEvent.mouseLocation for our use
|
||||
// case because it returns the pointer in flipped (top-left origin)
|
||||
// coordinates, which matches Wails / web pixel coordinates exactly.
|
||||
package cursor
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: -framework ApplicationServices
|
||||
#include <ApplicationServices/ApplicationServices.h>
|
||||
|
||||
// readCursor returns the current mouse position with origin at the
|
||||
// top-left of the primary display, in logical pixels.
|
||||
static void readCursor(double* x, double* y) {
|
||||
CGEventRef event = CGEventCreate(NULL);
|
||||
CGPoint p = CGEventGetLocation(event);
|
||||
if (event) CFRelease(event);
|
||||
*x = p.x;
|
||||
*y = p.y;
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
|
||||
// Get returns the current mouse pointer position.
|
||||
func Get() (Point, error) {
|
||||
var x, y C.double
|
||||
C.readCursor(&x, &y)
|
||||
return Point{X: int(x), Y: int(y)}, nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !darwin
|
||||
|
||||
package cursor
|
||||
|
||||
// Get is a no-op stub on non-macOS targets. The toolbar will fall back to
|
||||
// the centre of the screen on these platforms.
|
||||
func Get() (Point, error) {
|
||||
return Point{X: 0, Y: 0}, nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package display exposes platform-specific helpers for reading the
|
||||
// geometry of the primary display, in both CSS (logical) and PHYSICAL
|
||||
// pixels. The overlay flow needs both: CSS pixels to size the Wails window
|
||||
// to "fullscreen" (since Wails uses CSS-px-equivalent units), and the
|
||||
// backing scale factor to translate the user's CSS-px selection rectangle
|
||||
// into the physical-pixel rectangle of the captured PNG.
|
||||
package display
|
||||
|
||||
// Info describes the primary display.
|
||||
//
|
||||
// The struct is deliberately minimal: only the few fields the overlay flow
|
||||
// actually needs. We can grow it later without affecting callers because
|
||||
// it is returned by value.
|
||||
type Info struct {
|
||||
// CSSWidth / CSSHeight are the logical dimensions of the primary
|
||||
// display in points (i.e. what CSS / Wails uses).
|
||||
CSSWidth int
|
||||
CSSHeight int
|
||||
|
||||
// Scale is backing factor (CSS-px → device-px). 2 on Retina, 1 on
|
||||
// non-Retina. We model it as float64 to leave room for fractional
|
||||
// scales (e.g. Linux 1.25×) even though macOS effectively only ever
|
||||
// reports 1 or 2.
|
||||
Scale float64
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//go:build darwin
|
||||
|
||||
package display
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: -framework CoreGraphics -framework Foundation
|
||||
#include <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
// readPrimaryDisplay fills the four out-params with:
|
||||
// - cssW / cssH : logical (point) dimensions of the main display
|
||||
// - pxW / pxH : physical (device-pixel) dimensions
|
||||
// Using CGDisplayBounds for points and CGDisplayPixelsWide/High for pixels
|
||||
// is the canonical way to derive the backing scale on macOS without
|
||||
// bringing AppKit into the build (we do not want to link Cocoa here).
|
||||
static void readPrimaryDisplay(int* cssW, int* cssH, int* pxW, int* pxH) {
|
||||
CGDirectDisplayID id = CGMainDisplayID();
|
||||
CGRect bounds = CGDisplayBounds(id);
|
||||
*cssW = (int)bounds.size.width;
|
||||
*cssH = (int)bounds.size.height;
|
||||
*pxW = (int)CGDisplayPixelsWide(id);
|
||||
*pxH = (int)CGDisplayPixelsHigh(id);
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
|
||||
// Primary returns the geometry of the main display. The CGo call has no
|
||||
// failure path — the OS always reports a main display whenever there is at
|
||||
// least one attached, which is implied for any GUI process.
|
||||
func Primary() Info {
|
||||
var cssW, cssH, pxW, pxH C.int
|
||||
C.readPrimaryDisplay(&cssW, &cssH, &pxW, &pxH)
|
||||
scale := 1.0
|
||||
if cssW > 0 {
|
||||
scale = float64(pxW) / float64(cssW)
|
||||
}
|
||||
return Info{
|
||||
CSSWidth: int(cssW),
|
||||
CSSHeight: int(cssH),
|
||||
Scale: scale,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//go:build !darwin
|
||||
|
||||
package display
|
||||
|
||||
import "github.com/kbinani/screenshot"
|
||||
|
||||
// Primary returns the dimensions of display 0. We currently assume a 1× DPR
|
||||
// because Wails on Windows / Linux already paints in physical pixels, so
|
||||
// CSS coordinates and capture coordinates coincide. If a user ever runs at
|
||||
// non-1× we will add a platform-specific scale lookup.
|
||||
func Primary() Info {
|
||||
if screenshot.NumActiveDisplays() == 0 {
|
||||
return Info{CSSWidth: 1440, CSSHeight: 900, Scale: 1}
|
||||
}
|
||||
b := screenshot.GetDisplayBounds(0)
|
||||
return Info{
|
||||
CSSWidth: b.Dx(),
|
||||
CSSHeight: b.Dy(),
|
||||
Scale: 1,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// Package ftp provides the FTP side of SnapGo's FTP/SFTP destination.
|
||||
//
|
||||
// Design rationale:
|
||||
// - Plain FTP needs a real protocol client for PASV/EPSV handling; hand-
|
||||
// rolling those details would be fragile across common servers.
|
||||
// - SFTP is delegated to the sibling SSH adapter so authentication, agent,
|
||||
// key discovery, and known_hosts behaviour stay consistent with SCP.
|
||||
// - Both implementations upload to a temporary name and rename only after
|
||||
// the payload is complete, preventing a failed transfer from exposing a
|
||||
// partially written screenshot at the final path.
|
||||
package ftp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
ftpclient "github.com/jlaffaye/ftp"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
sshpkg "github.com/mmmy/snapgo/internal/infrastructure/ssh"
|
||||
)
|
||||
|
||||
// RemoteUploader is the common capability exposed to app.go for FTP and
|
||||
// SFTP. The application service only needs Upload; TestConnection remains an
|
||||
// infrastructure concern used by the Settings probe RPC.
|
||||
type RemoteUploader interface {
|
||||
Upload(ctx context.Context, remoteRelPath string, data []byte) error
|
||||
TestConnection(ctx context.Context) error
|
||||
}
|
||||
|
||||
// NewUploader validates cfg and returns the adapter for its selected protocol.
|
||||
func NewUploader(cfg domain.FTPConfig) (RemoteUploader, error) {
|
||||
normalized, err := normalizeConfig(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if normalized.Protocol == domain.FTPProtocolSFTP {
|
||||
return sshpkg.NewSFTPUploader(normalized), nil
|
||||
}
|
||||
return &plainUploader{cfg: normalized}, nil
|
||||
}
|
||||
|
||||
type plainUploader struct {
|
||||
cfg domain.FTPConfig
|
||||
}
|
||||
|
||||
func ftpLog() *slog.Logger { return slog.Default().With("component", "ftp") }
|
||||
|
||||
func normalizeConfig(cfg domain.FTPConfig) (domain.FTPConfig, error) {
|
||||
cfg.Protocol = strings.ToLower(strings.TrimSpace(cfg.Protocol))
|
||||
if cfg.Protocol == "" {
|
||||
cfg.Protocol = domain.FTPProtocolFTP
|
||||
}
|
||||
if cfg.Protocol != domain.FTPProtocolFTP && cfg.Protocol != domain.FTPProtocolSFTP {
|
||||
return domain.FTPConfig{}, fmt.Errorf("file transfer: protocol must be ftp or sftp")
|
||||
}
|
||||
cfg.Host = strings.TrimSpace(cfg.Host)
|
||||
cfg.User = strings.TrimSpace(cfg.User)
|
||||
if cfg.Host == "" || cfg.User == "" {
|
||||
return domain.FTPConfig{}, fmt.Errorf("file transfer: host and user are required")
|
||||
}
|
||||
if cfg.Port <= 0 {
|
||||
if cfg.Protocol == domain.FTPProtocolSFTP {
|
||||
cfg.Port = 22
|
||||
} else {
|
||||
cfg.Port = 21
|
||||
}
|
||||
}
|
||||
if cfg.Port > 65535 {
|
||||
return domain.FTPConfig{}, fmt.Errorf("file transfer: port must be between 1 and 65535")
|
||||
}
|
||||
if cfg.ConnectTimeoutSecs <= 0 {
|
||||
cfg.ConnectTimeoutSecs = 10
|
||||
}
|
||||
if cfg.AuthMethod == "" {
|
||||
cfg.AuthMethod = domain.SSHAuthPassword
|
||||
}
|
||||
if cfg.Protocol == domain.FTPProtocolSFTP &&
|
||||
cfg.AuthMethod != domain.SSHAuthPassword && cfg.AuthMethod != domain.SSHAuthKey {
|
||||
return domain.FTPConfig{}, fmt.Errorf("sftp: auth method must be password or key")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (u *plainUploader) dial(ctx context.Context) (*ftpclient.ServerConn, error) {
|
||||
timeout := time.Duration(u.cfg.ConnectTimeoutSecs) * time.Second
|
||||
addr := net.JoinHostPort(u.cfg.Host, fmt.Sprintf("%d", u.cfg.Port))
|
||||
ftpLog().Info("FTP dial start",
|
||||
"addr", addr,
|
||||
"user", u.cfg.User,
|
||||
"timeout", timeout,
|
||||
"has_password", u.cfg.Password != "")
|
||||
conn, err := ftpclient.Dial(
|
||||
addr,
|
||||
ftpclient.DialWithDialFunc(contextDialFunc(ctx, timeout)),
|
||||
ftpclient.DialWithShutTimeout(timeout),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ftp: dial %s: %w", addr, err)
|
||||
}
|
||||
if err := conn.Login(u.cfg.User, u.cfg.Password); err != nil {
|
||||
_ = conn.Quit()
|
||||
return nil, fmt.Errorf("ftp: login: %w", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// Upload stores one screenshot through plain FTP.
|
||||
func (u *plainUploader) Upload(ctx context.Context, remoteRelPath string, data []byte) error {
|
||||
cleaned, err := validateRemoteRelativePath(remoteRelPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn, err := u.dial(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Quit() }()
|
||||
|
||||
if err := enterFTPDirectory(conn, path.Dir(cleaned)); err != nil {
|
||||
return err
|
||||
}
|
||||
base := path.Base(cleaned)
|
||||
|
||||
tempName := temporaryRemoteName(base)
|
||||
removeTemp := true
|
||||
defer func() {
|
||||
if removeTemp {
|
||||
_ = conn.Delete(tempName)
|
||||
}
|
||||
}()
|
||||
|
||||
if err := conn.Stor(tempName, &contextReader{ctx: ctx, reader: bytes.NewReader(data)}); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return fmt.Errorf("ftp: store %s: %w", cleaned, err)
|
||||
}
|
||||
if err := conn.Rename(tempName, base); err != nil {
|
||||
return fmt.Errorf("ftp: commit %s: %w", cleaned, err)
|
||||
}
|
||||
removeTemp = false
|
||||
ftpLog().Info("FTP upload ok", "remote_path", cleaned, "size", len(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestConnection writes and removes a small probe under the configured path,
|
||||
// proving that credentials and directory permissions are both usable.
|
||||
func (u *plainUploader) TestConnection(ctx context.Context) error {
|
||||
probe, err := probeRemotePath(u.cfg.PathPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn, err := u.dial(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Quit() }()
|
||||
|
||||
if err := enterFTPDirectory(conn, path.Dir(probe)); err != nil {
|
||||
return err
|
||||
}
|
||||
base := path.Base(probe)
|
||||
if err := conn.Stor(base, strings.NewReader("snapgo")); err != nil {
|
||||
return fmt.Errorf("ftp probe: write: %w", err)
|
||||
}
|
||||
if err := conn.Delete(base); err != nil {
|
||||
return fmt.Errorf("ftp probe: delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// enterFTPDirectory walks to dir relative to the login root, creating missing
|
||||
// segments.
|
||||
func enterFTPDirectory(conn *ftpclient.ServerConn, dir string) error {
|
||||
dir = strings.Trim(dir, "/")
|
||||
if dir == "" || dir == "." {
|
||||
return nil
|
||||
}
|
||||
for _, segment := range strings.Split(dir, "/") {
|
||||
if err := conn.ChangeDir(segment); err == nil {
|
||||
continue
|
||||
}
|
||||
if err := conn.MakeDir(segment); err != nil {
|
||||
// A concurrent uploader may have created the directory after our
|
||||
// failed CWD. Retrying CWD distinguishes that race from a real error.
|
||||
if retryErr := conn.ChangeDir(segment); retryErr == nil {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("ftp: create directory %q: %w", segment, err)
|
||||
}
|
||||
if err := conn.ChangeDir(segment); err != nil {
|
||||
return fmt.Errorf("ftp: enter directory %q: %w", segment, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRemoteRelativePath(value string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || strings.HasPrefix(value, "/") || strings.HasPrefix(value, "~") {
|
||||
return "", fmt.Errorf("file transfer: remote path must be relative to the login directory")
|
||||
}
|
||||
if strings.ContainsAny(value, "\x00\r\n\\") {
|
||||
return "", fmt.Errorf("file transfer: remote path contains an invalid character")
|
||||
}
|
||||
for _, segment := range strings.Split(value, "/") {
|
||||
if segment == ".." {
|
||||
return "", fmt.Errorf("file transfer: remote path must not contain '..'")
|
||||
}
|
||||
}
|
||||
cleaned := path.Clean(value)
|
||||
if cleaned == "." || path.Base(cleaned) == "." || path.Base(cleaned) == ".." {
|
||||
return "", fmt.Errorf("file transfer: remote filename is empty")
|
||||
}
|
||||
return cleaned, nil
|
||||
}
|
||||
|
||||
func probeRemotePath(prefix string) (string, error) {
|
||||
prefix = strings.TrimSpace(prefix)
|
||||
prefix = strings.TrimPrefix(prefix, "~")
|
||||
prefix = strings.TrimLeft(prefix, "/")
|
||||
probe := fmt.Sprintf(".snapgo-probe-%d", time.Now().UnixNano())
|
||||
return validateRemoteRelativePath(path.Join(prefix, probe))
|
||||
}
|
||||
|
||||
func temporaryRemoteName(base string) string {
|
||||
return fmt.Sprintf(".%s.snapgo-upload-%d", base, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func contextDialFunc(ctx context.Context, timeout time.Duration) func(string, string) (net.Conn, error) {
|
||||
dialer := &net.Dialer{Timeout: timeout}
|
||||
return func(network, address string) (net.Conn, error) {
|
||||
conn, err := dialer.DialContext(ctx, network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
wrapped := &cancelableConn{
|
||||
Conn: conn,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = wrapped.Close()
|
||||
case <-wrapped.done:
|
||||
}
|
||||
}()
|
||||
return wrapped, nil
|
||||
}
|
||||
}
|
||||
|
||||
type cancelableConn struct {
|
||||
net.Conn
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (c *cancelableConn) Close() error {
|
||||
var err error
|
||||
c.once.Do(func() {
|
||||
close(c.done)
|
||||
err = c.Conn.Close()
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *contextReader) Read(p []byte) (int, error) {
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return 0, r.ctx.Err()
|
||||
default:
|
||||
return r.reader.Read(p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package ftp
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateRemoteRelativePath(t *testing.T) {
|
||||
valid, err := validateRemoteRelativePath("snapgo/2026/07/image.png")
|
||||
if err != nil {
|
||||
t.Fatalf("valid path rejected: %v", err)
|
||||
}
|
||||
if valid != "snapgo/2026/07/image.png" {
|
||||
t.Fatalf("unexpected normalized path %q", valid)
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"",
|
||||
"/absolute/image.png",
|
||||
"~/image.png",
|
||||
"../image.png",
|
||||
"snapgo/../../image.png",
|
||||
"snapgo\\image.png",
|
||||
"snapgo/image.png\nnext",
|
||||
}
|
||||
for _, value := range invalid {
|
||||
if _, err := validateRemoteRelativePath(value); err == nil {
|
||||
t.Errorf("expected %q to be rejected", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeRemotePathRejectsTraversalPrefix(t *testing.T) {
|
||||
if _, err := probeRemotePath("../../outside"); err == nil {
|
||||
t.Fatal("expected traversal prefix to fail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Package hotkey wraps golang.design/x/hotkey to provide a process-wide
|
||||
// global shortcut. The MVP only supports a single hard-coded combination
|
||||
// (Cmd+Shift+A on macOS) but the abstraction below allows the binding to
|
||||
// be replaced at runtime once we add per-platform parsing of user input.
|
||||
package hotkey
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
hk "golang.design/x/hotkey"
|
||||
)
|
||||
|
||||
// Manager owns the lifecycle of one global hotkey.
|
||||
type Manager struct {
|
||||
mu sync.Mutex
|
||||
current *hk.Hotkey
|
||||
stop chan struct{}
|
||||
}
|
||||
|
||||
// NewManager returns a fresh manager with no hotkey registered yet.
|
||||
func NewManager() *Manager { return &Manager{} }
|
||||
|
||||
// Register parses the spec (e.g. "cmd+shift+a") and binds the callback.
|
||||
// If a previous hotkey is registered, it is unregistered first so callers
|
||||
// can swap shortcuts at runtime when the user changes the setting.
|
||||
func (m *Manager) Register(spec string, onTrigger func()) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.current != nil {
|
||||
_ = m.current.Unregister()
|
||||
close(m.stop)
|
||||
m.current = nil
|
||||
m.stop = nil
|
||||
}
|
||||
|
||||
mods, key, err := parseSpec(spec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hot := hk.New(mods, key)
|
||||
if err := hot.Register(); err != nil {
|
||||
return fmt.Errorf("register hotkey %q: %w", spec, err)
|
||||
}
|
||||
|
||||
stop := make(chan struct{})
|
||||
m.current = hot
|
||||
m.stop = stop
|
||||
|
||||
// Listen on a dedicated goroutine. We never run the callback inline
|
||||
// because the keydown channel is unbuffered.
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-hot.Keydown():
|
||||
if onTrigger != nil {
|
||||
go onTrigger()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unregister releases the active hotkey, if any.
|
||||
func (m *Manager) Unregister() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.current != nil {
|
||||
_ = m.current.Unregister()
|
||||
close(m.stop)
|
||||
m.current = nil
|
||||
m.stop = nil
|
||||
}
|
||||
}
|
||||
|
||||
// parseSpec parses a "+"-separated hotkey description into (modifiers, key).
|
||||
//
|
||||
// Supported tokens (case-insensitive): cmd, command, ctrl, control,
|
||||
// option, alt, shift, plus a single letter A–Z or digit 0–9.
|
||||
//
|
||||
// We keep the parser intentionally tiny — full key mapping is out of scope
|
||||
// for the MVP.
|
||||
func parseSpec(spec string) ([]hk.Modifier, hk.Key, error) {
|
||||
parts := strings.Split(strings.ToLower(strings.TrimSpace(spec)), "+")
|
||||
if len(parts) == 0 {
|
||||
return nil, 0, fmt.Errorf("empty hotkey")
|
||||
}
|
||||
var mods []hk.Modifier
|
||||
var key hk.Key
|
||||
hasKey := false
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
switch p {
|
||||
case "cmd", "command", "meta", "super":
|
||||
mods = append(mods, modCmd())
|
||||
case "ctrl", "control":
|
||||
mods = append(mods, modCtrl())
|
||||
case "option", "alt":
|
||||
mods = append(mods, modOption())
|
||||
case "shift":
|
||||
mods = append(mods, modShift())
|
||||
default:
|
||||
k, ok := lookupKey(p)
|
||||
if !ok {
|
||||
return nil, 0, fmt.Errorf("unsupported token: %q", p)
|
||||
}
|
||||
key = k
|
||||
hasKey = true
|
||||
}
|
||||
}
|
||||
if !hasKey {
|
||||
return nil, 0, fmt.Errorf("hotkey %q is missing a key", spec)
|
||||
}
|
||||
return mods, key, nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
package hotkey
|
||||
|
||||
import hk "golang.design/x/hotkey"
|
||||
|
||||
// macOS uses ⌘ as the primary modifier; Option corresponds to Alt.
|
||||
//
|
||||
// This file is gated on cgo because golang.design/x/hotkey only exposes the
|
||||
// Mod* constants from its cgo-backed darwin implementation; with CGO_ENABLED=0
|
||||
// the package falls back to a stub that defines no constants.
|
||||
func modCmd() hk.Modifier { return hk.ModCmd }
|
||||
func modCtrl() hk.Modifier { return hk.ModCtrl }
|
||||
func modOption() hk.Modifier { return hk.ModOption }
|
||||
func modShift() hk.Modifier { return hk.ModShift }
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build linux && cgo
|
||||
|
||||
package hotkey
|
||||
|
||||
import hk "golang.design/x/hotkey"
|
||||
|
||||
// On Linux we map "cmd" to Ctrl so the same config string ("cmd+shift+a")
|
||||
// stays meaningful across platforms.
|
||||
//
|
||||
// The X11 backend exposes modifiers as Mod1..Mod5 rather than named Alt/Option
|
||||
// constants; Mod1 is the conventional Alt mask under X11, so "option"/"alt"
|
||||
// resolve to hk.Mod1. This file is gated on cgo because the constants only
|
||||
// exist in the cgo-backed linux implementation (CGO_ENABLED=0 falls back to a
|
||||
// stub with no constants).
|
||||
func modCmd() hk.Modifier { return hk.ModCtrl }
|
||||
func modCtrl() hk.Modifier { return hk.ModCtrl }
|
||||
func modOption() hk.Modifier { return hk.Mod1 }
|
||||
func modShift() hk.Modifier { return hk.ModShift }
|
||||
@@ -0,0 +1,25 @@
|
||||
//go:build !windows && !cgo
|
||||
|
||||
package hotkey
|
||||
|
||||
import hk "golang.design/x/hotkey"
|
||||
|
||||
// This file covers the configuration where golang.design/x/hotkey compiles its
|
||||
// cgo-less stub (any non-Windows platform built with CGO_ENABLED=0). In that
|
||||
// stub the package defines the Modifier/Key types but no Mod*/Key* constants,
|
||||
// and Register panics at runtime. We still provide the package-internal
|
||||
// helpers so that snapgo keeps cross-compiling (e.g. `go vet`, editor analysis,
|
||||
// or CI cross-builds) without pulling in a C toolchain.
|
||||
//
|
||||
// The returned values are inert zero modifiers and lookupKey always reports
|
||||
// "unsupported": callers on this build cannot register a real global hotkey,
|
||||
// so surfacing an "unsupported token" parse error is preferable to reaching
|
||||
// the upstream panic.
|
||||
func modCmd() hk.Modifier { return 0 }
|
||||
func modCtrl() hk.Modifier { return 0 }
|
||||
func modOption() hk.Modifier { return 0 }
|
||||
func modShift() hk.Modifier { return 0 }
|
||||
|
||||
// lookupKey has no key constants to map against in the cgo-less stub, so it
|
||||
// always reports the token as unsupported.
|
||||
func lookupKey(string) (hk.Key, bool) { return 0, false }
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build windows
|
||||
|
||||
package hotkey
|
||||
|
||||
import hk "golang.design/x/hotkey"
|
||||
|
||||
// On Windows we map "cmd" to Ctrl so the same config string ("cmd+shift+a")
|
||||
// stays meaningful across platforms; "option" is treated as Alt. The Windows
|
||||
// backend does not require cgo, hence the single-tag guard.
|
||||
func modCmd() hk.Modifier { return hk.ModCtrl }
|
||||
func modCtrl() hk.Modifier { return hk.ModCtrl }
|
||||
func modOption() hk.Modifier { return hk.ModAlt }
|
||||
func modShift() hk.Modifier { return hk.ModShift }
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build windows || cgo
|
||||
|
||||
package hotkey
|
||||
|
||||
import hk "golang.design/x/hotkey"
|
||||
|
||||
// lookupKey maps a token from the user-supplied hotkey spec to a hk.Key.
|
||||
//
|
||||
// The Key* constants only exist in the platform backends that ship them
|
||||
// (windows, or the cgo-backed darwin/linux implementations); the cgo-less stub
|
||||
// in hotkey_unsupported.go provides a fallback lookupKey for the complement.
|
||||
//
|
||||
// The map is intentionally exhaustive over the alphanumeric set so we never
|
||||
// rely on an assumption that hk.KeyA..hk.KeyZ are contiguous values — the
|
||||
// upstream package gives no such guarantee.
|
||||
func lookupKey(token string) (hk.Key, bool) {
|
||||
switch token {
|
||||
case "a":
|
||||
return hk.KeyA, true
|
||||
case "b":
|
||||
return hk.KeyB, true
|
||||
case "c":
|
||||
return hk.KeyC, true
|
||||
case "d":
|
||||
return hk.KeyD, true
|
||||
case "e":
|
||||
return hk.KeyE, true
|
||||
case "f":
|
||||
return hk.KeyF, true
|
||||
case "g":
|
||||
return hk.KeyG, true
|
||||
case "h":
|
||||
return hk.KeyH, true
|
||||
case "i":
|
||||
return hk.KeyI, true
|
||||
case "j":
|
||||
return hk.KeyJ, true
|
||||
case "k":
|
||||
return hk.KeyK, true
|
||||
case "l":
|
||||
return hk.KeyL, true
|
||||
case "m":
|
||||
return hk.KeyM, true
|
||||
case "n":
|
||||
return hk.KeyN, true
|
||||
case "o":
|
||||
return hk.KeyO, true
|
||||
case "p":
|
||||
return hk.KeyP, true
|
||||
case "q":
|
||||
return hk.KeyQ, true
|
||||
case "r":
|
||||
return hk.KeyR, true
|
||||
case "s":
|
||||
return hk.KeyS, true
|
||||
case "t":
|
||||
return hk.KeyT, true
|
||||
case "u":
|
||||
return hk.KeyU, true
|
||||
case "v":
|
||||
return hk.KeyV, true
|
||||
case "w":
|
||||
return hk.KeyW, true
|
||||
case "x":
|
||||
return hk.KeyX, true
|
||||
case "y":
|
||||
return hk.KeyY, true
|
||||
case "z":
|
||||
return hk.KeyZ, true
|
||||
case "0":
|
||||
return hk.Key0, true
|
||||
case "1":
|
||||
return hk.Key1, true
|
||||
case "2":
|
||||
return hk.Key2, true
|
||||
case "3":
|
||||
return hk.Key3, true
|
||||
case "4":
|
||||
return hk.Key4, true
|
||||
case "5":
|
||||
return hk.Key5, true
|
||||
case "6":
|
||||
return hk.Key6, true
|
||||
case "7":
|
||||
return hk.Key7, true
|
||||
case "8":
|
||||
return hk.Key8, true
|
||||
case "9":
|
||||
return hk.Key9, true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// Package llm contains multimodal LLM adapters.
|
||||
//
|
||||
// The built-in providers are intentionally implemented through the
|
||||
// OpenAI-compatible chat/completions shape. Qwen DashScope, Volcengine Ark,
|
||||
// and OpenAI-compatible gateways all accept the same "text + image_url"
|
||||
// message content pattern, so one small HTTP adapter is enough here.
|
||||
package llm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// VisionClient calls one configured multimodal chat endpoint.
|
||||
type VisionClient struct {
|
||||
providerID string
|
||||
cfg domain.LLMProviderConfig
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// NewVisionClient validates cfg and returns a reusable client.
|
||||
func NewVisionClient(providerID string, cfg domain.LLMProviderConfig) (*VisionClient, error) {
|
||||
if strings.TrimSpace(cfg.BaseURL) == "" {
|
||||
return nil, fmt.Errorf("llm base url is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.APIKey) == "" {
|
||||
return nil, fmt.Errorf("llm api key is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.Model) == "" {
|
||||
return nil, fmt.Errorf("llm model is required")
|
||||
}
|
||||
timeout := cfg.TimeoutSecs
|
||||
if timeout <= 0 {
|
||||
timeout = 60
|
||||
}
|
||||
return &VisionClient{
|
||||
providerID: providerID,
|
||||
cfg: cfg,
|
||||
httpClient: &http.Client{Timeout: time.Duration(timeout) * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SummarizeImage asks the model to summarise an image available at imageURL.
|
||||
func (c *VisionClient) SummarizeImage(ctx context.Context, prompt string, imageURL string) (string, error) {
|
||||
prompt = strings.TrimSpace(prompt)
|
||||
if prompt == "" {
|
||||
return "", fmt.Errorf("llm prompt is empty")
|
||||
}
|
||||
imageURL = strings.TrimSpace(imageURL)
|
||||
if imageURL == "" {
|
||||
return "", fmt.Errorf("image url is empty")
|
||||
}
|
||||
|
||||
body := map[string]any{
|
||||
"model": c.cfg.Model,
|
||||
"messages": []map[string]any{
|
||||
{
|
||||
"role": "user",
|
||||
"content": []map[string]any{
|
||||
{"type": "text", "text": prompt},
|
||||
{"type": "image_url", "image_url": map[string]any{"url": imageURL}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
if c.cfg.MaxTokens > 0 {
|
||||
if c.providerID == domain.LLMProviderOpenAI {
|
||||
body["max_completion_tokens"] = c.cfg.MaxTokens
|
||||
} else {
|
||||
body["max_tokens"] = c.cfg.MaxTokens
|
||||
}
|
||||
}
|
||||
if c.cfg.Temperature >= 0 {
|
||||
body["temperature"] = c.cfg.Temperature
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal llm request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, chatCompletionsURL(c.cfg.BaseURL), bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build llm request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.cfg.APIKey)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("llm status %d: %s", resp.StatusCode, compactBody(data))
|
||||
}
|
||||
|
||||
var decoded chatCompletionResponse
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
return "", fmt.Errorf("decode llm response: %w", err)
|
||||
}
|
||||
if decoded.Error != nil && decoded.Error.Message != "" {
|
||||
return "", fmt.Errorf("llm error: %s", decoded.Error.Message)
|
||||
}
|
||||
if len(decoded.Choices) == 0 {
|
||||
return "", fmt.Errorf("llm response has no choices")
|
||||
}
|
||||
text := strings.TrimSpace(contentText(decoded.Choices[0].Message.Content))
|
||||
if text == "" {
|
||||
return "", fmt.Errorf("llm response is empty")
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
func chatCompletionsURL(baseURL string) string {
|
||||
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if strings.HasSuffix(base, "/chat/completions") {
|
||||
return base
|
||||
}
|
||||
return base + "/chat/completions"
|
||||
}
|
||||
|
||||
type chatCompletionResponse struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content any `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
Code any `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func contentText(content any) string {
|
||||
switch v := content.(type) {
|
||||
case string:
|
||||
return v
|
||||
case []any:
|
||||
parts := make([]string, 0, len(v))
|
||||
for _, item := range v {
|
||||
obj, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if text, ok := obj["text"].(string); ok {
|
||||
parts = append(parts, text)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "\n")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func compactBody(data []byte) string {
|
||||
text := strings.TrimSpace(string(data))
|
||||
if text == "" {
|
||||
return "<empty body>"
|
||||
}
|
||||
if len(text) > 800 {
|
||||
return text[:800] + "..."
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
func TestVisionClientSummarizeImageUsesChatCompletionImageURL(t *testing.T) {
|
||||
var requestBody map[string]any
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path != "/v1/chat/completions" {
|
||||
t.Fatalf("expected /v1/chat/completions, got %s", r.URL.Path)
|
||||
}
|
||||
if got := r.Header.Get("Authorization"); got != "Bearer test-key" {
|
||||
t.Fatalf("unexpected auth header %q", got)
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(bytes.NewBufferString(`{"choices":[{"message":{"content":"summary ok"}}]}`)),
|
||||
}, nil
|
||||
})
|
||||
|
||||
client, err := NewVisionClient(domain.LLMProviderQwen, domain.LLMProviderConfig{
|
||||
BaseURL: "https://example.test/v1",
|
||||
APIKey: "test-key",
|
||||
Model: "qwen-vl-plus",
|
||||
MaxTokens: 321,
|
||||
Temperature: 0.2,
|
||||
TimeoutSecs: 5,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
client.httpClient.Transport = transport
|
||||
|
||||
text, err := client.SummarizeImage(context.Background(), "describe", "https://cdn.example.com/a.png")
|
||||
if err != nil {
|
||||
t.Fatalf("summarize image: %v", err)
|
||||
}
|
||||
if text != "summary ok" {
|
||||
t.Fatalf("expected response text, got %q", text)
|
||||
}
|
||||
if requestBody["model"] != "qwen-vl-plus" {
|
||||
t.Fatalf("expected model forwarded, got %#v", requestBody["model"])
|
||||
}
|
||||
if requestBody["max_tokens"] != float64(321) {
|
||||
t.Fatalf("expected max_tokens forwarded, got %#v", requestBody["max_tokens"])
|
||||
}
|
||||
|
||||
messages := requestBody["messages"].([]any)
|
||||
content := messages[0].(map[string]any)["content"].([]any)
|
||||
if content[0].(map[string]any)["text"] != "describe" {
|
||||
t.Fatalf("expected prompt content, got %#v", content[0])
|
||||
}
|
||||
image := content[1].(map[string]any)
|
||||
if image["type"] != "image_url" {
|
||||
t.Fatalf("expected image_url item, got %#v", image)
|
||||
}
|
||||
url := image["image_url"].(map[string]any)["url"]
|
||||
if url != "https://cdn.example.com/a.png" {
|
||||
t.Fatalf("expected image url forwarded, got %#v", url)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCompletionsURLAcceptsFullEndpoint(t *testing.T) {
|
||||
full := "https://example.com/v1/chat/completions"
|
||||
if got := chatCompletionsURL(full); got != full {
|
||||
t.Fatalf("expected full endpoint unchanged, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// Package logging centralises slog configuration.
|
||||
//
|
||||
// 设计动机:
|
||||
// - SnapGo 是 macOS GUI 应用, 由 Finder/open 启动时 stderr 会被重定向
|
||||
// 到 /dev/null, slog 默认 handler 写到 stderr 因此对用户不可见.
|
||||
// - 为方便排查网络 / 权限 / SCP 协议层问题, 我们将日志同时写入磁盘文件
|
||||
// 和 stderr, 让 `tail -f` 与开发期 `wails dev` 都能直接看到输出.
|
||||
// - 单独抽出包可避免 main / app 直接依赖文件 IO 细节, 也方便后续替换为
|
||||
// os_log 或集中式日志方案.
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxLogSize is the byte threshold that triggers a rotation. 5 MiB keeps
|
||||
// a useful amount of recent history while staying small enough to open
|
||||
// in any editor.
|
||||
maxLogSize = 5 * 1024 * 1024
|
||||
// maxBackups is how many rotated files to retain (snapgo.log.1,
|
||||
// snapgo.log.2). Older ones are deleted on each rotation.
|
||||
maxBackups = 2
|
||||
)
|
||||
|
||||
// teeWriter is a thin io.Writer that fans out a single slog write to many
|
||||
// underlying writers. We avoid log.MultiWriter from the std library because
|
||||
// io.MultiWriter already covers the use case without an extra dependency.
|
||||
type teeWriter struct {
|
||||
writers []io.Writer
|
||||
}
|
||||
|
||||
// Write copies p to every underlying writer. We deliberately keep going on
|
||||
// errors so a single broken writer (e.g. closed file handle) does not lose
|
||||
// output to the surviving writers; the last error wins which is sufficient
|
||||
// for a logger.
|
||||
func (t *teeWriter) Write(p []byte) (int, error) {
|
||||
var lastErr error
|
||||
for _, w := range t.writers {
|
||||
if w == nil {
|
||||
continue
|
||||
}
|
||||
if _, err := w.Write(p); err != nil {
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
return len(p), lastErr
|
||||
}
|
||||
|
||||
// Init wires slog.Default to write to both ~/Library/Logs/SnapGo/snapgo.log
|
||||
// and stderr. Returns a closer the caller (main) should defer so the file
|
||||
// handle is released on shutdown.
|
||||
//
|
||||
// 日志级别可通过环境变量 SNAPGO_LOG_LEVEL 调整: debug|info|warn|error.
|
||||
// 默认 debug 以便排查 SCP 阶段性问题, 待功能稳定后可调整为 info.
|
||||
func Init() (closer func()) {
|
||||
level := parseLevel(os.Getenv("SNAPGO_LOG_LEVEL"))
|
||||
|
||||
var fileW io.Writer
|
||||
logPath, err := defaultLogPath()
|
||||
if err == nil {
|
||||
// Size-based rotation keeps the log directory bounded; append mode is
|
||||
// preserved inside rotatingFile so prior-launch context survives.
|
||||
rf, ferr := newRotatingFile(logPath, maxLogSize, maxBackups)
|
||||
if ferr == nil {
|
||||
fileW = rf
|
||||
closer = func() { _ = rf.Close() }
|
||||
}
|
||||
}
|
||||
if closer == nil {
|
||||
closer = func() {}
|
||||
}
|
||||
|
||||
writer := &teeWriter{writers: []io.Writer{os.Stderr}}
|
||||
if fileW != nil {
|
||||
writer.writers = append(writer.writers, fileW)
|
||||
}
|
||||
|
||||
handler := slog.NewTextHandler(writer, &slog.HandlerOptions{Level: level})
|
||||
slog.SetDefault(slog.New(handler))
|
||||
|
||||
slog.Info("logging initialised",
|
||||
"level", level.String(),
|
||||
"file", logPath)
|
||||
return closer
|
||||
}
|
||||
|
||||
// rotatingFile is a size-based rotating log writer.
|
||||
//
|
||||
// 设计理由:
|
||||
// - GUI 应用长期 append 写日志, 不加限制会无限增长, 占满磁盘.
|
||||
// - 标准库不提供滚动能力, 引入 lumberjack 等第三方库又会增加依赖,
|
||||
// 而我们的需求很简单 (单文件 / 按大小 / 固定份数), 自实现成本更低.
|
||||
// - 实现策略: 每次 Write 前检查写入后是否超过 maxLogSize, 超过则先
|
||||
// rotate (snapgo.log -> snapgo.log.1 -> snapgo.log.2, 丢弃最老的),
|
||||
// 再写入新建的 snapgo.log. 用互斥锁保证并发安全 (slog handler 自身
|
||||
// 不保证对 io.Writer 的串行化).
|
||||
type rotatingFile struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
maxSize int64
|
||||
backups int
|
||||
file *os.File
|
||||
size int64
|
||||
}
|
||||
|
||||
// newRotatingFile opens (or creates, append mode) the target log file and
|
||||
// initialises the current size from the existing file so a restart does not
|
||||
// reset the rotation threshold.
|
||||
func newRotatingFile(path string, maxSize int64, backups int) (*rotatingFile, error) {
|
||||
r := &rotatingFile{path: path, maxSize: maxSize, backups: backups}
|
||||
if err := r.openExisting(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// openExisting opens the active log file in append mode and records its
|
||||
// current size.
|
||||
func (r *rotatingFile) openExisting() error {
|
||||
f, err := os.OpenFile(r.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
r.file = f
|
||||
r.size = info.Size()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write appends p, rotating first when the write would exceed maxSize.
|
||||
func (r *rotatingFile) Write(p []byte) (int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if r.size+int64(len(p)) > r.maxSize {
|
||||
if err := r.rotate(); err != nil {
|
||||
// On rotation failure we keep writing to the current file rather
|
||||
// than dropping logs; oversized-by-a-bit beats data loss.
|
||||
r.size += int64(len(p))
|
||||
n, werr := r.file.Write(p)
|
||||
if werr != nil {
|
||||
return n, werr
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
n, err := r.file.Write(p)
|
||||
r.size += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// rotate closes the current file, shifts backups (snapgo.log.1 ->
|
||||
// snapgo.log.2, dropping the oldest), renames the active file to
|
||||
// snapgo.log.1, then opens a fresh active file.
|
||||
func (r *rotatingFile) rotate() error {
|
||||
if err := r.file.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Drop the oldest backup, then shift the rest up by one index.
|
||||
oldest := fmt.Sprintf("%s.%d", r.path, r.backups)
|
||||
_ = os.Remove(oldest)
|
||||
for i := r.backups - 1; i >= 1; i-- {
|
||||
src := fmt.Sprintf("%s.%d", r.path, i)
|
||||
dst := fmt.Sprintf("%s.%d", r.path, i+1)
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
if r.backups >= 1 {
|
||||
_ = os.Rename(r.path, fmt.Sprintf("%s.1", r.path))
|
||||
}
|
||||
return r.openExisting()
|
||||
}
|
||||
|
||||
// Close releases the underlying file handle.
|
||||
func (r *rotatingFile) Close() error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.file == nil {
|
||||
return nil
|
||||
}
|
||||
return r.file.Close()
|
||||
}
|
||||
|
||||
// defaultLogPath returns ~/Library/Logs/SnapGo/snapgo.log, creating the
|
||||
// parent directory if needed. macOS users expect app logs to live there
|
||||
// (Console.app surfaces this directory under "Reports" and `open ~/Library/Logs`
|
||||
// is muscle-memory).
|
||||
func defaultLogPath() (string, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dir := filepath.Join(home, "Library", "Logs", "SnapGo")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, "snapgo.log"), nil
|
||||
}
|
||||
|
||||
// parseLevel translates a free-form string into an slog.Level. We default
|
||||
// to debug because the app currently has plenty of diagnostic logs and the
|
||||
// user-facing impact (slightly more disk IO on uploads) is negligible.
|
||||
func parseLevel(s string) slog.Level {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case "error":
|
||||
return slog.LevelError
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn
|
||||
case "info":
|
||||
return slog.LevelInfo
|
||||
case "debug", "":
|
||||
return slog.LevelDebug
|
||||
default:
|
||||
return slog.LevelDebug
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
// Package ocr contains cloud OCR adapters.
|
||||
package ocr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/application"
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// Client calls one configured OCR provider.
|
||||
type Client struct {
|
||||
providerID string
|
||||
cfg domain.OCRProviderConfig
|
||||
httpClient *http.Client
|
||||
now func() time.Time
|
||||
nonce func() string
|
||||
}
|
||||
|
||||
var _ application.OCRRecognizer = (*Client)(nil)
|
||||
|
||||
// NewClient validates cfg and returns a reusable OCR client.
|
||||
func NewClient(providerID string, cfg domain.OCRProviderConfig) (*Client, error) {
|
||||
if strings.TrimSpace(cfg.Endpoint) == "" {
|
||||
return nil, fmt.Errorf("ocr endpoint is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.AccessKeyID) == "" {
|
||||
return nil, fmt.Errorf("ocr access key id is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.AccessKeySecret) == "" {
|
||||
return nil, fmt.Errorf("ocr access key secret is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.Action) == "" {
|
||||
return nil, fmt.Errorf("ocr action is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.Version) == "" {
|
||||
return nil, fmt.Errorf("ocr version is required")
|
||||
}
|
||||
switch providerID {
|
||||
case domain.OCRProviderAliyun:
|
||||
case domain.OCRProviderVolcengine:
|
||||
if strings.TrimSpace(cfg.Region) == "" {
|
||||
return nil, fmt.Errorf("volcengine ocr region is required")
|
||||
}
|
||||
if strings.TrimSpace(cfg.Service) == "" {
|
||||
return nil, fmt.Errorf("volcengine ocr service is required")
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported ocr provider %q", providerID)
|
||||
}
|
||||
timeout := cfg.TimeoutSecs
|
||||
if timeout <= 0 {
|
||||
timeout = 30
|
||||
}
|
||||
return &Client{
|
||||
providerID: providerID,
|
||||
cfg: cfg,
|
||||
httpClient: &http.Client{Timeout: time.Duration(timeout) * time.Second},
|
||||
now: time.Now,
|
||||
nonce: randomNonce,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RecognizeText extracts visible text from a PNG screenshot.
|
||||
func (c *Client) RecognizeText(ctx context.Context, pngBytes []byte) (string, error) {
|
||||
if len(pngBytes) == 0 {
|
||||
return "", fmt.Errorf("empty screenshot")
|
||||
}
|
||||
switch c.providerID {
|
||||
case domain.OCRProviderAliyun:
|
||||
return c.recognizeAliyun(ctx, pngBytes)
|
||||
case domain.OCRProviderVolcengine:
|
||||
return c.recognizeVolcengine(ctx, pngBytes)
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported ocr provider %q", c.providerID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) recognizeAliyun(ctx context.Context, pngBytes []byte) (string, error) {
|
||||
endpoint, err := parseEndpoint(c.cfg.Endpoint)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(pngBytes))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build aliyun ocr request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
c.signAliyun(req, pngBytes)
|
||||
return c.doOCRRequest(req, "aliyun ocr")
|
||||
}
|
||||
|
||||
func (c *Client) recognizeVolcengine(ctx context.Context, pngBytes []byte) (string, error) {
|
||||
endpoint, err := parseEndpoint(c.cfg.Endpoint)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
query := endpoint.Query()
|
||||
query.Set("Action", c.cfg.Action)
|
||||
query.Set("Version", c.cfg.Version)
|
||||
endpoint.RawQuery = query.Encode()
|
||||
|
||||
body := map[string]string{
|
||||
"image_base64": base64.StdEncoding.EncodeToString(pngBytes),
|
||||
}
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal volcengine ocr request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build volcengine ocr request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.signVolcengine(req, payload)
|
||||
return c.doOCRRequest(req, "volcengine ocr")
|
||||
}
|
||||
|
||||
func (c *Client) doOCRRequest(req *http.Request, label string) (string, error) {
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s request: %w", label, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("%s status %d: %s", label, resp.StatusCode, compactBody(data))
|
||||
}
|
||||
text, err := parseOCRText(data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s response: %w", label, err)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
func (c *Client) signAliyun(req *http.Request, payload []byte) {
|
||||
now := c.now().UTC()
|
||||
payloadHash := sha256Hex(payload)
|
||||
nonce := c.nonce()
|
||||
|
||||
req.Header.Set("x-acs-action", c.cfg.Action)
|
||||
req.Header.Set("x-acs-version", c.cfg.Version)
|
||||
req.Header.Set("x-acs-date", now.Format("2006-01-02T15:04:05Z"))
|
||||
req.Header.Set("x-acs-signature-nonce", nonce)
|
||||
req.Header.Set("x-acs-content-sha256", payloadHash)
|
||||
|
||||
signedHeaders := []string{
|
||||
"content-type",
|
||||
"host",
|
||||
"x-acs-action",
|
||||
"x-acs-content-sha256",
|
||||
"x-acs-date",
|
||||
"x-acs-signature-nonce",
|
||||
"x-acs-version",
|
||||
}
|
||||
canonicalHeaders := canonicalHeaders(req, signedHeaders)
|
||||
canonicalRequest := strings.Join([]string{
|
||||
req.Method,
|
||||
canonicalURI(req.URL),
|
||||
canonicalQuery(req.URL),
|
||||
canonicalHeaders,
|
||||
strings.Join(signedHeaders, ";"),
|
||||
payloadHash,
|
||||
}, "\n")
|
||||
stringToSign := "ACS3-HMAC-SHA256\n" + sha256Hex([]byte(canonicalRequest))
|
||||
signature := hmacSHA256Hex([]byte(c.cfg.AccessKeySecret), []byte(stringToSign))
|
||||
req.Header.Set(
|
||||
"Authorization",
|
||||
fmt.Sprintf("ACS3-HMAC-SHA256 Credential=%s,SignedHeaders=%s,Signature=%s",
|
||||
c.cfg.AccessKeyID,
|
||||
strings.Join(signedHeaders, ";"),
|
||||
signature,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Client) signVolcengine(req *http.Request, payload []byte) {
|
||||
now := c.now().UTC()
|
||||
xDate := now.Format("20060102T150405Z")
|
||||
shortDate := now.Format("20060102")
|
||||
payloadHash := sha256Hex(payload)
|
||||
|
||||
req.Header.Set("X-Date", xDate)
|
||||
req.Header.Set("X-Content-Sha256", payloadHash)
|
||||
|
||||
signedHeaders := []string{
|
||||
"content-type",
|
||||
"host",
|
||||
"x-content-sha256",
|
||||
"x-date",
|
||||
}
|
||||
canonicalHeaders := canonicalHeaders(req, signedHeaders)
|
||||
canonicalRequest := strings.Join([]string{
|
||||
req.Method,
|
||||
canonicalURI(req.URL),
|
||||
canonicalQuery(req.URL),
|
||||
canonicalHeaders,
|
||||
strings.Join(signedHeaders, ";"),
|
||||
payloadHash,
|
||||
}, "\n")
|
||||
scope := strings.Join([]string{shortDate, c.cfg.Region, c.cfg.Service, "request"}, "/")
|
||||
stringToSign := strings.Join([]string{
|
||||
"HMAC-SHA256",
|
||||
xDate,
|
||||
scope,
|
||||
sha256Hex([]byte(canonicalRequest)),
|
||||
}, "\n")
|
||||
signingKey := volcengineSigningKey(c.cfg.AccessKeySecret, shortDate, c.cfg.Region, c.cfg.Service)
|
||||
signature := hmacSHA256Hex(signingKey, []byte(stringToSign))
|
||||
req.Header.Set(
|
||||
"Authorization",
|
||||
fmt.Sprintf("HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s",
|
||||
c.cfg.AccessKeyID,
|
||||
scope,
|
||||
strings.Join(signedHeaders, ";"),
|
||||
signature,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
func parseEndpoint(raw string) (*url.URL, error) {
|
||||
endpoint := strings.TrimSpace(raw)
|
||||
if endpoint == "" {
|
||||
return nil, fmt.Errorf("ocr endpoint is required")
|
||||
}
|
||||
if !strings.Contains(endpoint, "://") {
|
||||
endpoint = "https://" + endpoint
|
||||
}
|
||||
parsed, err := url.Parse(endpoint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse ocr endpoint: %w", err)
|
||||
}
|
||||
if parsed.Scheme == "" || parsed.Host == "" {
|
||||
return nil, fmt.Errorf("invalid ocr endpoint %q", raw)
|
||||
}
|
||||
if parsed.Path == "" {
|
||||
parsed.Path = "/"
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func parseOCRText(data []byte) (string, error) {
|
||||
var root any
|
||||
if err := json.Unmarshal(data, &root); err != nil {
|
||||
return "", fmt.Errorf("decode json: %w", err)
|
||||
}
|
||||
if msg := responseError(root); msg != "" {
|
||||
return "", errors.New(msg)
|
||||
}
|
||||
if text := normalizeOCRText(extractOverallOCRText(root, "")); text != "" {
|
||||
return text, nil
|
||||
}
|
||||
parts := collectOCRParts(root, "")
|
||||
if len(parts) == 0 {
|
||||
return "", fmt.Errorf("no text found")
|
||||
}
|
||||
return strings.Join(dedupeNonEmpty(parts), "\n"), nil
|
||||
}
|
||||
|
||||
func responseError(v any) string {
|
||||
obj, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if meta, ok := obj["ResponseMetadata"].(map[string]any); ok {
|
||||
if errObj, ok := meta["Error"].(map[string]any); ok {
|
||||
if msg := stringValue(errObj["Message"]); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if code := stringValue(errObj["Code"]); code != "" {
|
||||
return code
|
||||
}
|
||||
}
|
||||
}
|
||||
if errObj, ok := obj["Error"].(map[string]any); ok {
|
||||
if msg := stringValue(errObj["Message"]); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := stringValue(errObj["message"]); msg != "" {
|
||||
return msg
|
||||
}
|
||||
}
|
||||
if code, ok := numericCode(obj["code"]); ok && code != 0 && code != 10000 {
|
||||
if msg := stringValue(obj["message"]); msg != "" {
|
||||
return msg
|
||||
}
|
||||
if msg := stringValue(obj["msg"]); msg != "" {
|
||||
return msg
|
||||
}
|
||||
return fmt.Sprintf("provider code %.0f", code)
|
||||
}
|
||||
if code := stringValue(obj["Code"]); code != "" && !isSuccessCode(code) {
|
||||
if msg := stringValue(obj["Message"]); msg != "" {
|
||||
return msg
|
||||
}
|
||||
return code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractOverallOCRText(v any, parentKey string) string {
|
||||
switch value := v.(type) {
|
||||
case string:
|
||||
text := strings.TrimSpace(value)
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
if looksLikeJSON(text) {
|
||||
var nested any
|
||||
if err := json.Unmarshal([]byte(text), &nested); err == nil {
|
||||
if nestedText := extractOverallOCRText(nested, parentKey); nestedText != "" {
|
||||
return nestedText
|
||||
}
|
||||
}
|
||||
}
|
||||
if isAggregateContainerKey(parentKey) {
|
||||
return text
|
||||
}
|
||||
return ""
|
||||
case map[string]any:
|
||||
for _, key := range aggregateTextKeys() {
|
||||
if child, ok := value[key]; ok {
|
||||
if text := extractOverallOCRText(child, key); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range responseContainerKeys() {
|
||||
if child, ok := value[key]; ok {
|
||||
if text := extractOverallOCRText(child, key); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(value))
|
||||
for key := range value {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
if isAggregateTextKey(key) ||
|
||||
isResponseContainerKey(key) ||
|
||||
isBlockContainerKey(key) ||
|
||||
isMetadataKey(key) {
|
||||
continue
|
||||
}
|
||||
if text := extractOverallOCRText(value[key], key); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
return ""
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func collectOCRParts(v any, parentKey string) []string {
|
||||
switch value := v.(type) {
|
||||
case string:
|
||||
text := strings.TrimSpace(value)
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
if looksLikeJSON(text) {
|
||||
var nested any
|
||||
if err := json.Unmarshal([]byte(text), &nested); err == nil {
|
||||
return collectOCRParts(nested, parentKey)
|
||||
}
|
||||
}
|
||||
if isTextKey(parentKey) || isContainerTextKey(parentKey) {
|
||||
return []string{text}
|
||||
}
|
||||
return nil
|
||||
case []any:
|
||||
parts := make([]string, 0, len(value))
|
||||
for _, item := range value {
|
||||
parts = append(parts, collectOCRParts(item, parentKey)...)
|
||||
}
|
||||
return parts
|
||||
case map[string]any:
|
||||
parts := make([]string, 0)
|
||||
for _, key := range priorityOCRKeys() {
|
||||
if child, ok := value[key]; ok {
|
||||
parts = append(parts, collectOCRParts(child, key)...)
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(value))
|
||||
for key := range value {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
if isPriorityOCRKey(key) || isMetadataKey(key) {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, collectOCRParts(value[key], key)...)
|
||||
}
|
||||
return parts
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func aggregateTextKeys() []string {
|
||||
return []string{
|
||||
"content",
|
||||
"Content",
|
||||
"text",
|
||||
"Text",
|
||||
"full_text",
|
||||
"FullText",
|
||||
"fullText",
|
||||
"plain_text",
|
||||
"PlainText",
|
||||
"plainText",
|
||||
"recognized_text",
|
||||
"RecognizedText",
|
||||
"recognizedText",
|
||||
"ocr_text",
|
||||
"OCRText",
|
||||
"ocrText",
|
||||
}
|
||||
}
|
||||
|
||||
func responseContainerKeys() []string {
|
||||
return []string{
|
||||
"Data",
|
||||
"data",
|
||||
"Result",
|
||||
"result",
|
||||
}
|
||||
}
|
||||
|
||||
func priorityOCRKeys() []string {
|
||||
return []string{
|
||||
"Data",
|
||||
"data",
|
||||
"Result",
|
||||
"result",
|
||||
"content",
|
||||
"Content",
|
||||
"text",
|
||||
"Text",
|
||||
"DetectedText",
|
||||
"detected_text",
|
||||
"line_text",
|
||||
"LineText",
|
||||
"line_texts",
|
||||
"LineTexts",
|
||||
"word",
|
||||
"Word",
|
||||
"words",
|
||||
"Words",
|
||||
"words_result",
|
||||
"WordsResult",
|
||||
"prism_wordsInfo",
|
||||
"prism_words_info",
|
||||
"ocr_infos",
|
||||
"OCRInfos",
|
||||
"items",
|
||||
"Items",
|
||||
"blocks",
|
||||
"Blocks",
|
||||
"regions",
|
||||
"Regions",
|
||||
}
|
||||
}
|
||||
|
||||
func isAggregateTextKey(key string) bool {
|
||||
for _, item := range aggregateTextKeys() {
|
||||
if item == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isAggregateContainerKey(key string) bool {
|
||||
return isAggregateTextKey(key) || isResponseContainerKey(key)
|
||||
}
|
||||
|
||||
func isResponseContainerKey(key string) bool {
|
||||
for _, item := range responseContainerKeys() {
|
||||
if item == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isBlockContainerKey(key string) bool {
|
||||
switch normalizeKey(key) {
|
||||
case "wordsresult", "prismwordsinfo", "prismwords", "ocrinfos", "items",
|
||||
"blocks", "regions", "words", "linetexts", "lines", "cells":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isPriorityOCRKey(key string) bool {
|
||||
for _, item := range priorityOCRKeys() {
|
||||
if item == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isTextKey(key string) bool {
|
||||
switch normalizeKey(key) {
|
||||
case "content", "text", "detectedtext", "linetext", "word", "words", "value":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isContainerTextKey(key string) bool {
|
||||
switch normalizeKey(key) {
|
||||
case "data", "result", "linetexts", "texts":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isMetadataKey(key string) bool {
|
||||
switch normalizeKey(key) {
|
||||
case "requestid", "request", "code", "status", "statuscode", "success",
|
||||
"error", "errors", "message", "msg", "cost", "angle", "probability",
|
||||
"confidence", "height", "width", "left", "top", "right", "bottom",
|
||||
"x", "y", "responsemetadata":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeKey(key string) string {
|
||||
key = strings.ToLower(key)
|
||||
key = strings.ReplaceAll(key, "_", "")
|
||||
key = strings.ReplaceAll(key, "-", "")
|
||||
return key
|
||||
}
|
||||
|
||||
func dedupeNonEmpty(parts []string) []string {
|
||||
seen := map[string]struct{}{}
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
for _, line := range strings.Split(part, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[line]; ok {
|
||||
continue
|
||||
}
|
||||
seen[line] = struct{}{}
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeOCRText(text string) string {
|
||||
lines := strings.Split(strings.TrimSpace(text), "\n")
|
||||
out := make([]string, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return strings.Join(out, "\n")
|
||||
}
|
||||
|
||||
func looksLikeJSON(text string) bool {
|
||||
return strings.HasPrefix(text, "{") || strings.HasPrefix(text, "[")
|
||||
}
|
||||
|
||||
func stringValue(v any) string {
|
||||
if s, ok := v.(string); ok {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func numericCode(v any) (float64, bool) {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return n, true
|
||||
case int:
|
||||
return float64(n), true
|
||||
case json.Number:
|
||||
f, err := n.Float64()
|
||||
return f, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func isSuccessCode(code string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(code)) {
|
||||
case "", "ok", "success", "200", "10000":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func canonicalURI(u *url.URL) string {
|
||||
if u == nil || u.EscapedPath() == "" {
|
||||
return "/"
|
||||
}
|
||||
return u.EscapedPath()
|
||||
}
|
||||
|
||||
func canonicalQuery(u *url.URL) string {
|
||||
if u == nil || u.RawQuery == "" {
|
||||
return ""
|
||||
}
|
||||
values, _ := url.ParseQuery(u.RawQuery)
|
||||
return values.Encode()
|
||||
}
|
||||
|
||||
func canonicalHeaders(req *http.Request, signedHeaders []string) string {
|
||||
lines := make([]string, 0, len(signedHeaders))
|
||||
for _, key := range signedHeaders {
|
||||
var value string
|
||||
if key == "host" {
|
||||
value = req.URL.Host
|
||||
} else {
|
||||
value = req.Header.Get(key)
|
||||
}
|
||||
lines = append(lines, key+":"+normalizeHeaderValue(value)+"\n")
|
||||
}
|
||||
return strings.Join(lines, "")
|
||||
}
|
||||
|
||||
func normalizeHeaderValue(value string) string {
|
||||
return strings.Join(strings.Fields(strings.TrimSpace(value)), " ")
|
||||
}
|
||||
|
||||
func volcengineSigningKey(secret, date, region, service string) []byte {
|
||||
kDate := hmacSHA256([]byte(secret), []byte(date))
|
||||
kRegion := hmacSHA256(kDate, []byte(region))
|
||||
kService := hmacSHA256(kRegion, []byte(service))
|
||||
return hmacSHA256(kService, []byte("request"))
|
||||
}
|
||||
|
||||
func hmacSHA256(key, data []byte) []byte {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
mac.Write(data)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
func hmacSHA256Hex(key, data []byte) string {
|
||||
return hex.EncodeToString(hmacSHA256(key, data))
|
||||
}
|
||||
|
||||
func sha256Hex(data []byte) string {
|
||||
sum := sha256.Sum256(data)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func randomNonce() string {
|
||||
buf := make([]byte, 16)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
func compactBody(data []byte) string {
|
||||
text := strings.TrimSpace(string(data))
|
||||
if text == "" {
|
||||
return "<empty body>"
|
||||
}
|
||||
if len(text) > 800 {
|
||||
return text[:800] + "..."
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package ocr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
func TestAliyunRecognizeTextSignsRawPNGRequest(t *testing.T) {
|
||||
var requestBody []byte
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Host != "ocr-api.cn-hangzhou.aliyuncs.com" {
|
||||
t.Fatalf("unexpected host %s", r.URL.Host)
|
||||
}
|
||||
if got := r.Header.Get("x-acs-action"); got != "RecognizeGeneral" {
|
||||
t.Fatalf("unexpected action %q", got)
|
||||
}
|
||||
if got := r.Header.Get("x-acs-version"); got != "2021-07-07" {
|
||||
t.Fatalf("unexpected version %q", got)
|
||||
}
|
||||
if got := r.Header.Get("x-acs-date"); got != "2026-07-08T01:02:03Z" {
|
||||
t.Fatalf("unexpected date %q", got)
|
||||
}
|
||||
if got := r.Header.Get("Authorization"); !strings.Contains(got, "ACS3-HMAC-SHA256 Credential=ak") {
|
||||
t.Fatalf("unexpected auth header %q", got)
|
||||
}
|
||||
var err error
|
||||
requestBody, err = io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(bytes.NewBufferString(
|
||||
`{"Data":"{\"content\":\"第一行\\n第二行\"}"}`,
|
||||
)),
|
||||
}, nil
|
||||
})
|
||||
|
||||
client, err := NewClient(domain.OCRProviderAliyun, domain.OCRProviderConfig{
|
||||
Endpoint: "https://ocr-api.cn-hangzhou.aliyuncs.com",
|
||||
AccessKeyID: "ak",
|
||||
AccessKeySecret: "sk",
|
||||
Action: "RecognizeGeneral",
|
||||
Version: "2021-07-07",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
client.httpClient.Transport = transport
|
||||
client.now = func() time.Time { return time.Date(2026, 7, 8, 1, 2, 3, 0, time.UTC) }
|
||||
client.nonce = func() string { return "nonce" }
|
||||
|
||||
text, err := client.RecognizeText(context.Background(), []byte("png"))
|
||||
if err != nil {
|
||||
t.Fatalf("recognize text: %v", err)
|
||||
}
|
||||
if string(requestBody) != "png" {
|
||||
t.Fatalf("expected raw png body, got %q", string(requestBody))
|
||||
}
|
||||
if text != "第一行\n第二行" {
|
||||
t.Fatalf("unexpected OCR text %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolcengineRecognizeTextSignsBase64JSONRequest(t *testing.T) {
|
||||
var requestBody map[string]string
|
||||
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if got := r.URL.Query().Get("Action"); got != "OCRNormal" {
|
||||
t.Fatalf("unexpected action %q", got)
|
||||
}
|
||||
if got := r.URL.Query().Get("Version"); got != "2020-08-26" {
|
||||
t.Fatalf("unexpected version %q", got)
|
||||
}
|
||||
if got := r.Header.Get("X-Date"); got != "20260708T010203Z" {
|
||||
t.Fatalf("unexpected x-date %q", got)
|
||||
}
|
||||
if got := r.Header.Get("Authorization"); !strings.Contains(got, "HMAC-SHA256 Credential=ak/20260708/cn-north-1/cv/request") {
|
||||
t.Fatalf("unexpected auth header %q", got)
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(bytes.NewBufferString(
|
||||
`{"ResponseMetadata":{"RequestId":"r"},"Result":{"LineTexts":["你好","世界"]}}`,
|
||||
)),
|
||||
}, nil
|
||||
})
|
||||
|
||||
client, err := NewClient(domain.OCRProviderVolcengine, domain.OCRProviderConfig{
|
||||
Endpoint: "https://visual.volcengineapi.com",
|
||||
AccessKeyID: "ak",
|
||||
AccessKeySecret: "sk",
|
||||
Region: "cn-north-1",
|
||||
Service: "cv",
|
||||
Action: "OCRNormal",
|
||||
Version: "2020-08-26",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
client.httpClient.Transport = transport
|
||||
client.now = func() time.Time { return time.Date(2026, 7, 8, 1, 2, 3, 0, time.UTC) }
|
||||
|
||||
text, err := client.RecognizeText(context.Background(), []byte("png"))
|
||||
if err != nil {
|
||||
t.Fatalf("recognize text: %v", err)
|
||||
}
|
||||
if requestBody["image_base64"] != base64.StdEncoding.EncodeToString([]byte("png")) {
|
||||
t.Fatalf("expected base64 image body, got %#v", requestBody)
|
||||
}
|
||||
if text != "你好\n世界" {
|
||||
t.Fatalf("unexpected OCR text %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOCRTextSupportsWordsResult(t *testing.T) {
|
||||
text, err := parseOCRText([]byte(`{"data":{"words_result":[{"words":"foo"},{"words":"bar"}]}}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parse ocr text: %v", err)
|
||||
}
|
||||
if text != "foo\nbar" {
|
||||
t.Fatalf("unexpected OCR text %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOCRTextPrefersOverallContentOverBlocks(t *testing.T) {
|
||||
text, err := parseOCRText([]byte(`{
|
||||
"Data": "{\"content\":\"整体识别文本\",\"prism_wordsInfo\":[{\"word\":\"整体\"},{\"word\":\"识别\"},{\"word\":\"文本\"}]}"
|
||||
}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parse ocr text: %v", err)
|
||||
}
|
||||
if text != "整体识别文本" {
|
||||
t.Fatalf("expected overall content only, got %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOCRTextPrefersResultTextOverWordsResult(t *testing.T) {
|
||||
text, err := parseOCRText([]byte(`{
|
||||
"Result": {
|
||||
"text": "hello world",
|
||||
"words_result": [{"words":"hello"},{"words":"world"}]
|
||||
}
|
||||
}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parse ocr text: %v", err)
|
||||
}
|
||||
if text != "hello world" {
|
||||
t.Fatalf("expected result text only, got %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOCRTextReturnsProviderError(t *testing.T) {
|
||||
_, err := parseOCRText([]byte(`{"ResponseMetadata":{"Error":{"Code":"BadRequest","Message":"bad image"}}}`))
|
||||
if err == nil || !strings.Contains(err.Error(), "bad image") {
|
||||
t.Fatalf("expected provider error, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// Package oss contains storage adapters that satisfy domain.OSSProvider.
|
||||
//
|
||||
// The S3 adapter targets any S3-compatible endpoint via aws-sdk-go-v2.
|
||||
package oss
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
awsv2 "github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// S3Provider implements domain.OSSProvider using aws-sdk-go-v2.
|
||||
//
|
||||
// We construct one client per Provider instance because the S3 client is
|
||||
// goroutine-safe and the configuration is immutable for the lifetime of the
|
||||
// provider.
|
||||
type S3Provider struct {
|
||||
cfg domain.S3Config
|
||||
client *s3.Client
|
||||
}
|
||||
|
||||
// NewS3Provider builds an *S3Provider from the supplied user configuration.
|
||||
//
|
||||
// The endpoint is plumbed through BaseEndpoint + UsePathStyle so any
|
||||
// S3-compatible service (MinIO, R2, B2, Aliyun OSS s3 endpoint) works
|
||||
// without us writing per-vendor branches.
|
||||
func NewS3Provider(cfg domain.S3Config) (*S3Provider, error) {
|
||||
if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" {
|
||||
return nil, fmt.Errorf("s3 config: endpoint/bucket/accessKeyId/secretAccessKey are required")
|
||||
}
|
||||
region := cfg.Region
|
||||
if region == "" {
|
||||
region = "us-east-1"
|
||||
}
|
||||
awsCfg := awsv2.Config{
|
||||
Region: region,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(
|
||||
cfg.AccessKeyID, cfg.SecretAccessKey, "",
|
||||
),
|
||||
}
|
||||
endpoint := cfg.Endpoint
|
||||
client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = awsv2.String(endpoint)
|
||||
o.UsePathStyle = cfg.UsePathStyle
|
||||
})
|
||||
return &S3Provider{cfg: cfg, client: client}, nil
|
||||
}
|
||||
|
||||
// Name identifies this provider in logs and history records.
|
||||
func (p *S3Provider) Name() string { return "s3" }
|
||||
|
||||
// Upload pushes the bytes to the configured bucket and returns a public URL.
|
||||
//
|
||||
// We pass the body via bytes.Reader so the SDK can compute Content-Length
|
||||
// and signed checksum without buffering the data twice.
|
||||
func (p *S3Provider) Upload(ctx context.Context, key string, data []byte, contentType string) (string, error) {
|
||||
if contentType == "" {
|
||||
contentType = "image/png"
|
||||
}
|
||||
_, err := p.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: awsv2.String(p.cfg.Bucket),
|
||||
Key: awsv2.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
ContentType: awsv2.String(contentType),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("s3 put object: %w", err)
|
||||
}
|
||||
return p.BuildPublicURL(key), nil
|
||||
}
|
||||
|
||||
// BuildPublicURL constructs the URL that the user pastes into Markdown.
|
||||
//
|
||||
// Priority:
|
||||
// 1. PublicURLBase if user filled it (best-fit for CDN-fronted buckets);
|
||||
// 2. {Endpoint}/{Bucket}/{Key} for path-style;
|
||||
// 3. virtual-hosted-style fallback ({bucket}.host).
|
||||
func (p *S3Provider) BuildPublicURL(key string) string {
|
||||
if p.cfg.PublicURLBase != "" {
|
||||
base := strings.TrimRight(p.cfg.PublicURLBase, "/")
|
||||
return base + "/" + key
|
||||
}
|
||||
endpoint := strings.TrimRight(p.cfg.Endpoint, "/")
|
||||
if p.cfg.UsePathStyle {
|
||||
return endpoint + "/" + p.cfg.Bucket + "/" + key
|
||||
}
|
||||
// Virtual-hosted-style: replace host with {bucket}.{host}
|
||||
if u, err := url.Parse(endpoint); err == nil && u.Host != "" {
|
||||
u.Host = p.cfg.Bucket + "." + u.Host
|
||||
u.Path = "/" + key
|
||||
return u.String()
|
||||
}
|
||||
return endpoint + "/" + p.cfg.Bucket + "/" + key
|
||||
}
|
||||
|
||||
// Delete removes a previously uploaded object by key.
|
||||
//
|
||||
// The summary pipeline uses this to clean up the temporary screenshot it had
|
||||
// to upload only so a remote multimodal model could fetch it via public URL.
|
||||
func (p *S3Provider) Delete(ctx context.Context, key string) error {
|
||||
if _, err := p.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: awsv2.String(p.cfg.Bucket),
|
||||
Key: awsv2.String(key),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("s3 delete object: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestConnection performs a small put + delete to verify credentials and
|
||||
// bucket reachability. Used by the "Test connection" button in settings.
|
||||
func (p *S3Provider) TestConnection(ctx context.Context) error {
|
||||
probeKey := strings.TrimRight(p.cfg.PathPrefix, "/") + "/.snapgo-probe"
|
||||
probeKey = strings.TrimLeft(probeKey, "/")
|
||||
if _, err := p.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: awsv2.String(p.cfg.Bucket),
|
||||
Key: awsv2.String(probeKey),
|
||||
Body: bytes.NewReader([]byte("snapgo")),
|
||||
ContentType: awsv2.String("text/plain"),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("probe put: %w", err)
|
||||
}
|
||||
if _, err := p.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: awsv2.String(p.cfg.Bucket),
|
||||
Key: awsv2.String(probeKey),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("probe delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package screencapture defines the cross-platform Capturer abstraction.
|
||||
//
|
||||
// Per-platform implementations live in sibling files:
|
||||
// - capturer_darwin.go macOS, uses /usr/sbin/screencapture
|
||||
// - capturer_other.go non-darwin, uses kbinani/screenshot
|
||||
//
|
||||
// The interface is kept here so callers do not need build tags.
|
||||
package screencapture
|
||||
|
||||
import "image"
|
||||
|
||||
// Capturer is the abstraction that the application service depends on.
|
||||
type Capturer interface {
|
||||
// CaptureRegion grabs the pixels within the supplied virtual-screen
|
||||
// rectangle and returns PNG-encoded bytes.
|
||||
CaptureRegion(rect image.Rectangle) ([]byte, error)
|
||||
|
||||
// VirtualBounds returns the union rectangle of every connected display.
|
||||
VirtualBounds() image.Rectangle
|
||||
|
||||
// CaptureInteractive opens a system-provided region picker (e.g. macOS's
|
||||
// `screencapture -i`) and returns the resulting PNG bytes once the user
|
||||
// confirms a selection. If the user cancels (Esc / right-click), it
|
||||
// returns (nil, ErrCancelled) so callers can short-circuit cleanly.
|
||||
CaptureInteractive() ([]byte, error)
|
||||
|
||||
// CaptureFullScreen grabs the entire primary display silently and
|
||||
// returns the PNG bytes. Used as the backdrop for the in-app Snipaste-
|
||||
// style overlay; the per-region crop happens later in CropPNG once the
|
||||
// user finishes dragging.
|
||||
CaptureFullScreen() ([]byte, error)
|
||||
}
|
||||
|
||||
// ErrCancelled signals that the user aborted an interactive capture.
|
||||
// It is a sentinel value; callers should compare via errors.Is.
|
||||
type cancelled struct{}
|
||||
|
||||
func (cancelled) Error() string { return "capture cancelled by user" }
|
||||
|
||||
// ErrCancelled is returned from CaptureInteractive when the user dismisses
|
||||
// the system selection UI without confirming a region.
|
||||
var ErrCancelled = cancelled{}
|
||||
@@ -0,0 +1,145 @@
|
||||
//go:build darwin
|
||||
|
||||
package screencapture
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// macCapturer shells out to /usr/sbin/screencapture, which is bundled with
|
||||
// macOS, requires no cgo, and is fully compatible with macOS 15/26 SDKs
|
||||
// where CoreGraphics's display-capture API has been removed.
|
||||
//
|
||||
// Trade-off: a tiny process-spawn cost per capture (~30 ms). Acceptable for
|
||||
// an interactive screenshot tool — users cannot perceive it.
|
||||
type macCapturer struct{}
|
||||
|
||||
// New returns a macOS-native Capturer.
|
||||
func New() Capturer { return &macCapturer{} }
|
||||
|
||||
// VirtualBounds returns the union of all displays measured in CSS pixels
|
||||
// (i.e. logical, not Retina physical pixels). We query system_profiler via
|
||||
// AppleScript-free shell utilities to avoid extra cgo dependencies.
|
||||
//
|
||||
// For simplicity we currently return the main display only; this matches
|
||||
// what the WebView/window can actually paint without a separate transparent
|
||||
// window per display. Multi-monitor support is a follow-up spec.
|
||||
func (c *macCapturer) VirtualBounds() image.Rectangle {
|
||||
out, err := exec.Command(
|
||||
"system_profiler", "SPDisplaysDataType",
|
||||
).Output()
|
||||
if err == nil {
|
||||
// Look for "Resolution: 3024 x 1964" lines and take the first one.
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if !strings.HasPrefix(line, "Resolution:") {
|
||||
continue
|
||||
}
|
||||
parts := strings.Fields(line)
|
||||
// Expected pattern: ["Resolution:", "3024", "x", "1964", ...]
|
||||
if len(parts) >= 4 {
|
||||
w, errW := strconv.Atoi(parts[1])
|
||||
h, errH := strconv.Atoi(parts[3])
|
||||
if errW == nil && errH == nil {
|
||||
// Resolution reported is physical; convert to CSS px by
|
||||
// halving for Retina (assume 2× when w >= 2560).
|
||||
if w >= 2560 {
|
||||
w /= 2
|
||||
h /= 2
|
||||
}
|
||||
return image.Rect(0, 0, w, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Conservative fallback used by ~all modern Macs.
|
||||
return image.Rect(0, 0, 1440, 900)
|
||||
}
|
||||
|
||||
// CaptureRegion grabs the requested rectangle via the OS tool and returns
|
||||
// the resulting PNG bytes.
|
||||
//
|
||||
// Rect coords here are logical screen coordinates, matching macOS
|
||||
// screencapture's -R contract and the CSS-point coordinates reported by the
|
||||
// transparent overlay.
|
||||
func (c *macCapturer) CaptureRegion(rect image.Rectangle) ([]byte, error) {
|
||||
if rect.Dx() <= 0 || rect.Dy() <= 0 {
|
||||
return nil, fmt.Errorf("invalid capture rectangle: %v", rect)
|
||||
}
|
||||
|
||||
tmp := filepath.Join(os.TempDir(), fmt.Sprintf("snapgo-%d.png", time.Now().UnixNano()))
|
||||
defer os.Remove(tmp)
|
||||
|
||||
region := fmt.Sprintf("%d,%d,%d,%d",
|
||||
rect.Min.X, rect.Min.Y, rect.Dx(), rect.Dy(),
|
||||
)
|
||||
|
||||
// -x: silent (no shutter sound)
|
||||
// -R: rectangle
|
||||
// -t png
|
||||
cmd := exec.Command("/usr/sbin/screencapture", "-x", "-R", region, "-t", "png", tmp)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("screencapture: %w (%s)", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
data, err := os.ReadFile(tmp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read screencapture output: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// CaptureInteractive launches `screencapture -i` which presents the macOS
|
||||
// native region selector (the same crosshair that Cmd+Shift+4 produces).
|
||||
//
|
||||
// Design rationale:
|
||||
// - The native picker is pixel-perfect across Retina / external displays
|
||||
// and supports multi-monitor out of the box.
|
||||
// - It also handles Esc / right-click to cancel without requiring us to
|
||||
// run a transparent overlay window — which previously caused the main
|
||||
// window to flash a grey full-screen and trap the user.
|
||||
// - When the user cancels, screencapture exits 0 but writes no file; we
|
||||
// detect that case via os.Stat and return ErrCancelled.
|
||||
func (c *macCapturer) CaptureInteractive() ([]byte, error) {
|
||||
tmp := filepath.Join(os.TempDir(), fmt.Sprintf("snapgo-i-%d.png", time.Now().UnixNano()))
|
||||
defer os.Remove(tmp)
|
||||
|
||||
// -i: interactive region selection
|
||||
// -x: silent (suppress the camera shutter sound)
|
||||
// -t png: png output
|
||||
cmd := exec.Command("/usr/sbin/screencapture", "-i", "-x", "-t", "png", tmp)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("screencapture -i: %w (%s)", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
|
||||
// User cancelled (Esc / right-click): tool exits 0 with no file written.
|
||||
info, err := os.Stat(tmp)
|
||||
if err != nil || info.Size() == 0 {
|
||||
return nil, ErrCancelled
|
||||
}
|
||||
return os.ReadFile(tmp)
|
||||
}
|
||||
|
||||
// CaptureFullScreen runs `screencapture -x` to grab the primary display in
|
||||
// a single shot. We use -m so only the main display is captured even if
|
||||
// external monitors are attached — matches the "primary screen only" UX
|
||||
// chosen for the in-app overlay.
|
||||
func (c *macCapturer) CaptureFullScreen() ([]byte, error) {
|
||||
tmp := filepath.Join(os.TempDir(), fmt.Sprintf("snapgo-full-%d.png", time.Now().UnixNano()))
|
||||
defer os.Remove(tmp)
|
||||
|
||||
// -x: silent
|
||||
// -m: main display only
|
||||
// -t png: png output
|
||||
cmd := exec.Command("/usr/sbin/screencapture", "-x", "-m", "-t", "png", tmp)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("screencapture -x -m: %w (%s)", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return os.ReadFile(tmp)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//go:build !darwin
|
||||
|
||||
package screencapture
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
|
||||
"github.com/kbinani/screenshot"
|
||||
)
|
||||
|
||||
// kbinaniCapturer is the default non-darwin Capturer.
|
||||
type kbinaniCapturer struct{}
|
||||
|
||||
// New returns the default cross-platform Capturer for non-macOS systems.
|
||||
func New() Capturer { return &kbinaniCapturer{} }
|
||||
|
||||
func (c *kbinaniCapturer) VirtualBounds() image.Rectangle {
|
||||
n := screenshot.NumActiveDisplays()
|
||||
if n == 0 {
|
||||
return image.Rect(0, 0, 0, 0)
|
||||
}
|
||||
bounds := screenshot.GetDisplayBounds(0)
|
||||
for i := 1; i < n; i++ {
|
||||
bounds = bounds.Union(screenshot.GetDisplayBounds(i))
|
||||
}
|
||||
return bounds
|
||||
}
|
||||
|
||||
func (c *kbinaniCapturer) CaptureRegion(rect image.Rectangle) ([]byte, error) {
|
||||
if rect.Dx() <= 0 || rect.Dy() <= 0 {
|
||||
return nil, fmt.Errorf("invalid capture rectangle: %v", rect)
|
||||
}
|
||||
img, err := screenshot.CaptureRect(rect)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("capture: %w", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return nil, fmt.Errorf("encode png: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// CaptureInteractive on non-darwin platforms is not yet implemented. The
|
||||
// frontend overlay still works there. We surface a clear error so callers
|
||||
// can decide whether to fall back to the WebView overlay.
|
||||
func (c *kbinaniCapturer) CaptureInteractive() ([]byte, error) {
|
||||
return nil, fmt.Errorf("interactive capture is not implemented on this platform yet")
|
||||
}
|
||||
|
||||
// CaptureFullScreen grabs the primary display via kbinani/screenshot and
|
||||
// PNG-encodes the result. Multi-display extension is deliberately deferred
|
||||
// to keep parity with the macOS "primary only" UX.
|
||||
func (c *kbinaniCapturer) CaptureFullScreen() ([]byte, error) {
|
||||
if screenshot.NumActiveDisplays() == 0 {
|
||||
return nil, fmt.Errorf("no active display detected")
|
||||
}
|
||||
bounds := screenshot.GetDisplayBounds(0)
|
||||
img, err := screenshot.CaptureRect(bounds)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("capture full screen: %w", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return nil, fmt.Errorf("encode png: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package screencapture
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
)
|
||||
|
||||
// CropPNG decodes the supplied PNG, crops it to rect (in PHYSICAL pixels of
|
||||
// the source image — i.e. the same coordinate system the PNG itself uses),
|
||||
// and re-encodes the result.
|
||||
//
|
||||
// Why an extra abstraction: the overlay flow captures the entire screen as
|
||||
// one big PNG and lets the user pick a region in the WebView. The selection
|
||||
// rectangle the WebView reports is in CSS pixels, so callers must scale by
|
||||
// the display's backing factor before invoking CropPNG. Splitting "scale"
|
||||
// from "crop" keeps this helper focused and unit-testable.
|
||||
func CropPNG(pngBytes []byte, rect image.Rectangle) ([]byte, error) {
|
||||
if rect.Dx() <= 0 || rect.Dy() <= 0 {
|
||||
return nil, fmt.Errorf("invalid crop rectangle: %v", rect)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(pngBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode source png: %w", err)
|
||||
}
|
||||
// Clip the requested rectangle to the source bounds — defensive guard
|
||||
// against off-by-one errors from CSS-px → physical-px scaling.
|
||||
src := img.Bounds()
|
||||
clipped := rect.Intersect(src)
|
||||
if clipped.Empty() {
|
||||
return nil, fmt.Errorf("crop rectangle %v has no overlap with source %v", rect, src)
|
||||
}
|
||||
|
||||
// SubImage is documented on most concrete image types; the standard
|
||||
// library decodes PNGs into one of those, so this assertion is safe in
|
||||
// practice. Fall back to a manual copy otherwise.
|
||||
type subImager interface {
|
||||
SubImage(r image.Rectangle) image.Image
|
||||
}
|
||||
var cropped image.Image
|
||||
if si, ok := img.(subImager); ok {
|
||||
cropped = si.SubImage(clipped)
|
||||
} else {
|
||||
dst := image.NewRGBA(image.Rect(0, 0, clipped.Dx(), clipped.Dy()))
|
||||
for y := 0; y < clipped.Dy(); y++ {
|
||||
for x := 0; x < clipped.Dx(); x++ {
|
||||
dst.Set(x, y, img.At(clipped.Min.X+x, clipped.Min.Y+y))
|
||||
}
|
||||
}
|
||||
cropped = dst
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, cropped); err != nil {
|
||||
return nil, fmt.Errorf("encode cropped png: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
// Package ssh provides an SCP-based remote upload adapter for SnapGo.
|
||||
//
|
||||
// Design rationale:
|
||||
// - We deliberately implement SCP "sink mode" by hand on top of an SSH
|
||||
// session instead of pulling in an extra dependency. The protocol is
|
||||
// trivial (one control line + payload + null byte) and we only need
|
||||
// write support, so a custom implementation keeps the dependency
|
||||
// surface small and auditable.
|
||||
// - The adapter is split into a Client (connection lifetime) and a
|
||||
// CopyFile method (single transfer) so future use-cases such as listing
|
||||
// or deleting remote files can extend the same SSH session.
|
||||
// - All public methods accept a context so the application layer can
|
||||
// enforce a timeout that matches the user-perceived capture latency.
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/agent"
|
||||
"golang.org/x/crypto/ssh/knownhosts"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// logger returns a component-scoped slog logger bound to the CURRENT
|
||||
// default handler.
|
||||
//
|
||||
// 为什么是函数而非包级 slog.With 变量:
|
||||
// - 包级变量在 main() 调用 logging.Init() 之前就初始化, 那一刻
|
||||
// slog.Default() 还是 bootstrap handler (它转发给标准 log 包).
|
||||
// - logging.Init() 里的 slog.SetDefault() 会把标准 log 包重定向回新的
|
||||
// TextHandler, 于是旧 handler 先把整行格式化成 "INFO msg component=ssh..."
|
||||
// 再被新 handler 当成一个 msg 二次包裹, 产生双前缀日志.
|
||||
// - 每次惰性读取 slog.Default() 即可始终拿到正确的目标 handler.
|
||||
func sshLog() *slog.Logger { return slog.Default().With("component", "ssh") }
|
||||
|
||||
// Client is a thin wrapper around *ssh.Client whose lifetime maps 1:1
|
||||
// to a single upload operation. We do not pool connections because the
|
||||
// expected cadence (a few uploads per minute at most) does not justify
|
||||
// the additional complexity of managing keep-alives.
|
||||
type Client struct {
|
||||
client *ssh.Client
|
||||
cfg domain.SSHConfig
|
||||
}
|
||||
|
||||
// Dial establishes an SSH connection using the supplied configuration.
|
||||
//
|
||||
// Authentication priority:
|
||||
// 1. Password, if non-empty.
|
||||
// 2. Local ssh-agent ($SSH_AUTH_SOCK), if present.
|
||||
// 3. ~/.ssh/id_ed25519 → id_rsa fallback files.
|
||||
//
|
||||
// Host-key verification follows cfg.StrictHostKey. When strict, the user-
|
||||
// supplied known_hosts file is honoured (defaulting to ~/.ssh/known_hosts).
|
||||
// When false the call uses ssh.InsecureIgnoreHostKey, which is a deliberate
|
||||
// trade-off that surfaces in the UI — the settings page warns the user.
|
||||
func Dial(ctx context.Context, cfg domain.SSHConfig) (*Client, error) {
|
||||
if cfg.Host == "" || cfg.User == "" {
|
||||
return nil, fmt.Errorf("ssh: host and user are required")
|
||||
}
|
||||
port := cfg.Port
|
||||
if port <= 0 {
|
||||
port = 22
|
||||
}
|
||||
timeout := time.Duration(cfg.ConnectTimeoutSecs) * time.Second
|
||||
if timeout <= 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
|
||||
authMethods, authSummary, err := buildAuthMethods(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(authMethods) == 0 {
|
||||
sshLog().Warn("dial aborted: no auth methods",
|
||||
"host", cfg.Host, "user", cfg.User, "auth_summary", authSummary)
|
||||
return nil, fmt.Errorf("ssh: no authentication methods available (set password or ensure ssh-agent / ~/.ssh/id_* exists)")
|
||||
}
|
||||
|
||||
hostKeyCallback, hostKeyMode, err := buildHostKeyCallback(cfg)
|
||||
if err != nil {
|
||||
sshLog().Error("host key callback failed",
|
||||
"host", cfg.Host, "strict", cfg.StrictHostKey,
|
||||
"known_hosts", cfg.KnownHostsPath, "err", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
clientCfg := &ssh.ClientConfig{
|
||||
User: cfg.User,
|
||||
Auth: authMethods,
|
||||
HostKeyCallback: hostKeyCallback,
|
||||
Timeout: timeout,
|
||||
}
|
||||
addr := net.JoinHostPort(cfg.Host, fmt.Sprintf("%d", port))
|
||||
|
||||
sshLog().Info("dial start",
|
||||
"addr", addr, "user", cfg.User,
|
||||
"timeout", timeout, "auth_summary", authSummary, "host_key", hostKeyMode)
|
||||
|
||||
dialStart := time.Now()
|
||||
// Honour ctx by dialing through net.Dialer so an early ctx cancel
|
||||
// surfaces here instead of after the (long) ssh handshake.
|
||||
dialer := net.Dialer{Timeout: timeout}
|
||||
tcpConn, err := dialer.DialContext(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
sshLog().Error("tcp dial failed",
|
||||
"addr", addr, "elapsed", time.Since(dialStart), "err", err)
|
||||
return nil, fmt.Errorf("ssh: dial %s: %w", addr, err)
|
||||
}
|
||||
sshLog().Debug("tcp connected", "addr", addr, "elapsed", time.Since(dialStart))
|
||||
|
||||
hsStart := time.Now()
|
||||
sshConn, chans, reqs, err := ssh.NewClientConn(tcpConn, addr, clientCfg)
|
||||
if err != nil {
|
||||
_ = tcpConn.Close()
|
||||
sshLog().Error("ssh handshake failed",
|
||||
"addr", addr, "user", cfg.User,
|
||||
"elapsed", time.Since(hsStart), "err", err)
|
||||
return nil, fmt.Errorf("ssh: handshake: %w", err)
|
||||
}
|
||||
sshLog().Info("ssh handshake ok",
|
||||
"addr", addr, "user", cfg.User,
|
||||
"server_version", string(sshConn.ServerVersion()),
|
||||
"elapsed", time.Since(hsStart))
|
||||
return &Client{
|
||||
client: ssh.NewClient(sshConn, chans, reqs),
|
||||
cfg: cfg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Close shuts down the underlying SSH connection.
|
||||
func (c *Client) Close() error {
|
||||
if c == nil || c.client == nil {
|
||||
return nil
|
||||
}
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
// CopyFile uploads `data` to remoteRelativePath under the user's home
|
||||
// directory. The caller passes a path *relative to $HOME*; the adapter
|
||||
// strips any leading "/" or "~" so users cannot escape their home
|
||||
// directory through misconfigured PathPrefix values.
|
||||
//
|
||||
// The upload uses the SCP "sink mode" protocol:
|
||||
//
|
||||
// $ scp -t <remote-dir>
|
||||
// ← we send: D0755 0 <subdir>\n (mkdir -p analogue, repeated)
|
||||
// ← we send: C0644 <size> <basename>\n
|
||||
// ← we send: <bytes...>\0
|
||||
// ← we send: E\n (close each directory)
|
||||
//
|
||||
// Each line we write is acknowledged by a single 0x00 byte from the remote
|
||||
// `scp -t` process; a non-zero ack indicates an error.
|
||||
func (c *Client) CopyFile(ctx context.Context, remoteRelativePath string, data []byte, mode os.FileMode) error {
|
||||
cleaned := normaliseRemotePath(remoteRelativePath)
|
||||
if cleaned == "" {
|
||||
return fmt.Errorf("ssh: remote path is empty")
|
||||
}
|
||||
|
||||
dir, base := path.Split(cleaned)
|
||||
dir = strings.Trim(dir, "/")
|
||||
|
||||
sshLog().Info("scp copy start",
|
||||
"remote_path", cleaned, "dir", dir, "file", base,
|
||||
"size", len(data), "mode", fmt.Sprintf("%#o", mode.Perm()))
|
||||
|
||||
session, err := c.client.NewSession()
|
||||
if err != nil {
|
||||
sshLog().Error("scp new session failed", "err", err)
|
||||
return fmt.Errorf("ssh: new session: %w", err)
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
stdin, err := session.StdinPipe()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ssh: stdin pipe: %w", err)
|
||||
}
|
||||
stdout, err := session.StdoutPipe()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ssh: stdout pipe: %w", err)
|
||||
}
|
||||
|
||||
// `-t` puts the remote scp into "sink mode" rooted at $HOME. `-r`
|
||||
// allows us to feed `D` directives so we can create directory trees
|
||||
// in one round-trip rather than running a separate `mkdir -p`.
|
||||
cmd := fmt.Sprintf("scp -tr %s", shellQuote("./"))
|
||||
sshLog().Debug("scp remote command", "cmd", cmd)
|
||||
if err := session.Start(cmd); err != nil {
|
||||
sshLog().Error("scp session start failed", "cmd", cmd, "err", err)
|
||||
return fmt.Errorf("ssh: start scp: %w", err)
|
||||
}
|
||||
|
||||
transferStart := time.Now()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- writeSCPStream(stdin, stdout, dir, base, data, mode)
|
||||
}()
|
||||
|
||||
// Wait for either ctx, the writer goroutine, or the remote command.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
sshLog().Warn("scp cancelled by context",
|
||||
"remote_path", cleaned, "elapsed", time.Since(transferStart), "err", ctx.Err())
|
||||
_ = session.Signal(ssh.SIGTERM)
|
||||
_ = session.Close()
|
||||
return ctx.Err()
|
||||
case writeErr := <-errCh:
|
||||
if writeErr != nil {
|
||||
sshLog().Error("scp protocol failed",
|
||||
"remote_path", cleaned, "elapsed", time.Since(transferStart), "err", writeErr)
|
||||
_ = session.Close()
|
||||
return writeErr
|
||||
}
|
||||
}
|
||||
|
||||
if err := session.Wait(); err != nil {
|
||||
sshLog().Error("scp session wait failed",
|
||||
"remote_path", cleaned, "elapsed", time.Since(transferStart), "err", err)
|
||||
return fmt.Errorf("ssh: scp wait: %w", err)
|
||||
}
|
||||
sshLog().Info("scp copy ok",
|
||||
"remote_path", cleaned, "size", len(data), "elapsed", time.Since(transferStart))
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeSCPStream drives the SCP sink-mode dialogue described above. It is
|
||||
// extracted from CopyFile for two reasons:
|
||||
// 1. It contains the only blocking IO so we can run it in a goroutine
|
||||
// and select on ctx.Done().
|
||||
// 2. It makes the protocol-level steps testable in isolation (the unit
|
||||
// tests pipe an in-memory bytes.Buffer into expectAck).
|
||||
func writeSCPStream(stdin io.WriteCloser, stdout io.Reader, dir, base string, data []byte, mode os.FileMode) error {
|
||||
defer stdin.Close()
|
||||
|
||||
// First ack: the remote scp -t emits an initial 0x00 once it is ready.
|
||||
if err := expectAck(stdout); err != nil {
|
||||
return fmt.Errorf("scp: initial ack: %w", err)
|
||||
}
|
||||
sshLog().Debug("scp initial ack received")
|
||||
|
||||
// Walk `dir` segment by segment, opening each level with `D0755 0 <name>`.
|
||||
dirs := splitNonEmpty(dir, "/")
|
||||
for _, segment := range dirs {
|
||||
line := fmt.Sprintf("D0755 0 %s\n", segment)
|
||||
if _, err := io.WriteString(stdin, line); err != nil {
|
||||
return fmt.Errorf("scp: write D-line: %w", err)
|
||||
}
|
||||
if err := expectAck(stdout); err != nil {
|
||||
return fmt.Errorf("scp: ack D-line %q: %w", segment, err)
|
||||
}
|
||||
sshLog().Debug("scp dir opened", "segment", segment)
|
||||
}
|
||||
|
||||
// File header: `C<perm> <size> <name>\n`
|
||||
header := fmt.Sprintf("C%04o %d %s\n", mode.Perm(), len(data), base)
|
||||
if _, err := io.WriteString(stdin, header); err != nil {
|
||||
return fmt.Errorf("scp: write C-line: %w", err)
|
||||
}
|
||||
if err := expectAck(stdout); err != nil {
|
||||
return fmt.Errorf("scp: ack C-line: %w", err)
|
||||
}
|
||||
sshLog().Debug("scp header acked", "header", strings.TrimSpace(header))
|
||||
|
||||
if _, err := stdin.Write(data); err != nil {
|
||||
return fmt.Errorf("scp: write payload: %w", err)
|
||||
}
|
||||
if _, err := stdin.Write([]byte{0}); err != nil {
|
||||
return fmt.Errorf("scp: write trailing null: %w", err)
|
||||
}
|
||||
if err := expectAck(stdout); err != nil {
|
||||
return fmt.Errorf("scp: ack payload: %w", err)
|
||||
}
|
||||
sshLog().Debug("scp payload acked", "bytes", len(data))
|
||||
|
||||
// Pop each directory we opened earlier with an `E` line so the remote
|
||||
// scp finishes cleanly.
|
||||
for range dirs {
|
||||
if _, err := io.WriteString(stdin, "E\n"); err != nil {
|
||||
return fmt.Errorf("scp: write E-line: %w", err)
|
||||
}
|
||||
if err := expectAck(stdout); err != nil {
|
||||
return fmt.Errorf("scp: ack E-line: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// expectAck reads exactly one byte from the remote scp and treats anything
|
||||
// other than 0x00 as a protocol-level error. When the remote signals an
|
||||
// error (0x01 = warning, 0x02 = fatal) it is followed by a textual reason
|
||||
// terminated with '\n', which we surface to the caller.
|
||||
func expectAck(r io.Reader) error {
|
||||
buf := make([]byte, 1)
|
||||
if _, err := io.ReadFull(r, buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if buf[0] == 0 {
|
||||
return nil
|
||||
}
|
||||
// Read the rest of the message until newline so the user sees a
|
||||
// meaningful "permission denied"-style reason.
|
||||
msg := readUntilNewline(r)
|
||||
return fmt.Errorf("scp remote error (%d): %s", buf[0], strings.TrimSpace(msg))
|
||||
}
|
||||
|
||||
func readUntilNewline(r io.Reader) string {
|
||||
var sb strings.Builder
|
||||
buf := make([]byte, 1)
|
||||
for i := 0; i < 1024; i++ {
|
||||
if _, err := io.ReadFull(r, buf); err != nil {
|
||||
break
|
||||
}
|
||||
if buf[0] == '\n' {
|
||||
break
|
||||
}
|
||||
sb.WriteByte(buf[0])
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// TestConnection performs a minimal handshake + `pwd` round trip so the
|
||||
// settings UI can confirm the credentials work without writing a file.
|
||||
func TestConnection(ctx context.Context, cfg domain.SSHConfig) error {
|
||||
sshLog().Info("test connection start", "host", cfg.Host, "user", cfg.User, "port", cfg.Port)
|
||||
start := time.Now()
|
||||
client, err := Dial(ctx, cfg)
|
||||
if err != nil {
|
||||
sshLog().Error("test connection: dial failed", "err", err, "elapsed", time.Since(start))
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
session, err := client.client.NewSession()
|
||||
if err != nil {
|
||||
sshLog().Error("test connection: new session failed", "err", err)
|
||||
return fmt.Errorf("ssh: new session: %w", err)
|
||||
}
|
||||
defer session.Close()
|
||||
if err := session.Run("true"); err != nil {
|
||||
sshLog().Error("test connection: probe failed", "err", err)
|
||||
return fmt.Errorf("ssh: probe command failed: %w", err)
|
||||
}
|
||||
sshLog().Info("test connection ok", "elapsed", time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
// normaliseRemotePath strips any leading "/" or "~" so the path is always
|
||||
// interpreted relative to the remote $HOME, matching the UI promise.
|
||||
func normaliseRemotePath(p string) string {
|
||||
p = strings.TrimSpace(p)
|
||||
p = strings.TrimPrefix(p, "~")
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
p = strings.TrimPrefix(p, "./")
|
||||
return path.Clean(p)
|
||||
}
|
||||
|
||||
// splitNonEmpty splits `s` on `sep` and discards empty segments so the
|
||||
// caller does not have to defend against double slashes etc.
|
||||
func splitNonEmpty(s, sep string) []string {
|
||||
parts := strings.Split(s, sep)
|
||||
out := parts[:0]
|
||||
for _, part := range parts {
|
||||
if part == "" || part == "." {
|
||||
continue
|
||||
}
|
||||
out = append(out, part)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// shellQuote is a defensive single-quote escaper used when interpolating
|
||||
// user-controlled strings (currently only the relative root ".") into the
|
||||
// remote `scp` command line. We do NOT quote arbitrary user paths because
|
||||
// SCP itself receives them through the protocol channel above.
|
||||
func shellQuote(s string) string {
|
||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||
}
|
||||
|
||||
// buildAuthMethods chooses authentication methods given the supplied
|
||||
// configuration.
|
||||
//
|
||||
// The method set is gated by cfg.AuthMethod:
|
||||
// - SSHAuthPassword → password only.
|
||||
// - SSHAuthKey → ssh-agent + ~/.ssh/id_* key files only.
|
||||
// - "" / SSHAuthBuiltin (legacy) → password (if set) + agent + key files.
|
||||
//
|
||||
// (Kerberos never reaches here; it uses the system ssh binary instead.)
|
||||
//
|
||||
// Returns a human-readable summary alongside the method slice so the
|
||||
// caller can include "password+agent+ed25519" (and similar) in its dial
|
||||
// log without leaking secret material.
|
||||
func buildAuthMethods(cfg domain.SSHConfig) ([]ssh.AuthMethod, string, error) {
|
||||
var methods []ssh.AuthMethod
|
||||
var sources []string
|
||||
|
||||
// Decide which families are allowed for the selected method. An empty /
|
||||
// "builtin" value preserves the original combined behaviour so configs
|
||||
// written before the split keep working.
|
||||
allowPassword := cfg.AuthMethod == domain.SSHAuthPassword ||
|
||||
cfg.AuthMethod == domain.SSHAuthBuiltin || cfg.AuthMethod == ""
|
||||
allowKey := cfg.AuthMethod == domain.SSHAuthKey ||
|
||||
cfg.AuthMethod == domain.SSHAuthBuiltin || cfg.AuthMethod == ""
|
||||
|
||||
if allowPassword && cfg.Password != "" {
|
||||
methods = append(methods, ssh.Password(cfg.Password))
|
||||
sources = append(sources, "password")
|
||||
}
|
||||
if allowKey {
|
||||
if sock := os.Getenv("SSH_AUTH_SOCK"); sock != "" {
|
||||
if conn, err := net.Dial("unix", sock); err == nil {
|
||||
// 关键: 仅在 agent 真正持有 key 时才把它加入 auth methods.
|
||||
//
|
||||
// macOS 的 launchd ssh-agent 即便没有任何 identity 也会响应,
|
||||
// 此时若仍注册 PublicKeysCallback, x/crypto 会把它当作一次空的
|
||||
// publickey 尝试. 配合服务器的 MaxAuthTries 计数, 这次"空尝试"
|
||||
// 会挤占后续基于磁盘私钥的认证机会, 最终导致
|
||||
// "[none publickey] no supported methods remain" —— 即便磁盘上
|
||||
// 的 key 本身完全可用. 因此空 agent 必须跳过.
|
||||
ag := agent.NewClient(conn)
|
||||
if keys, lerr := ag.List(); lerr == nil && len(keys) > 0 {
|
||||
methods = append(methods, ssh.PublicKeysCallback(ag.Signers))
|
||||
sources = append(sources, fmt.Sprintf("agent(%d)", len(keys)))
|
||||
} else {
|
||||
sshLog().Debug("ssh-agent has no identities; skipping",
|
||||
"sock", sock, "list_err", lerr)
|
||||
}
|
||||
} else {
|
||||
sshLog().Debug("ssh-agent dial failed", "sock", sock, "err", err)
|
||||
}
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
// Probe the common default keys; any unreadable / missing file is
|
||||
// silently skipped so the user never sees noise about keys they did
|
||||
// not set up.
|
||||
for _, name := range []string{"id_ed25519", "id_rsa", "id_ecdsa"} {
|
||||
signer, err := loadPrivateKey(path.Join(home, ".ssh", name))
|
||||
if err == nil && signer != nil {
|
||||
methods = append(methods, ssh.PublicKeys(signer))
|
||||
sources = append(sources, name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sshLog().Debug("home dir unavailable for ssh keys", "err", err)
|
||||
}
|
||||
}
|
||||
if len(sources) == 0 {
|
||||
return methods, "none", nil
|
||||
}
|
||||
return methods, strings.Join(sources, "+"), nil
|
||||
}
|
||||
|
||||
// loadPrivateKey reads and parses a single OpenSSH private key file.
|
||||
// Returns (nil, nil) when the file does not exist so the caller can keep
|
||||
// scanning the standard key list.
|
||||
func loadPrivateKey(p string) (ssh.Signer, error) {
|
||||
data, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
signer, err := ssh.ParsePrivateKey(data)
|
||||
if err != nil {
|
||||
// Encrypted keys without a passphrase are skipped silently for now;
|
||||
// passphrase support is left to a follow-up spec.
|
||||
return nil, nil
|
||||
}
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
// buildHostKeyCallback returns either a strict known_hosts-backed callback
|
||||
// or an InsecureIgnoreHostKey fallback, depending on cfg.StrictHostKey.
|
||||
//
|
||||
// The returned mode string ("insecure" or "known_hosts:<path>") is logged
|
||||
// at dial time so a "rejected by host key" failure is easy to diagnose.
|
||||
func buildHostKeyCallback(cfg domain.SSHConfig) (ssh.HostKeyCallback, string, error) {
|
||||
if !cfg.StrictHostKey {
|
||||
// Deliberate trade-off: matches `scp -o StrictHostKeyChecking=no` and
|
||||
// keeps the first-launch experience friction-free for personal LANs.
|
||||
return ssh.InsecureIgnoreHostKey(), "insecure", nil
|
||||
}
|
||||
knownHosts := cfg.KnownHostsPath
|
||||
if knownHosts == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("ssh: resolve home for known_hosts: %w", err)
|
||||
}
|
||||
knownHosts = path.Join(home, ".ssh", "known_hosts")
|
||||
}
|
||||
cb, err := knownhosts.New(knownHosts)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("ssh: load known_hosts %q: %w", knownHosts, err)
|
||||
}
|
||||
return cb, "known_hosts:" + knownHosts, nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// kerberos_uploader.go — an SSHUploader implementation that delegates to
|
||||
// the system /usr/bin/ssh + /usr/bin/scp binaries so an existing Kerberos
|
||||
// (GSSAPI) credential cache populated by `kinit` is reused transparently.
|
||||
//
|
||||
// 设计理由 (为什么不用 golang.org/x/crypto/ssh 做 Kerberos):
|
||||
// - macOS 的 Kerberos 票据默认存放在 API: 类型的 credential cache 中,
|
||||
// 由系统 GSSD (Heimdal) 守护进程托管. Go 生态的 gokrb5 只能读取
|
||||
// FILE: 类型 ccache 与 keytab, 无法访问 API: ccache, 因此在 macOS 上
|
||||
// 用纯 Go 实现 GSSAPI 认证基本不可行.
|
||||
// - 系统自带的 /usr/bin/ssh 原生集成 Heimdal GSSAPI, 用户 `kinit` 之后
|
||||
// 的票据可被直接复用. 把上传委托给系统 ssh/scp 是最稳妥的方案, 也与
|
||||
// 用户"命令行能免密登录即可"的预期完全一致.
|
||||
// - 仅在 AuthMethod == kerberos 时启用此实现; builtin 路径不受影响.
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// systemSSHPath / systemSCPPath are the absolute paths to the macOS system
|
||||
// binaries. We use absolute paths rather than relying on $PATH so a hijacked
|
||||
// PATH cannot redirect us to an arbitrary binary, and because GUI apps on
|
||||
// macOS often launch with a minimal PATH that omits /usr/bin entirely.
|
||||
const (
|
||||
systemSSHPath = "/usr/bin/ssh"
|
||||
systemSCPPath = "/usr/bin/scp"
|
||||
)
|
||||
|
||||
// KerberosUploader satisfies application.SSHUploader by shelling out to the
|
||||
// system scp binary with GSSAPI authentication enabled.
|
||||
type KerberosUploader struct {
|
||||
cfg domain.SSHConfig
|
||||
}
|
||||
|
||||
// NewKerberosUploader returns an uploader that delegates to system scp.
|
||||
func NewKerberosUploader(cfg domain.SSHConfig) *KerberosUploader {
|
||||
return &KerberosUploader{cfg: cfg}
|
||||
}
|
||||
|
||||
// Upload writes data to remoteRelPath (relative to the remote $HOME) by
|
||||
// staging it in a local temp file and invoking system scp once.
|
||||
//
|
||||
// We stage to a temp file because scp transfers files, not stdin; piping a
|
||||
// stream would require the more fragile `scp -t` sink protocol that we only
|
||||
// use for the in-process client. A temp file is simpler and robust.
|
||||
func (u *KerberosUploader) Upload(ctx context.Context, remoteRelPath string, data []byte, mode os.FileMode) error {
|
||||
start := time.Now()
|
||||
cleaned := normaliseRemotePath(remoteRelPath)
|
||||
if cleaned == "" {
|
||||
return fmt.Errorf("ssh(kerberos): remote path is empty")
|
||||
}
|
||||
sshLog().Info("kerberos uploader start",
|
||||
"host", u.cfg.Host, "user", u.cfg.User, "port", u.cfg.Port,
|
||||
"remote_path", cleaned, "size", len(data))
|
||||
|
||||
// 1. Ensure the remote directory tree exists. scp itself will not create
|
||||
// intermediate directories, so we run a remote `mkdir -p` first.
|
||||
dir, _ := path.Split(cleaned)
|
||||
dir = strings.Trim(dir, "/")
|
||||
if dir != "" {
|
||||
if err := u.runRemoteMkdir(ctx, dir); err != nil {
|
||||
sshLog().Error("kerberos uploader mkdir failed",
|
||||
"dir", dir, "elapsed", time.Since(start), "err", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Stage the payload to a local temp file for scp to read.
|
||||
tmp, err := os.CreateTemp("", "snapgo-scp-*.png")
|
||||
if err != nil {
|
||||
return fmt.Errorf("ssh(kerberos): create temp: %w", err)
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
defer os.Remove(tmpPath)
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("ssh(kerberos): write temp: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("ssh(kerberos): close temp: %w", err)
|
||||
}
|
||||
if err := os.Chmod(tmpPath, mode.Perm()); err != nil {
|
||||
sshLog().Debug("kerberos uploader chmod temp failed", "err", err)
|
||||
}
|
||||
|
||||
// 3. scp the temp file to "user@host:cleaned" (cleaned is relative to
|
||||
// $HOME, which scp interprets correctly for a remote login shell).
|
||||
remoteTarget := fmt.Sprintf("%s@%s:%s", u.cfg.User, u.cfg.Host, cleaned)
|
||||
args := append(u.commonSCPArgs(), tmpPath, remoteTarget)
|
||||
if err := u.runCommand(ctx, systemSCPPath, args); err != nil {
|
||||
sshLog().Error("kerberos uploader scp failed",
|
||||
"remote_path", cleaned, "elapsed", time.Since(start), "err", err)
|
||||
return err
|
||||
}
|
||||
sshLog().Info("kerberos uploader done",
|
||||
"remote_path", cleaned, "size", len(data), "total_elapsed", time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
// runRemoteMkdir runs `mkdir -p ~/<dir>` on the remote host via system ssh.
|
||||
func (u *KerberosUploader) runRemoteMkdir(ctx context.Context, dir string) error {
|
||||
remote := fmt.Sprintf("%s@%s", u.cfg.User, u.cfg.Host)
|
||||
// Quote the directory so spaces / metacharacters cannot break the shell
|
||||
// command. dir is already normalised (no leading ~ or /).
|
||||
cmd := "mkdir -p " + shellQuote("./"+dir)
|
||||
args := append(u.commonSSHArgs(), remote, cmd)
|
||||
return u.runCommand(ctx, systemSSHPath, args)
|
||||
}
|
||||
|
||||
// commonSSHArgs builds the shared option set that enables GSSAPI auth and
|
||||
// disables interactive prompts (we want a hard failure, never a hang waiting
|
||||
// for a password the GUI cannot answer).
|
||||
func (u *KerberosUploader) commonSSHArgs() []string {
|
||||
port := u.cfg.Port
|
||||
if port <= 0 {
|
||||
port = 22
|
||||
}
|
||||
timeout := u.cfg.ConnectTimeoutSecs
|
||||
if timeout <= 0 {
|
||||
timeout = 10
|
||||
}
|
||||
args := []string{
|
||||
"-p", strconv.Itoa(port),
|
||||
"-o", "GSSAPIAuthentication=yes",
|
||||
"-o", "GSSAPIDelegateCredentials=no",
|
||||
"-o", "PreferredAuthentications=gssapi-with-mic,gssapi-keyex",
|
||||
"-o", "PubkeyAuthentication=no",
|
||||
"-o", "PasswordAuthentication=no",
|
||||
"-o", "KbdInteractiveAuthentication=no",
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "ConnectTimeout=" + strconv.Itoa(timeout),
|
||||
}
|
||||
args = append(args, u.hostKeyArgs()...)
|
||||
return args
|
||||
}
|
||||
|
||||
// commonSCPArgs mirrors commonSSHArgs but uses scp's uppercase -P port flag.
|
||||
func (u *KerberosUploader) commonSCPArgs() []string {
|
||||
port := u.cfg.Port
|
||||
if port <= 0 {
|
||||
port = 22
|
||||
}
|
||||
timeout := u.cfg.ConnectTimeoutSecs
|
||||
if timeout <= 0 {
|
||||
timeout = 10
|
||||
}
|
||||
args := []string{
|
||||
"-P", strconv.Itoa(port),
|
||||
"-o", "GSSAPIAuthentication=yes",
|
||||
"-o", "GSSAPIDelegateCredentials=no",
|
||||
"-o", "PreferredAuthentications=gssapi-with-mic,gssapi-keyex",
|
||||
"-o", "PubkeyAuthentication=no",
|
||||
"-o", "PasswordAuthentication=no",
|
||||
"-o", "KbdInteractiveAuthentication=no",
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "ConnectTimeout=" + strconv.Itoa(timeout),
|
||||
}
|
||||
args = append(args, u.hostKeyArgs()...)
|
||||
return args
|
||||
}
|
||||
|
||||
// hostKeyArgs maps StrictHostKey onto OpenSSH's StrictHostKeyChecking option,
|
||||
// keeping behaviour consistent with the in-process client.
|
||||
func (u *KerberosUploader) hostKeyArgs() []string {
|
||||
if u.cfg.StrictHostKey {
|
||||
if u.cfg.KnownHostsPath != "" {
|
||||
return []string{
|
||||
"-o", "StrictHostKeyChecking=yes",
|
||||
"-o", "UserKnownHostsFile=" + u.cfg.KnownHostsPath,
|
||||
}
|
||||
}
|
||||
return []string{"-o", "StrictHostKeyChecking=yes"}
|
||||
}
|
||||
// Non-strict: accept new keys automatically but still record them. This
|
||||
// mirrors the in-process InsecureIgnoreHostKey trade-off the UI warns of.
|
||||
return []string{"-o", "StrictHostKeyChecking=accept-new"}
|
||||
}
|
||||
|
||||
// runCommand executes the given binary, capturing combined stderr so a
|
||||
// failure surfaces the remote/OpenSSH diagnostic instead of a bare exit code.
|
||||
func (u *KerberosUploader) runCommand(ctx context.Context, bin string, args []string) error {
|
||||
cmd := exec.CommandContext(ctx, bin, args...)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
sshLog().Debug("kerberos exec", "bin", bin, "args", strings.Join(args, " "))
|
||||
if err := cmd.Run(); err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
return fmt.Errorf("%s failed: %s", path.Base(bin), msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestKerberosConnection probes the remote host with system ssh, surfacing a
|
||||
// clear hint when no valid ticket is present.
|
||||
func TestKerberosConnection(ctx context.Context, cfg domain.SSHConfig) error {
|
||||
sshLog().Info("kerberos test connection start",
|
||||
"host", cfg.Host, "user", cfg.User, "port", cfg.Port)
|
||||
u := &KerberosUploader{cfg: cfg}
|
||||
remote := fmt.Sprintf("%s@%s", cfg.User, cfg.Host)
|
||||
args := append(u.commonSSHArgs(), remote, "true")
|
||||
if err := u.runCommand(ctx, systemSSHPath, args); err != nil {
|
||||
// Detect the most common cause: no/expired Kerberos ticket.
|
||||
if !hasKerberosTicket(ctx) {
|
||||
return fmt.Errorf("no valid Kerberos ticket found — run `kinit %s@BYTEDANCE.COM` first (%w)", cfg.User, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
sshLog().Info("kerberos test connection ok")
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasKerberosTicket reports whether `klist -s` indicates a valid ticket.
|
||||
// `klist -s` exits 0 when a valid TGT exists, non-zero otherwise.
|
||||
func hasKerberosTicket(ctx context.Context) bool {
|
||||
cmd := exec.CommandContext(ctx, "/usr/bin/klist", "-s")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// SFTPUploader transfers screenshots through the SSH File Transfer Protocol.
|
||||
// It lives beside the SCP client so both protocols share the same SSH
|
||||
// authentication and host-key implementation without duplicating credential
|
||||
// discovery code.
|
||||
type SFTPUploader struct {
|
||||
cfg domain.FTPConfig
|
||||
}
|
||||
|
||||
// NewSFTPUploader returns a short-lived SFTP adapter. A fresh SSH/SFTP
|
||||
// connection is opened for every upload or connection probe.
|
||||
func NewSFTPUploader(cfg domain.FTPConfig) *SFTPUploader {
|
||||
return &SFTPUploader{cfg: cfg}
|
||||
}
|
||||
|
||||
func (u *SFTPUploader) sshConfig() domain.SSHConfig {
|
||||
return domain.SSHConfig{
|
||||
Host: u.cfg.Host,
|
||||
Port: u.cfg.Port,
|
||||
User: u.cfg.User,
|
||||
AuthMethod: u.cfg.AuthMethod,
|
||||
Password: u.cfg.Password,
|
||||
StrictHostKey: u.cfg.StrictHostKey,
|
||||
KnownHostsPath: u.cfg.KnownHostsPath,
|
||||
ConnectTimeoutSecs: u.cfg.ConnectTimeoutSecs,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *SFTPUploader) dial(ctx context.Context) (*Client, *sftp.Client, error) {
|
||||
sshClient, err := Dial(ctx, u.sshConfig())
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("sftp: %w", err)
|
||||
}
|
||||
sftpClient, err := sftp.NewClient(sshClient.client)
|
||||
if err != nil {
|
||||
_ = sshClient.Close()
|
||||
return nil, nil, fmt.Errorf("sftp: start subsystem: %w", err)
|
||||
}
|
||||
return sshClient, sftpClient, nil
|
||||
}
|
||||
|
||||
// Upload writes data to a temporary file and atomically exposes it at the
|
||||
// final relative path after the transfer completes.
|
||||
func (u *SFTPUploader) Upload(ctx context.Context, remoteRelPath string, data []byte) error {
|
||||
cleaned, err := validateSFTPRemotePath(remoteRelPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sshClient, sftpClient, err := u.dial(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
done := closeSFTPOnCancel(ctx, sshClient, sftpClient)
|
||||
defer sshClient.Close()
|
||||
defer sftpClient.Close()
|
||||
defer close(done)
|
||||
|
||||
dir := path.Dir(cleaned)
|
||||
if dir != "." {
|
||||
if err := sftpClient.MkdirAll(dir); err != nil {
|
||||
return fmt.Errorf("sftp: create directory %s: %w", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
tempPath := path.Join(dir, temporarySFTPName(path.Base(cleaned)))
|
||||
removeTemp := true
|
||||
defer func() {
|
||||
if removeTemp {
|
||||
_ = sftpClient.Remove(tempPath)
|
||||
}
|
||||
}()
|
||||
|
||||
file, err := sftpClient.OpenFile(tempPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sftp: create temporary file: %w", err)
|
||||
}
|
||||
reader := &sftpContextReader{ctx: ctx, reader: bytes.NewReader(data)}
|
||||
_, copyErr := io.Copy(file, reader)
|
||||
if copyErr == nil {
|
||||
copyErr = file.Chmod(0o644)
|
||||
}
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return fmt.Errorf("sftp: write %s: %w", cleaned, copyErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("sftp: close %s: %w", cleaned, closeErr)
|
||||
}
|
||||
if err := sftpClient.Rename(tempPath, cleaned); err != nil {
|
||||
return fmt.Errorf("sftp: commit %s: %w", cleaned, err)
|
||||
}
|
||||
removeTemp = false
|
||||
sshLog().Info("SFTP upload ok", "remote_path", cleaned, "size", len(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestConnection verifies SFTP write/delete permissions with a small probe.
|
||||
func (u *SFTPUploader) TestConnection(ctx context.Context) error {
|
||||
probe, err := sftpProbePath(u.cfg.PathPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sshClient, sftpClient, err := u.dial(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
done := closeSFTPOnCancel(ctx, sshClient, sftpClient)
|
||||
defer sshClient.Close()
|
||||
defer sftpClient.Close()
|
||||
defer close(done)
|
||||
|
||||
dir := path.Dir(probe)
|
||||
if dir != "." {
|
||||
if err := sftpClient.MkdirAll(dir); err != nil {
|
||||
return fmt.Errorf("sftp probe: create directory: %w", err)
|
||||
}
|
||||
}
|
||||
file, err := sftpClient.OpenFile(probe, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sftp probe: create: %w", err)
|
||||
}
|
||||
_, writeErr := file.Write([]byte("snapgo"))
|
||||
closeErr := file.Close()
|
||||
if writeErr != nil {
|
||||
_ = sftpClient.Remove(probe)
|
||||
return fmt.Errorf("sftp probe: write: %w", writeErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = sftpClient.Remove(probe)
|
||||
return fmt.Errorf("sftp probe: close: %w", closeErr)
|
||||
}
|
||||
if err := sftpClient.Remove(probe); err != nil {
|
||||
return fmt.Errorf("sftp probe: delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeSFTPOnCancel(ctx context.Context, sshClient *Client, sftpClient *sftp.Client) chan struct{} {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = sftpClient.Close()
|
||||
_ = sshClient.Close()
|
||||
case <-done:
|
||||
}
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
func validateSFTPRemotePath(value string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || strings.HasPrefix(value, "/") || strings.HasPrefix(value, "~") {
|
||||
return "", fmt.Errorf("sftp: remote path must be relative to the login directory")
|
||||
}
|
||||
if strings.ContainsAny(value, "\x00\r\n\\") {
|
||||
return "", fmt.Errorf("sftp: remote path contains an invalid character")
|
||||
}
|
||||
for _, segment := range strings.Split(value, "/") {
|
||||
if segment == ".." {
|
||||
return "", fmt.Errorf("sftp: remote path must not contain '..'")
|
||||
}
|
||||
}
|
||||
cleaned := path.Clean(value)
|
||||
if cleaned == "." || path.Base(cleaned) == "." || path.Base(cleaned) == ".." {
|
||||
return "", fmt.Errorf("sftp: remote filename is empty")
|
||||
}
|
||||
return cleaned, nil
|
||||
}
|
||||
|
||||
func sftpProbePath(prefix string) (string, error) {
|
||||
prefix = strings.TrimSpace(prefix)
|
||||
prefix = strings.TrimPrefix(prefix, "~")
|
||||
prefix = strings.TrimLeft(prefix, "/")
|
||||
return validateSFTPRemotePath(path.Join(prefix, fmt.Sprintf(".snapgo-probe-%d", time.Now().UnixNano())))
|
||||
}
|
||||
|
||||
func temporarySFTPName(base string) string {
|
||||
return fmt.Sprintf(".%s.snapgo-upload-%d", base, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
type sftpContextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r *sftpContextReader) Read(p []byte) (int, error) {
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return 0, r.ctx.Err()
|
||||
default:
|
||||
return r.reader.Read(p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ssh
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateSFTPRemotePathRejectsTraversal(t *testing.T) {
|
||||
if got, err := validateSFTPRemotePath("snapgo/2026/image.png"); err != nil || got != "snapgo/2026/image.png" {
|
||||
t.Fatalf("valid path: got %q err=%v", got, err)
|
||||
}
|
||||
|
||||
for _, value := range []string{
|
||||
"",
|
||||
"/absolute/image.png",
|
||||
"~/image.png",
|
||||
"../image.png",
|
||||
"snapgo/../../image.png",
|
||||
"snapgo\\image.png",
|
||||
} {
|
||||
if _, err := validateSFTPRemotePath(value); err == nil {
|
||||
t.Errorf("expected %q to be rejected", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSFTPProbePathRejectsTraversalPrefix(t *testing.T) {
|
||||
if _, err := sftpProbePath("../../outside"); err == nil {
|
||||
t.Fatal("expected traversal prefix to fail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// uploader.go — small adapter that satisfies application.SSHUploader by
|
||||
// dialing a one-shot connection per upload. This keeps the application
|
||||
// layer free of any direct dependency on golang.org/x/crypto/ssh while
|
||||
// still exposing a clean, unit-testable contract.
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/mmmy/snapgo/internal/domain"
|
||||
)
|
||||
|
||||
// Uploader is the production implementation of application.SSHUploader.
|
||||
//
|
||||
// We dial fresh per-upload because:
|
||||
// - Captures happen sparsely (a few per minute at peak), so the cost of
|
||||
// a TCP+SSH handshake is dwarfed by user think-time.
|
||||
// - Holding a long-lived connection would force us to add keepalives,
|
||||
// reconnection logic, and config-change invalidation — not worth it
|
||||
// for the current usage profile.
|
||||
type Uploader struct {
|
||||
cfg domain.SSHConfig
|
||||
}
|
||||
|
||||
// NewUploader returns a ready-to-use uploader. The configuration is
|
||||
// captured by value so a simultaneous in-flight upload cannot be re-
|
||||
// targeted by a settings save.
|
||||
func NewUploader(cfg domain.SSHConfig) *Uploader {
|
||||
return &Uploader{cfg: cfg}
|
||||
}
|
||||
|
||||
// Upload satisfies application.SSHUploader. We log entry/exit at INFO so
|
||||
// the operator sees a single line per upload in the normal happy path,
|
||||
// and ERROR with elapsed time when something fails.
|
||||
func (u *Uploader) Upload(ctx context.Context, remoteRelPath string, data []byte, mode os.FileMode) error {
|
||||
start := time.Now()
|
||||
sshLog().Info("uploader.Upload start",
|
||||
"host", u.cfg.Host, "user", u.cfg.User, "port", u.cfg.Port,
|
||||
"remote_path", remoteRelPath, "size", len(data))
|
||||
|
||||
client, err := Dial(ctx, u.cfg)
|
||||
if err != nil {
|
||||
sshLog().Error("uploader.Upload dial failed",
|
||||
"host", u.cfg.Host, "elapsed", time.Since(start), "err", err)
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
if err := client.CopyFile(ctx, remoteRelPath, data, mode); err != nil {
|
||||
sshLog().Error("uploader.Upload copy failed",
|
||||
"remote_path", remoteRelPath, "elapsed", time.Since(start), "err", err)
|
||||
return err
|
||||
}
|
||||
sshLog().Info("uploader.Upload done",
|
||||
"remote_path", remoteRelPath, "size", len(data),
|
||||
"total_elapsed", time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.7 KiB |