1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
package main
// Transmission RPC client.
//
// Spec: https://github.com/transmission/transmission/blob/main/docs/rpc-spec.md
//
// The one non-obvious part is the CSRF protection: the daemon rejects the first
// request with 409 and returns the session id to use in an X-Transmission-Session-Id
// header. We store it and retry. The id can expire at any time, so any request
// may get a 409 and must be prepared to redo this dance.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"go.opentelemetry.io/otel/trace"
)
type transmissionClient struct {
host string
port int
http *http.Client
mu sync.Mutex
sessionID string
}
func newTransmissionClient(host string, port int) *transmissionClient {
return &transmissionClient{
host: host,
port: port,
http: &http.Client{Timeout: 30 * time.Second},
}
}
// transmissionRequest is the RPC envelope.
type transmissionRequest struct {
Method string `json:"method"`
Arguments map[string]any `json:"arguments"`
Tag *int `json:"tag,omitempty"`
}
// transmissionResponse is the reply envelope. Arguments is left raw so each
// call site can decode the shape it expects.
type transmissionResponse struct {
Result string `json:"result"`
Arguments json.RawMessage `json:"arguments"`
Tag *int `json:"tag"`
}
func (c *transmissionClient) getSessionID() string {
c.mu.Lock()
defer c.mu.Unlock()
return c.sessionID
}
func (c *transmissionClient) setSessionID(id string) {
c.mu.Lock()
defer c.mu.Unlock()
c.sessionID = id
}
// do performs an RPC call, transparently handling the session id handshake.
func (c *transmissionClient) do(ctx context.Context, req transmissionRequest) (json.RawMessage, error) {
return inSpan1(ctx, "Transmission Request", func(ctx context.Context, span trace.Span) (json.RawMessage, error) {
attr(span, "transmission.method", req.Method)
if req.Arguments != nil {
attr(span, "transmission.arguments", req.Arguments)
}
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
url := fmt.Sprintf("http://%s:%d/transmission/rpc", c.host, c.port)
// At most two attempts: the second one carries a session id freshly
// obtained from a 409.
for attempt := 0; attempt < 2; attempt++ {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
if id := c.getSessionID(); id != "" {
httpReq.Header.Set("X-Transmission-Session-Id", id)
}
resp, err := c.http.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("contacting transmission at %s: %w", url, err)
}
respBody, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
return nil, readErr
}
switch resp.StatusCode {
case http.StatusConflict:
newID := resp.Header.Get("X-Transmission-Session-Id")
if newID == "" {
return nil, fmt.Errorf(`missing "X-Transmission-Session-Id" header in 409 response`)
}
event(span, "New Transmission Session ID")
c.setSessionID(newID)
continue
case http.StatusOK:
var out transmissionResponse
if err := json.Unmarshal(respBody, &out); err != nil {
return nil, fmt.Errorf("cannot parse transmission RPC response: %w", err)
}
if out.Result != "success" {
return nil, fmt.Errorf("transmission RPC error: %s", out.Result)
}
if len(out.Arguments) == 0 {
return nil, fmt.Errorf("transmission RPC error: no `arguments` field in response")
}
return out.Arguments, nil
default:
return nil, fmt.Errorf("transmission returned a non-200 response: %d: %s",
resp.StatusCode, truncate(string(respBody), 300))
}
}
return nil, fmt.Errorf("transmission kept asking for a new session id")
})
}
// torrentStatusInfo is the per-torrent status the UI shows.
type torrentStatusInfo struct {
TorrentHash string
// PercentDone is 0..100, rounded up, matching the Haskell Percentage type.
PercentDone int
}
// listTorrentsByHash asks for the given torrents only.
//
// Torrents that Transmission no longer knows about are simply absent from the
// reply; the caller uses that to detect deletions.
func (c *transmissionClient) listTorrentsByHash(ctx context.Context, hashes []string) (map[string]torrentStatusInfo, error) {
if len(hashes) == 0 {
return map[string]torrentStatusInfo{}, nil
}
args := map[string]any{
"ids": hashes,
"fields": []string{"hashString", "percentDone"},
}
raw, err := c.do(ctx, transmissionRequest{Method: "torrent-get", Arguments: args})
if err != nil {
return nil, err
}
var out struct {
Torrents []struct {
HashString string `json:"hashString"`
PercentDone float64 `json:"percentDone"`
} `json:"torrents"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return nil, err
}
res := make(map[string]torrentStatusInfo, len(out.Torrents))
for _, t := range out.Torrents {
res[t.HashString] = torrentStatusInfo{
TorrentHash: t.HashString,
PercentDone: percentage(t.PercentDone),
}
}
return res, nil
}
// percentage converts Transmission's 0..1 fraction to whole percent.
//
// Rounds up, as the Haskell `scientificPercentage` did, so that a torrent that
// has made any progress at all does not display as 0%.
func percentage(f float64) int {
if f < 0 {
return 0
}
if f > 1 {
return 100
}
p := int(f * 100)
if float64(p) < f*100 {
p++
}
return p
}
// addTorrent hands a .torrent file to Transmission and starts it.
//
// Transmission answers with either "torrent-added" or, if it already had it,
// "torrent-duplicate"; both carry the hash we need.
func (c *transmissionClient) addTorrent(ctx context.Context, torrentFile []byte) (hash string, name string, err error) {
args := map[string]any{
"metainfo": base64.StdEncoding.EncodeToString(torrentFile),
"paused": false,
}
raw, err := c.do(ctx, transmissionRequest{Method: "torrent-add", Arguments: args})
if err != nil {
return "", "", err
}
var out struct {
Added struct {
HashString string `json:"hashString"`
Name string `json:"name"`
} `json:"torrent-added"`
Duplicate struct {
HashString string `json:"hashString"`
Name string `json:"name"`
} `json:"torrent-duplicate"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return "", "", err
}
if out.Duplicate.HashString != "" {
return out.Duplicate.HashString, out.Duplicate.Name, nil
}
if out.Added.HashString != "" {
return out.Added.HashString, out.Added.Name, nil
}
return "", "", fmt.Errorf("transmission returned neither torrent-added nor torrent-duplicate")
}
// getAndUpdateTransmissionTorrentsStatus refreshes the status of the torrents we
// believe are in Transmission, and forgets the ones that are not there anymore.
//
// Returns whether our stored state was stale, and the current status by hash.
// When stale, the caller re-runs its query rather than rendering a table that
// mentions torrents that no longer exist.
func (a *app) getAndUpdateTransmissionTorrentsStatus(ctx context.Context, knownHashes []string) (stale bool, status map[string]torrentStatusInfo, err error) {
err = inSpan(ctx, "getAndUpdateTransmissionTorrentsStatus", func(ctx context.Context, span trace.Span) error {
actual, err := a.transmission.listTorrentsByHash(ctx, knownHashes)
if err != nil {
return err
}
status = actual
var gone []string
for _, h := range knownHashes {
if _, ok := actual[h]; !ok {
gone = append(gone, h)
}
}
if len(gone) == 0 {
event(span, "We know about all transmission hashes.")
return nil
}
attr(span, "db.delete-transmission-hashes", gone)
// Clearing torrent_file as well as the hash matches the Haskell
// version: a torrent removed from Transmission is treated as never
// having been downloaded, so the UI offers to fetch it again.
if _, err := a.pool.Exec(ctx, `
UPDATE redacted.torrents_json
SET transmission_torrent_hash = NULL,
torrent_file = NULL
WHERE transmission_torrent_hash = ANY ($1::text[])`, gone); err != nil {
return fmt.Errorf("clearing stale transmission hashes: %w", err)
}
stale = true
return nil
})
return stale, status, err
}
|