| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "path/filepath" |
| 7 | ) |
| 8 | |
| 9 | type connectionTransport struct { |
| 10 | base http.RoundTripper |
| 11 | id string |
| 12 | } |
| 13 | |
| 14 | func (t connectionTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 15 | copy := r.Clone(r.Context()) |
| 16 | copy.Header.Set(connectionHeader, t.id) |
| 17 | return t.base.RoundTrip(copy) |
| 18 | } |
| 19 | |
| 20 | func (t connectionTransport) CloseIdleConnections() { |
| 21 | if closer, ok := t.base.(interface{ CloseIdleConnections() }); ok { |
| 22 | closer.CloseIdleConnections() |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | func (c *controllerClient) bindConnection(expected string) (ClientContext, error) { |
| 30 | var current ClientContext |
| 31 | status, err := c.call("GET", "/api/client/context", nil, ¤t) |
| 32 | if err == nil && status == http.StatusNotFound && expected == "" { |
| 33 | return ClientContext{Mode: "local", ConnectionID: "local"}, nil |
| 34 | } |
| 35 | if err != nil || status != http.StatusOK { |
| 36 | return current, errors.New("无法核对当前文件传递连接") |
| 37 | } |
| 38 | if current.DesktopGateway && (expected == "" || current.Mode == "none") { |
| 39 | return current, errors.New("请先选择工作环境,再重新进行文件操作") |
| 40 | } |
| 41 | if current.Mode == "remote" && (expected == "" || current.State.State != "connected") { |
| 42 | return current, errors.New("远程连接不可用,请重新连接后选择文件") |
| 43 | } |
| 44 | if expected != "" && expected != current.ConnectionID { |
| 45 | return current, errors.New("连接已经切换,请在当前主机重新选择文件") |
| 46 | } |
| 47 | c.connectionID = current.ConnectionID |
| 48 | c.client.Transport = connectionTransport{base: c.client.Transport, id: current.ConnectionID} |
| 49 | return current, nil |
| 50 | } |
| 51 | |
| 52 | func clientDownloadProfile(profile string, current ClientContext) (string, error) { |
| 53 | if current.Mode != "remote" { |
| 54 | return profile, nil |
| 55 | } |
| 56 | if !remoteInstanceID.MatchString(current.InstanceID) { |
| 57 | return "", errors.New("远程实例身份无效") |
| 58 | } |
| 59 | return filepath.Join(profile, "remote-downloads", current.InstanceID), nil |
| 60 | } |