1
0

apiserver.go 27 KB

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