| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "sort" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/host" |
| 15 | ) |
| 16 | |
| 17 | type SavedDownload struct { |
| 18 | InstanceID string `json:"instance_id,omitempty"` |
| 19 | ID string `json:"id"` |
| 20 | Name string `json:"name"` |
| 21 | Path string `json:"path"` |
| 22 | SavedAt time.Time `json:"saved_at"` |
| 23 | } |
| 24 | |
| 25 | func savedDownloadPath(profile, id string) string { |
| 26 | return filepath.Join(profile, "browser-downloads", id+".json") |
| 27 | } |
| 28 | func readSavedDownload(profile, id string) (SavedDownload, error) { |
| 29 | var saved SavedDownload |
| 30 | if !browserFileID.MatchString(id) { |
| 31 | return saved, errors.New("下载标识无效") |
| 32 | } |
| 33 | path := savedDownloadPath(profile, id) |
| 34 | if err := host.CheckPrivateFile(path); err != nil { |
| 35 | return saved, err |
| 36 | } |
| 37 | f, err := os.Open(path) |
| 38 | if err != nil { |
| 39 | return saved, err |
| 40 | } |
| 41 | defer f.Close() |
| 42 | if err = json.NewDecoder(io.LimitReader(f, 16384)).Decode(&saved); err != nil { |
| 43 | return saved, err |
| 44 | } |
| 45 | if saved.ID != id || !filepath.IsAbs(saved.Path) || !browserDownloadName(saved.Name) { |
| 46 | return saved, errors.New("下载位置记录无效") |
| 47 | } |
| 48 | return saved, nil |
| 49 | } |
| 50 | func rememberDownload(profile string, saved SavedDownload, firstOnly bool) error { |
| 51 | if !browserFileID.MatchString(saved.ID) { |
| 52 | return errors.New("下载标识无效") |
| 53 | } |
| 54 | directory := filepath.Join(profile, "browser-downloads") |
| 55 | if err := host.EnsurePrivateDir(directory); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | lock, err := os.OpenFile(filepath.Join(directory, ".lock"), os.O_CREATE|os.O_RDWR, 0600) |
| 59 | if err != nil { |
| 60 | return err |
| 61 | } |
| 62 | defer lock.Close() |
| 63 | for attempts := 0; ; attempts++ { |
| 64 | if err = lockController(lock); err == nil { |
| 65 | break |
| 66 | } |
| 67 | if attempts >= 40 { |
| 68 | return errors.New("下载位置正在更新,请重试") |
| 69 | } |
| 70 | time.Sleep(25 * time.Millisecond) |
| 71 | } |
| 72 | defer unlockController(lock) |
| 73 | if firstOnly { |
| 74 | if _, err = readSavedDownload(profile, saved.ID); err == nil { |
| 75 | return nil |
| 76 | } |
| 77 | } |
| 78 | saved.SavedAt = time.Now().UTC() |
| 79 | return writePrivate(savedDownloadPath(profile, saved.ID), saved) |
| 80 | } |
| 81 | func (s *Server) savedBrowserDownloads(w http.ResponseWriter, r *http.Request) { |
| 82 | serveSavedDownloads(w, s.profile) |
| 83 | } |
| 84 | |
| 85 | func serveSavedDownloads(w http.ResponseWriter, profile string) { |
| 86 | entries, err := os.ReadDir(filepath.Join(profile, "browser-downloads")) |
| 87 | if err != nil && !os.IsNotExist(err) { |
| 88 | http.Error(w, "无法读取已保存的位置", 500) |
| 89 | return |
| 90 | } |
| 91 | records := []SavedDownload{} |
| 92 | for _, entry := range entries { |
| 93 | name := entry.Name() |
| 94 | if len(name) != 41 { |
| 95 | continue |
| 96 | } |
| 97 | if saved, err := readSavedDownload(profile, name[:36]); err == nil { |
| 98 | records = append(records, saved) |
| 99 | } |
| 100 | } |
| 101 | sort.Slice(records, func(i, j int) bool { return records[i].SavedAt.After(records[j].SavedAt) }) |
| 102 | if len(records) > 100 { |
| 103 | records = records[:100] |
| 104 | } |
| 105 | jsonReply(w, records) |
| 106 | } |
| 107 | |
| 108 | |
| 109 | |
| 110 | func BrowserFile(configPath, action, id, destination string) (SavedDownload, error) { |
| 111 | return BrowserFileForConnection(configPath, "", action, id, destination) |
| 112 | } |
| 113 | |
| 114 | func BrowserFileForConnection(configPath, connectionID, action, id, destination string) (SavedDownload, error) { |
| 115 | var result SavedDownload |
| 116 | if !browserFileID.MatchString(id) || (action != "save" && action != "open" && action != "reveal") { |
| 117 | return result, errors.New("下载操作无效") |
| 118 | } |
| 119 | client, err := connectController(filepath.Dir(configPath)) |
| 120 | if err != nil { |
| 121 | return result, err |
| 122 | } |
| 123 | defer client.close() |
| 124 | client.client.Timeout = 30 * time.Minute |
| 125 | entry, _ := url.Parse(client.launch.URL) |
| 126 | status, err := client.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil) |
| 127 | if err != nil || status != 200 { |
| 128 | return result, errors.New("无法连接下载会话") |
| 129 | } |
| 130 | connection, err := client.bindConnection(connectionID) |
| 131 | if err != nil { |
| 132 | return result, err |
| 133 | } |
| 134 | profile := filepath.Dir(configPath) |
| 135 | if connection.DesktopGateway && connection.Mode == "local" { |
| 136 | profile = filepath.Dir(profile) |
| 137 | } |
| 138 | saveProfile, err := clientDownloadProfile(profile, connection) |
| 139 | if err != nil { |
| 140 | return result, err |
| 141 | } |
| 142 | var item browserDownloadInfo |
| 143 | if connection.Mode == "remote" && action != "save" { |
| 144 | saved, readErr := readSavedDownload(saveProfile, id) |
| 145 | if readErr != nil || saved.InstanceID != connection.InstanceID { |
| 146 | return result, errors.New("请先将文件另存为到本机,再打开或显示所在位置") |
| 147 | } |
| 148 | result = saved |
| 149 | } else { |
| 150 | status, err = client.call("GET", "/api/browser/files/downloads/"+id, nil, &item) |
| 151 | if err != nil || status != 200 { |
| 152 | return result, errors.New("下载文件不可用,请确认 Cage 已解锁且下载已完成") |
| 153 | } |
| 154 | result = SavedDownload{ID: id, Name: item.Name, Path: item.Path} |
| 155 | if connection.Mode == "remote" { |
| 156 | result.Path = "" |
| 157 | result.InstanceID = connection.InstanceID |
| 158 | } |
| 159 | } |
| 160 | if action == "save" { |
| 161 | if !filepath.IsAbs(destination) || filepath.Base(destination) == "." { |
| 162 | return result, errors.New("保存位置无效") |
| 163 | } |
| 164 | parent, resolveErr := filepath.EvalSymlinks(filepath.Dir(destination)) |
| 165 | if resolveErr != nil { |
| 166 | return result, errors.New("所选保存文件夹已不可用") |
| 167 | } |
| 168 | destination = filepath.Join(parent, filepath.Base(destination)) |
| 169 | request, _ := http.NewRequest("GET", client.origin+"/api/browser/files/downloads/"+id+"/content", nil) |
| 170 | request.Header.Set("Origin", client.origin) |
| 171 | client.client.Timeout = 30 * time.Minute |
| 172 | response, err := client.client.Do(request) |
| 173 | if err != nil { |
| 174 | return result, errors.New("无法读取下载文件,请重试") |
| 175 | } |
| 176 | defer response.Body.Close() |
| 177 | if response.StatusCode != 200 { |
| 178 | return result, errors.New("下载源文件已不可用,请从原网页重新下载") |
| 179 | } |
| 180 | if err = saveDownloadedStream(destination, response.Body, response.ContentLength); err != nil { |
| 181 | return result, err |
| 182 | } |
| 183 | result.Path = destination |
| 184 | result.Name = filepath.Base(destination) |
| 185 | if err = rememberDownload(saveProfile, result, false); err != nil { |
| 186 | return result, err |
| 187 | } |
| 188 | } else { |
| 189 | file, err := openDownloadedFile(result.Path) |
| 190 | if err != nil { |
| 191 | return result, errors.New("文件已移动、删除或无法访问") |
| 192 | } |
| 193 | file.Close() |
| 194 | if err = openHostFile(result.Path, action); err != nil { |
| 195 | return result, err |
| 196 | } |
| 197 | } |
| 198 | return result, nil |
| 199 | } |
| 200 | |
| 201 | func saveDownloadedStream(destination string, source io.Reader, size int64) error { |
| 202 | if existing, err := os.Lstat(destination); err == nil && !existing.Mode().IsRegular() { |
| 203 | return errors.New("请选择普通文件保存位置") |
| 204 | } |
| 205 | temporary, err := os.CreateTemp(filepath.Dir(destination), ".cage-download-*.part") |
| 206 | if err != nil { |
| 207 | return errors.New("无法写入所选文件夹") |
| 208 | } |
| 209 | defer os.Remove(temporary.Name()) |
| 210 | count, err := io.Copy(temporary, source) |
| 211 | if err == nil && size >= 0 && count != size { |
| 212 | err = io.ErrUnexpectedEOF |
| 213 | } |
| 214 | if err == nil { |
| 215 | err = temporary.Sync() |
| 216 | } |
| 217 | closeErr := temporary.Close() |
| 218 | if err == nil { |
| 219 | err = closeErr |
| 220 | } |
| 221 | if err != nil { |
| 222 | return errors.New("保存未完成,原文件未覆盖;请检查空间或连接后重试") |
| 223 | } |
| 224 | if err = os.Rename(temporary.Name(), destination); err != nil { |
| 225 | return errors.New("无法保存到所选位置,原文件未覆盖") |
| 226 | } |
| 227 | return nil |
| 228 | } |