apiserver.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. // ============================================================================
  2. // apiserver.go — 内置 API 服务
  3. //
  4. // 用 Gin 提供的本机 HTTP API:健康检查、通知、窗口控制、电源命令、屏幕截图、
  5. // 鼠标提醒等;日志写控制台并存入环形缓冲(供「主机」页实时查看)。
  6. // ============================================================================
  7. package main
  8. import (
  9. "archive/zip"
  10. "context"
  11. "crypto/rand"
  12. "crypto/subtle"
  13. "encoding/base64"
  14. "encoding/binary"
  15. "fmt"
  16. "io"
  17. "log"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "github.com/gen2brain/beeep" // 跨平台系统通知,Windows 下为托盘气泡/Toast
  27. "github.com/gin-gonic/gin"
  28. )
  29. // notifyRequest 通知接口的请求体
  30. type notifyRequest struct {
  31. Title string `json:"title"` // 通知标题,为空时使用应用名
  32. Message string `json:"message"` // 通知正文
  33. }
  34. // mouseAlertRequest 鼠标提醒接口的请求体
  35. type mouseAlertRequest struct {
  36. Text string `json:"text"` // 提示文字,为空时使用默认文案
  37. }
  38. // ------------------------------------------------------------------------
  39. // Gin 日志环形缓冲:日志同时写控制台与内存缓冲,供「主机」页实时查看
  40. // ------------------------------------------------------------------------
  41. const apiLogCapacity = 300 // 环形缓冲最多保留的日志行数
  42. // logRing 固定容量的日志环形缓冲,实现 io.Writer
  43. type logRing struct {
  44. mu sync.Mutex
  45. lines []string
  46. }
  47. // Write 按行拆分写入缓冲,并向所有前端窗口广播 "apilog" 事件
  48. func (r *logRing) Write(p []byte) (int, error) {
  49. text := strings.TrimRight(string(p), "\r\n")
  50. r.mu.Lock()
  51. for _, line := range strings.Split(text, "\n") {
  52. if strings.TrimSpace(line) == "" {
  53. continue
  54. }
  55. if strings.Contains(line, `"/api/logs"`) {
  56. continue // 面板轮询自身的访问日志不入缓冲,避免刷屏
  57. }
  58. r.lines = append(r.lines, line)
  59. if len(r.lines) > apiLogCapacity {
  60. r.lines = r.lines[len(r.lines)-apiLogCapacity:] // 丢弃最旧的行
  61. }
  62. if app != nil {
  63. app.Event.Emit("apilog", line) // 实时推送到「主机」页
  64. }
  65. }
  66. r.mu.Unlock()
  67. return len(p), nil
  68. }
  69. // Snapshot 返回当前缓冲的全部日志行
  70. func (r *logRing) Snapshot() []string {
  71. r.mu.Lock()
  72. defer r.mu.Unlock()
  73. out := make([]string, len(r.lines))
  74. copy(out, r.lines)
  75. return out
  76. }
  77. // Clear 清空日志缓冲
  78. func (r *logRing) Clear() {
  79. r.mu.Lock()
  80. r.lines = nil
  81. r.mu.Unlock()
  82. }
  83. var apiLogRing = &logRing{}
  84. // ------------------------------------------------------------------------
  85. // API 服务生命周期:地址变化时平滑重启(仅监听配置的地址)
  86. // ------------------------------------------------------------------------
  87. var (
  88. apiMu sync.Mutex
  89. apiServer *http.Server
  90. apiAddr string // 当前监听地址
  91. apiStartedAt time.Time // 本次启动时间
  92. apiLastErr string // 最近一次启动 / 运行错误
  93. )
  94. // currentAPIAddr 返回内置 API 当前监听地址(未运行为空),供服务模式登记转发目标
  95. func currentAPIAddr() string {
  96. apiMu.Lock()
  97. defer apiMu.Unlock()
  98. if apiServer == nil {
  99. return ""
  100. }
  101. return apiAddr
  102. }
  103. // StopAPIServer 停止内置 API 服务(从服务页手动关闭)。
  104. // 停止后 apiServer 置 nil、apiAddr 保留,便于再次启动或恢复。
  105. func StopAPIServer() {
  106. apiMu.Lock()
  107. old := apiServer
  108. apiServer = nil
  109. apiAddr = ""
  110. apiLastErr = ""
  111. apiMu.Unlock()
  112. if old != nil {
  113. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  114. _ = old.Shutdown(ctx) // 平滑关闭,中断不复用连接
  115. cancel()
  116. }
  117. log.Printf("API server stopped by user")
  118. fmt.Fprintf(apiLogRing, "[SYS] API 服务已停止\n")
  119. }
  120. // StartAPIServer 启动 / 重启内置 API 服务(从服务页手动启动或恢复)。
  121. // 使用配置中的地址(为空时用默认地址)。
  122. func StartAPIServer() {
  123. ensureAPIServer(loadSettings().APIAddr)
  124. }
  125. // APIStatus API 服务运行状态,供「主机」页展示
  126. type APIStatus struct {
  127. Addr string `json:"addr"` // 当前监听地址
  128. Running bool `json:"running"` // 是否正在监听
  129. StartedAt string `json:"startedAt"` // 启动时间
  130. Error string `json:"error"` // 最近错误信息
  131. }
  132. // ensureAPIServer 确保 API 服务监听在指定地址;地址变化时先关闭旧服务再启动
  133. func ensureAPIServer(addr string) {
  134. addr = strings.TrimSpace(addr)
  135. if addr == "" {
  136. addr = DefaultAPIAddr
  137. }
  138. apiMu.Lock()
  139. if apiServer != nil && apiAddr == addr && apiLastErr == "" {
  140. apiMu.Unlock()
  141. return // 地址未变且运行正常,无需重启
  142. }
  143. old := apiServer
  144. apiServer = nil
  145. apiAddr = addr
  146. apiStartedAt = time.Now()
  147. apiLastErr = ""
  148. apiMu.Unlock()
  149. if old != nil {
  150. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  151. _ = old.Shutdown(ctx) // 平滑关闭旧服务,中断不复用连接
  152. cancel()
  153. }
  154. go runAPIServer(addr)
  155. }
  156. // runAPIServer 构建路由并启动监听(出错只记录状态,不影响应用本身)
  157. func runAPIServer(addr string) {
  158. gin.SetMode(gin.ReleaseMode) // 生产模式,减少日志噪音
  159. router := gin.New()
  160. router.Use(gin.LoggerWithConfig(gin.LoggerConfig{
  161. // 环形缓冲必须放在前面:Windows GUI 程序的 Stdout 可能不可写,
  162. // MultiWriter 遇到前一个 writer 出错便停止,不能因此阻断界面日志与事件推送。
  163. Output: io.MultiWriter(apiLogRing, os.Stdout),
  164. // 自定义格式:服务模式转发来的请求追加 [service],便于区分来源
  165. Formatter: func(p gin.LogFormatterParams) string {
  166. via := ""
  167. if p.Request != nil && p.Request.Header.Get("X-TengTu-Via") == "service" {
  168. via = " [service]"
  169. }
  170. return fmt.Sprintf("[GIN] %v | %3d | %13v | %15s | %-7s %#v%s\n",
  171. p.TimeStamp.Format("2006/01/02 - 15:04:05"),
  172. p.StatusCode,
  173. p.Latency,
  174. p.ClientIP,
  175. p.Method,
  176. p.Path,
  177. via,
  178. )
  179. },
  180. }))
  181. router.Use(gin.Recovery()) // 捕获 panic,避免接口崩溃导致进程退出
  182. router.Use(corsMiddleware()) // 允许跨域,便于前端或其他本机工具调用
  183. router.GET("/health", func(c *gin.Context) {
  184. c.JSON(http.StatusOK, gin.H{"status": "ok"}) // 健康检查
  185. })
  186. router.GET("/upload", handleUploadPage) // 客户端上传页(手机等设备浏览器访问)
  187. router.GET("/api/qr", handleQRImage) // 生成二维码图片(供客户端上传页/桌面端展示)
  188. api := router.Group("/api")
  189. api.GET("/logs", handleGetAPILogs) // 读取 Gin 日志环形缓冲(供面板/外部核对)
  190. api.POST("/notify", handleNotify) // 弹出系统托盘通知
  191. api.POST("/window/show", handleShowWindow) // 显示主窗口
  192. api.POST("/window/compact", handleWindowCompact) // 窗口收拢/还原(与双击手柄等效)
  193. api.POST("/mouse/alert", handleMouseAlert) // 触发系统级鼠标提醒(闪烁光标+提示文字)
  194. api.POST("/tag/open", handleTagOpen) // 打开标签编辑窗口(注册表右键菜单转发)
  195. api.POST("/handle/flash", handleHandleFlash) // 触发拖动手柄圆点闪烁(颜色+大小变化)
  196. api.GET("/settings", handleGetSettings) // 读取配置
  197. api.POST("/settings", handleSaveSettings) // 保存配置
  198. api.GET("/stocks", handleGetStocks) // 获取股票行情
  199. api.GET("/screenshot", handleScreenshot) // 截取屏幕,返回 PNG 数据 URI
  200. api.POST("/upload", handleUpload) // 上传文件(需密码)
  201. api.GET("/download/:filename", handleDownload) // 下载已上传文件(需密码)
  202. api.POST("/xz/cmd", handleXZCmdPost) // 下发指令(left/right/up/down),与服务模式共用实现
  203. api.GET("/xz/cmd", handleXZCmdGet) // 读取最新指令
  204. api.GET("/xz/cmd/:cmd", handleXZCmdPathPost) // 路径参数下发(URL 编码),如 /xz/cmd/left
  205. pc := api.Group("/pc") // 主机控制接口(移植自主机服务)
  206. pc.GET("/poweroff", handlePoweroff) // 30 秒后关机
  207. pc.GET("/restart", handleRestart) // 30 秒后重启
  208. pc.GET("/sleep", handleSleep) // 30 秒后休眠
  209. pc.GET("/lock", handleLock) // 立即锁屏
  210. pc.GET("/cancel", handleCancel) // 取消待执行命令
  211. pc.GET("/status", handlePCStatus) // 查询命令状态
  212. pc.GET("/timesync", handleTimeSync) // 同步系统时间
  213. server := &http.Server{Addr: addr, Handler: router}
  214. apiMu.Lock()
  215. apiServer = server
  216. apiMu.Unlock()
  217. log.Printf("API server listening on http://%s", addr)
  218. fmt.Fprintf(apiLogRing, "[SYS] API 服务已启动 http://%s\n", addr)
  219. if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  220. apiMu.Lock()
  221. apiLastErr = err.Error() // 端口被占用等错误只记录,不影响应用启动
  222. apiMu.Unlock()
  223. log.Printf("api server stopped: %v", err)
  224. fmt.Fprintf(apiLogRing, "[SYS] API 服务异常停止: %v\n", err)
  225. }
  226. }
  227. // getAPIStatus 返回当前 API 服务状态快照
  228. func getAPIStatus() APIStatus {
  229. apiMu.Lock()
  230. defer apiMu.Unlock()
  231. started := ""
  232. if !apiStartedAt.IsZero() {
  233. started = apiStartedAt.Format("01-02 15:04:05")
  234. }
  235. return APIStatus{
  236. Addr: apiAddr,
  237. Running: apiServer != nil,
  238. StartedAt: started,
  239. Error: apiLastErr,
  240. }
  241. }
  242. // corsMiddleware 简单放行跨域请求(服务默认仅监听 127.0.0.1,风险可控)
  243. func corsMiddleware() gin.HandlerFunc {
  244. return func(c *gin.Context) {
  245. c.Header("Access-Control-Allow-Origin", "*")
  246. c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
  247. c.Header("Access-Control-Allow-Headers", "Content-Type")
  248. if c.Request.Method == http.MethodOptions {
  249. c.AbortWithStatus(http.StatusNoContent) // 预检请求直接返回
  250. return
  251. }
  252. c.Next()
  253. }
  254. }
  255. // handleGetAPILogs 返回 Gin 日志环形缓冲的当前内容(最近若干行)
  256. func handleGetAPILogs(c *gin.Context) {
  257. c.JSON(http.StatusOK, gin.H{"lines": apiLogRing.Snapshot()})
  258. }
  259. // handleNotify 通过系统通知弹出消息,例如:POST /api/notify {"message":"任务完成"}
  260. func handleNotify(c *gin.Context) {
  261. var req notifyRequest
  262. if err := c.ShouldBindJSON(&req); err != nil {
  263. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  264. return
  265. }
  266. if req.Title == "" {
  267. req.Title = "腾图工具箱" // 未指定标题时使用默认标题
  268. }
  269. if err := beeep.Notify(req.Title, req.Message, ""); err != nil {
  270. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  271. return
  272. }
  273. c.JSON(http.StatusOK, gin.H{"ok": true}) // 通知已发出
  274. }
  275. // handleMouseAlert 触发系统级鼠标提醒,例如:POST /api/mouse/alert {"text":"有新订单"}
  276. func handleMouseAlert(c *gin.Context) {
  277. var req mouseAlertRequest
  278. if err := c.ShouldBindJSON(&req); err != nil {
  279. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  280. return
  281. }
  282. triggerMouseAlert(req.Text) // 触发鼠标闪烁 + 光标下方透明文字
  283. c.JSON(http.StatusOK, gin.H{"ok": true})
  284. }
  285. // handleTagOpen 打开标签编辑窗口,例如:POST /api/tag/open {"path":"C:\\xx\\yy.txt"}
  286. // 由注册表右键菜单「标签」调用本程序时,若已有实例在运行则转发到此接口;
  287. // 运行中的实例收到后弹出标签编辑窗口(openTagEditor)供用户输入标签/备注。
  288. func handleTagOpen(c *gin.Context) {
  289. var req struct {
  290. Path string `json:"path"`
  291. }
  292. if err := c.ShouldBindJSON(&req); err != nil {
  293. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  294. return
  295. }
  296. path := strings.TrimSpace(req.Path)
  297. if path == "" {
  298. c.JSON(http.StatusBadRequest, gin.H{"error": "path 不能为空"})
  299. return
  300. }
  301. openTagEditor(path) // 弹出标签编辑窗口(单实例,已有窗口则切换路径并聚焦)
  302. c.JSON(http.StatusOK, gin.H{"ok": true})
  303. }
  304. // handleHandleFlash 触发拖动手柄圆点闪烁,例如:POST /api/handle/flash {"count":3}
  305. // count 为闪烁次数(可选,默认 3);前端收到 handleFlash 事件后播放颜色+大小变化动画。
  306. func handleHandleFlash(c *gin.Context) {
  307. var req struct {
  308. Count int `json:"count"`
  309. }
  310. // 允许空 body(默认 3 次闪烁)
  311. _ = c.ShouldBindJSON(&req)
  312. (&SettingsService{}).HandleFlash(req.Count)
  313. c.JSON(http.StatusOK, gin.H{"ok": true})
  314. }
  315. // handleShowWindow 显示并聚焦主窗口(从托盘恢复)
  316. func handleShowWindow(c *gin.Context) {
  317. showMainWindow()
  318. c.JSON(http.StatusOK, gin.H{"ok": true})
  319. }
  320. // handleWindowCompact 窗口收拢/还原(与双击手柄等效)。
  321. // 返回当前是否处于收拢(仅手柄)状态。
  322. func handleWindowCompact(c *gin.Context) {
  323. isCompact := (&SettingsService{}).ToggleWindowCompact()
  324. c.JSON(http.StatusOK, gin.H{"ok": true, "compact": isCompact})
  325. }
  326. // handleGetSettings 返回当前配置
  327. func handleGetSettings(c *gin.Context) {
  328. c.JSON(http.StatusOK, loadSettings())
  329. }
  330. // handleSaveSettings 保存配置并立即生效
  331. func handleSaveSettings(c *gin.Context) {
  332. var settings AppSettings
  333. if err := c.ShouldBindJSON(&settings); err != nil {
  334. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  335. return
  336. }
  337. settings = normalizeSettings(settings)
  338. settings = mergeRuntimeState(settings) // 保留自动保存的窗口尺寸与滚动条位置
  339. if err := saveSettings(settings); err != nil {
  340. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  341. return
  342. }
  343. applySettings(settings)
  344. c.JSON(http.StatusOK, settings) // 返回校正后的配置
  345. }
  346. // handleGetStocks 获取股票行情;支持 ?codes=sh600519,sz000001 临时指定代码
  347. func handleGetStocks(c *gin.Context) {
  348. codes := loadSettings().StockCodes
  349. if query := c.Query("codes"); query != "" {
  350. codes = nil
  351. for _, raw := range strings.Split(query, ",") {
  352. if code := normalizeStockCode(raw); code != "" {
  353. codes = append(codes, code)
  354. }
  355. }
  356. }
  357. quotes, err := fetchStockQuotes(codes)
  358. if err != nil {
  359. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  360. return
  361. }
  362. c.JSON(http.StatusOK, gin.H{"codes": codes, "quotes": quotes})
  363. }
  364. // handleScreenshot 截取屏幕并返回 PNG 数据 URI。
  365. // 支持 ?display=N 指定显示器(0 起);缺省或 -1 截取全部屏幕。
  366. func handleScreenshot(c *gin.Context) {
  367. idx := -1
  368. if v := c.Query("display"); v != "" {
  369. if n, err := strconv.Atoi(v); err == nil {
  370. idx = n
  371. }
  372. }
  373. dataURI, err := captureScreen(idx)
  374. if err != nil {
  375. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  376. return
  377. }
  378. c.JSON(http.StatusOK, gin.H{"image": dataURI, "display": idx})
  379. }
  380. // ------------------------------------------------------------------------
  381. // 文件上传 / 下载(需密码)
  382. //
  383. // 上传:POST /api/upload 表单字段 password(密码)、file(文件)。
  384. // 密码正确才保存到 uploadDir 目录;返回文件 URL 供二维码展示。
  385. // 下载:GET /api/download/:filename?password=xxx 校验密码后返回文件内容。
  386. // ------------------------------------------------------------------------
  387. // uploadDirPath 返回上传保存目录:配置为空时回退到用户配置目录下 uploads/。
  388. func uploadDirPath() string {
  389. dir := strings.TrimSpace(loadSettings().UploadDir)
  390. if dir != "" {
  391. return dir
  392. }
  393. cfg, err := os.UserConfigDir()
  394. if err != nil {
  395. return "." // 兜底:当前目录
  396. }
  397. return filepath.Join(cfg, "TengTuToolbox", "uploads")
  398. }
  399. // checkUploadPassword 校验上传密码(常数时间比较,防时序侧信道)。
  400. // 未设置密码时允许访问(与「空密码=不启用」语义一致)。
  401. func checkUploadPassword(pwd string) bool {
  402. expected := loadSettings().UploadPassword
  403. if strings.TrimSpace(expected) == "" {
  404. return true // 未设置密码:默认放行(用户未启用该功能)
  405. }
  406. return subtle.ConstantTimeCompare([]byte(pwd), []byte(expected)) == 1
  407. }
  408. // handleUpload 处理文件上传:密码正确才落盘,返回下载 URL 与文件信息。
  409. func handleUpload(c *gin.Context) {
  410. // 1) 校验密码(表单字段 password)
  411. pwd := c.PostForm("password")
  412. if !checkUploadPassword(pwd) {
  413. c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
  414. return
  415. }
  416. // 2) 读取上传文件
  417. fileHeader, err := c.FormFile("file")
  418. if err != nil {
  419. c.JSON(http.StatusBadRequest, gin.H{"error": "缺少文件字段 file"})
  420. return
  421. }
  422. if fileHeader.Size <= 0 {
  423. c.JSON(http.StatusBadRequest, gin.H{"error": "文件为空"})
  424. return
  425. }
  426. // 3) 校验文件大小:上限由配置「上传大小上限」决定(默认 512MB)
  427. maxMB := loadSettings().UploadMaxSize
  428. if maxMB <= 0 {
  429. maxMB = 512
  430. }
  431. maxUploadSize := int64(maxMB) << 20 // MB -> 字节
  432. if fileHeader.Size > maxUploadSize {
  433. c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("文件过大,上限 %dMB", maxMB)})
  434. return
  435. }
  436. // 4) 构造保存路径:仅用文件名(去路径),避免路径穿越
  437. dir := uploadDirPath()
  438. if err := os.MkdirAll(dir, 0o755); err != nil {
  439. c.JSON(http.StatusInternalServerError, gin.H{"error": "无法创建上传目录: " + err.Error()})
  440. return
  441. }
  442. origBase := filepath.Base(strings.ReplaceAll(fileHeader.Filename, "\\", "/"))
  443. if origBase == "." || origBase == "" {
  444. origBase = "upload.bin"
  445. }
  446. // 5) 落盘:存储文件名用「时间戳+随机数+原扩展名」,不可推测且天然唯一,避免覆盖与遍历。
  447. // zip 内条目保留原文件名,下载者解压后仍能看到原始文件名。
  448. storedName := newStoredName(origBase)
  449. final := filepath.Join(dir, storedName)
  450. if err := c.SaveUploadedFile(fileHeader, final); err != nil {
  451. c.JSON(http.StatusInternalServerError, gin.H{"error": "保存文件失败: " + err.Error()})
  452. return
  453. }
  454. // 6) 安全处理:把上传的原文件压缩为 zip(zip 内保留原文件名,文件名同样用时间戳+随机数),
  455. // 压缩成功后删除原文件,之后仅提供 zip 下载,避免可执行文件等被直接下载。
  456. zipName := newStoredName(origBase + ".zip")
  457. zipPath := filepath.Join(dir, zipName)
  458. if err := zipFile(final, zipPath, origBase); err != nil {
  459. // 压缩失败:删除原文件并报错,避免遗留未压缩文件
  460. os.Remove(final)
  461. c.JSON(http.StatusInternalServerError, gin.H{"error": "压缩文件失败: " + err.Error()})
  462. return
  463. }
  464. os.Remove(final) // 压缩成功,删除原文件
  465. // 7) 返回下载 URL(指向 zip,相对路径,前端拼完整地址)与文件信息
  466. savedName := filepath.Base(zipPath)
  467. downloadURL := "/api/download/" + url.PathEscape(savedName)
  468. fmt.Fprintf(apiLogRing, "[SYS] 文件已上传并压缩: %s -> %s (%d 字节)\n", origBase, savedName, fileHeader.Size)
  469. c.JSON(http.StatusOK, gin.H{
  470. "ok": true,
  471. "filename": origBase,
  472. "size": fileHeader.Size,
  473. "downloadUrl": downloadURL,
  474. })
  475. }
  476. // newStoredName 生成存储文件名:时间戳_6位随机数+原扩展名。
  477. // 扩展名做白名单过滤(仅保留字母数字,最长 10),防止可疑后缀。
  478. func newStoredName(orig string) string {
  479. ext := filepath.Ext(orig)
  480. ext = strings.Map(func(r rune) rune {
  481. if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '.' {
  482. return r
  483. }
  484. return -1
  485. }, ext)
  486. if len(ext) > 10 {
  487. ext = ext[:10]
  488. }
  489. ts := time.Now().Format("20060102_150405")
  490. rnd := fmt.Sprintf("%06d", cryptoRandInt(1000000))
  491. return fmt.Sprintf("%s_%s%s", ts, rnd, ext)
  492. }
  493. // cryptoRandInt 返回 [0, n) 的随机整数(crypto/rand),失败时回退 time 纳秒。
  494. func cryptoRandInt(n int) int {
  495. var b [8]byte
  496. if _, err := rand.Read(b[:]); err != nil {
  497. return int(time.Now().UnixNano() % int64(n))
  498. }
  499. v := int64(binary.BigEndian.Uint64(b[:]))
  500. if v < 0 {
  501. v = -v
  502. }
  503. return int(v % int64(n))
  504. }
  505. // zipFile 把 src 文件压缩为 dst zip,zip 内条目名用 name(一般取原文件名)。
  506. func zipFile(src, dst, name string) error {
  507. in, err := os.Open(src)
  508. if err != nil {
  509. return err
  510. }
  511. defer in.Close()
  512. out, err := os.Create(dst)
  513. if err != nil {
  514. return err
  515. }
  516. defer out.Close()
  517. zw := zip.NewWriter(out)
  518. defer zw.Close()
  519. w, err := zw.Create(name)
  520. if err != nil {
  521. return err
  522. }
  523. _, err = io.Copy(w, in)
  524. return err
  525. }
  526. // handleDownload 处理文件下载:密码正确才返回文件内容。
  527. func handleDownload(c *gin.Context) {
  528. if !checkUploadPassword(c.Query("password")) {
  529. c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
  530. return
  531. }
  532. name := filepath.Base(strings.ReplaceAll(c.Param("filename"), "\\", "/"))
  533. if name == "." || name == "" {
  534. c.JSON(http.StatusBadRequest, gin.H{"error": "文件名无效"})
  535. return
  536. }
  537. path := filepath.Join(uploadDirPath(), name)
  538. if _, err := os.Stat(path); err != nil {
  539. c.JSON(http.StatusNotFound, gin.H{"error": "文件不存在"})
  540. return
  541. }
  542. c.FileAttachment(path, name)
  543. }
  544. // ------------------------------------------------------------------------
  545. // 客户端上传页:手机/其他设备在浏览器中访问 http://<服务地址>/upload,
  546. // 输入密码并选择文件即可上传到本机,上传成功显示下载二维码。
  547. // ------------------------------------------------------------------------
  548. const clientUploadHTML = `<!DOCTYPE html>
  549. <html lang="zh-CN">
  550. <head>
  551. <meta charset="UTF-8">
  552. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  553. <title>腾图工具箱 · 文件上传</title>
  554. <style>
  555. * { box-sizing: border-box; margin: 0; padding: 0; }
  556. body {
  557. min-height: 100vh; display: flex; align-items: center; justify-content: center;
  558. font-family: -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "PingFang SC", "Microsoft YaHei", sans-serif;
  559. background: linear-gradient(160deg, #0b0e1d 0%, #1a1030 100%); color: #e9ecf5; padding: 20px;
  560. }
  561. .card {
  562. width: 100%; max-width: 400px; background: rgba(255,255,255,0.05);
  563. border: 1px solid rgba(255,255,255,0.12); border-radius: 16px; padding: 26px 24px;
  564. box-shadow: 0 10px 40px rgba(0,0,0,0.45); backdrop-filter: blur(6px);
  565. }
  566. h1 { font-size: 20px; text-align: center; margin-bottom: 6px; }
  567. .sub { text-align: center; color: #8b93a7; font-size: 13px; margin-bottom: 20px; }
  568. label { display: block; font-size: 13px; color: #b8bfd0; margin: 14px 0 6px; }
  569. input[type=password], input[type=file] {
  570. width: 100%; padding: 11px 12px; border-radius: 10px;
  571. border: 1px solid rgba(255,255,255,0.16); background: rgba(255,255,255,0.06);
  572. color: #e9ecf5; font-size: 15px;
  573. }
  574. input[type=file] { color: #8b93a7; padding: 8px; }
  575. button {
  576. width: 100%; margin-top: 20px; padding: 12px; border: 0; border-radius: 10px;
  577. background: linear-gradient(135deg, #ff5a4d, #ff2d72); color: #fff; font-size: 16px; font-weight: 600;
  578. cursor: pointer;
  579. }
  580. button:disabled { opacity: 0.6; cursor: default; }
  581. .progress { height: 6px; border-radius: 3px; background: rgba(255,255,255,0.12); margin-top: 16px; overflow: hidden; display: none; }
  582. .progress .bar { height: 100%; width: 0; background: linear-gradient(90deg, #ff5a4d, #ff2d72); transition: width .15s; }
  583. .result { margin-top: 18px; text-align: center; display: none; }
  584. .result img { width: 200px; height: 200px; border-radius: 12px; background: #fff; padding: 8px; margin-top: 14px; }
  585. .result .fname { margin-top: 10px; font-size: 14px; word-break: break-all; }
  586. .result .dllink {
  587. display: inline-block; margin-top: 8px; padding: 9px 18px; border-radius: 8px;
  588. background: rgba(255,255,255,0.10); border: 1px solid rgba(255,255,255,0.18);
  589. color: #4f8cff; font-size: 14px; text-decoration: none; word-break: break-all; max-width: 100%;
  590. }
  591. .result .dllink:hover { background: rgba(255,255,255,0.16); }
  592. .msg { margin-top: 12px; font-size: 13px; text-align: center; color: #ff9a9a; min-height: 18px; }
  593. </style>
  594. </head>
  595. <body>
  596. <div class="card">
  597. <h1>文件上传</h1>
  598. <div class="sub">腾图工具箱 · 客户端上传</div>
  599. <label>上传密码</label>
  600. <input type="password" id="pwd" placeholder="请输入上传密码" autocomplete="off">
  601. <label>选择文件</label>
  602. <input type="file" id="file">
  603. <button id="btn">上传</button>
  604. <div class="progress"><div class="bar" id="bar"></div></div>
  605. <div class="msg" id="msg"></div>
  606. <div class="result" id="result">
  607. <div class="fname" id="fname"></div>
  608. <a class="dllink" id="dllink" href="#" target="_blank" rel="noopener"></a>
  609. <img id="qr" alt="下载二维码">
  610. </div>
  611. </div>
  612. <script>
  613. var pwd = document.getElementById('pwd');
  614. var file = document.getElementById('file');
  615. var btn = document.getElementById('btn');
  616. var bar = document.getElementById('bar');
  617. var msg = document.getElementById('msg');
  618. var result = document.getElementById('result');
  619. var qr = document.getElementById('qr');
  620. var fname = document.getElementById('fname');
  621. var dllink = document.getElementById('dllink');
  622. function showMsg(t, err) { msg.textContent = t; msg.style.color = err ? '#ff9a9a' : '#3ddc84'; }
  623. btn.addEventListener('click', function () {
  624. var f = file.files && file.files[0];
  625. if (!f) { showMsg('请先选择文件', true); return; }
  626. btn.disabled = true; btn.textContent = '上传中…';
  627. result.style.display = 'none'; showMsg('', false);
  628. var progress = document.querySelector('.progress'); progress.style.display = 'block'; bar.style.width = '0%';
  629. var fd = new FormData(); fd.append('password', pwd.value.trim()); fd.append('file', f);
  630. var xhr = new XMLHttpRequest();
  631. xhr.open('POST', '/api/upload');
  632. xhr.upload.onprogress = function (e) { if (e.lengthComputable) bar.style.width = Math.round(e.loaded / e.total * 100) + '%'; };
  633. xhr.onload = function () {
  634. btn.disabled = false; btn.textContent = '上传';
  635. var data = {};
  636. try { data = JSON.parse(xhr.responseText); } catch (_) {}
  637. if (xhr.status >= 200 && xhr.status < 300 && data.ok) {
  638. var dl = '/api/download/' + encodeURIComponent(data.filename) + '?password=' + encodeURIComponent(pwd.value.trim());
  639. var full = location.origin + dl;
  640. fname.textContent = data.filename + '(' + data.size + ' 字节)';
  641. dllink.href = full;
  642. dllink.textContent = full; // 下载地址
  643. qr.src = '/api/qr?text=' + encodeURIComponent(full) + '&size=256';
  644. result.style.display = 'block';
  645. showMsg('上传成功', false);
  646. } else {
  647. showMsg(data.error || ('上传失败(HTTP ' + xhr.status + ')'), true);
  648. }
  649. };
  650. xhr.onerror = function () { btn.disabled = false; btn.textContent = '上传'; showMsg('网络错误,上传失败', true); };
  651. xhr.send(fd);
  652. });
  653. </script>
  654. </body>
  655. </html>
  656. `
  657. // handleUploadPage 返回客户端上传页 HTML(供手机等设备访问)
  658. func handleUploadPage(c *gin.Context) {
  659. c.Header("Content-Type", "text/html; charset=utf-8")
  660. c.String(http.StatusOK, clientUploadHTML)
  661. }
  662. // handleQRImage 生成二维码图片:GET /api/qr?text=xxx&size=300
  663. // 返回真实 PNG 图片字节(供客户端上传页 <img src> 直接加载)。
  664. func handleQRImage(c *gin.Context) {
  665. text := c.Query("text")
  666. if text == "" {
  667. c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 text 参数"})
  668. return
  669. }
  670. size, _ := strconv.Atoi(c.Query("size"))
  671. if size <= 0 {
  672. size = 300
  673. }
  674. uri, err := GenerateQRCode(text, size)
  675. if err != nil {
  676. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  677. return
  678. }
  679. // GenerateQRCode 返回 data URI,剥离前缀后得到原始 PNG 字节
  680. const prefix = "data:image/png;base64,"
  681. if strings.HasPrefix(uri, prefix) {
  682. if raw, derr := base64.StdEncoding.DecodeString(strings.TrimPrefix(uri, prefix)); derr == nil {
  683. c.Data(http.StatusOK, "image/png", raw)
  684. return
  685. }
  686. }
  687. c.String(http.StatusOK, uri)
  688. }