Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
510 lines (442 loc) · 14.4 KB
/
Copy pathclient.go
File metadata and controls
510 lines (442 loc) · 14.4 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
package aria2
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
// RPCError is a JSON-RPC error object returned by aria2.
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *RPCError) Error() string { return fmt.Sprintf("aria2 rpc error %d: %s", e.Code, e.Message) }
// ErrClosed is returned for calls made after the connection is gone.
var ErrClosed = errors.New("aria2: connection closed")
type request struct {
JSONRPC string `json:"jsonrpc"`
ID string `json:"id"`
Method string `json:"method"`
Params []any `json:"params"`
}
type response struct {
ID string `json:"id"`
Result json.RawMessage `json:"result"`
Error *RPCError `json:"error"`
Method string `json:"method"` // set for notifications
Params json.RawMessage `json:"params"`
}
// Client is a thread-safe aria2 JSON-RPC client over WebSocket.
type Client struct {
url string
secret string
conn *websocket.Conn
writeMu sync.Mutex
pendingMu sync.Mutex
pending map[string]chan *response
nextID atomic.Uint64
notifs chan Notification
closeOnce sync.Once
done chan struct{}
errMu sync.Mutex
err error
}
// Dial connects to an aria2 RPC endpoint, e.g. "ws://127.0.0.1:6800/jsonrpc".
// secret may be empty when the daemon runs without --rpc-secret.
func Dial(ctx context.Context, url, secret string) (*Client, error) {
dialer := websocket.Dialer{HandshakeTimeout: 5 * time.Second}
conn, resp, err := dialer.DialContext(ctx, url, http.Header{})
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
if err != nil {
return nil, fmt.Errorf("aria2: dial %s: %w", url, err)
}
c := &Client{
url: url,
secret: secret,
conn: conn,
pending: make(map[string]chan *response),
notifs: make(chan Notification, 64),
done: make(chan struct{}),
}
go c.readLoop()
return c, nil
}
// URL returns the endpoint this client is connected to.
func (c *Client) URL() string { return c.url }
// Notifications returns the channel of asynchronous aria2 events.
// The channel is closed when the connection dies.
func (c *Client) Notifications() <-chan Notification { return c.notifs }
// Done is closed when the connection is torn down.
func (c *Client) Done() <-chan struct{} { return c.done }
// Err reports why the connection closed, if it did.
func (c *Client) Err() error {
c.errMu.Lock()
defer c.errMu.Unlock()
return c.err
}
// Close tears down the connection.
func (c *Client) Close() error {
c.shutdown(ErrClosed)
return nil
}
func (c *Client) shutdown(err error) {
c.closeOnce.Do(func() {
c.errMu.Lock()
c.err = err
c.errMu.Unlock()
close(c.done)
c.conn.Close()
c.pendingMu.Lock()
for id, ch := range c.pending {
close(ch)
delete(c.pending, id)
}
c.pendingMu.Unlock()
close(c.notifs)
})
}
func (c *Client) readLoop() {
for {
_, data, err := c.conn.ReadMessage()
if err != nil {
c.shutdown(err)
return
}
var resp response
if err := json.Unmarshal(data, &resp); err != nil {
continue
}
if resp.Method != "" { // notification
for _, gid := range parseNotificationGIDs(resp.Params) {
select {
case c.notifs <- Notification{Method: resp.Method, GID: gid}:
default: // never block the read loop
}
}
continue
}
c.pendingMu.Lock()
ch, ok := c.pending[resp.ID]
if ok {
delete(c.pending, resp.ID)
}
c.pendingMu.Unlock()
if ok {
ch <- &resp
close(ch)
}
}
}
// Call invokes an arbitrary RPC method. The secret token is prepended
// automatically for aria2.* methods. result may be nil.
func (c *Client) Call(ctx context.Context, method string, result any, params ...any) error {
select {
case <-c.done:
return ErrClosed
default:
}
full := params
if c.secret != "" && len(method) > 6 && method[:6] == "aria2." {
full = append([]any{"token:" + c.secret}, params...)
}
if full == nil {
full = []any{}
}
id := fmt.Sprintf("%d", c.nextID.Add(1))
req := request{JSONRPC: "2.0", ID: id, Method: method, Params: full}
ch := make(chan *response, 1)
c.pendingMu.Lock()
c.pending[id] = ch
c.pendingMu.Unlock()
c.writeMu.Lock()
err := c.conn.WriteJSON(req)
c.writeMu.Unlock()
if err != nil {
c.pendingMu.Lock()
delete(c.pending, id)
c.pendingMu.Unlock()
return fmt.Errorf("aria2: write: %w", err)
}
select {
case <-ctx.Done():
c.pendingMu.Lock()
delete(c.pending, id)
c.pendingMu.Unlock()
return ctx.Err()
case <-c.done:
return ErrClosed
case resp, ok := <-ch:
if !ok || resp == nil {
return ErrClosed
}
if resp.Error != nil {
return resp.Error
}
if result != nil {
if err := json.Unmarshal(resp.Result, result); err != nil {
return fmt.Errorf("aria2: decode result of %s: %w", method, err)
}
}
return nil
}
}
// ---------------------------------------------------------------------------
// Adding downloads
// ---------------------------------------------------------------------------
// AddURI queues a download from one or more mirror URIs (HTTP/HTTPS/FTP/SFTP/magnet).
func (c *Client) AddURI(ctx context.Context, uris []string, opts Options) (string, error) {
var gid string
if opts == nil {
opts = Options{}
}
err := c.Call(ctx, "aria2.addUri", &gid, uris, opts)
return gid, err
}
// AddTorrent uploads raw .torrent file bytes. webSeeds may be nil.
func (c *Client) AddTorrent(ctx context.Context, torrent []byte, webSeeds []string, opts Options) (string, error) {
var gid string
if opts == nil {
opts = Options{}
}
if webSeeds == nil {
webSeeds = []string{}
}
err := c.Call(ctx, "aria2.addTorrent", &gid, base64.StdEncoding.EncodeToString(torrent), webSeeds, opts)
return gid, err
}
// AddTorrentFile reads a .torrent file from disk and queues it.
func (c *Client) AddTorrentFile(ctx context.Context, path string, opts Options) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
return c.AddTorrent(ctx, data, nil, opts)
}
// AddMetalink uploads raw .metalink/.meta4 file bytes. Returns the new GIDs.
func (c *Client) AddMetalink(ctx context.Context, metalink []byte, opts Options) ([]string, error) {
var gids []string
if opts == nil {
opts = Options{}
}
err := c.Call(ctx, "aria2.addMetalink", &gids, base64.StdEncoding.EncodeToString(metalink), opts)
return gids, err
}
// AddMetalinkFile reads a metalink file from disk and queues it.
func (c *Client) AddMetalinkFile(ctx context.Context, path string, opts Options) ([]string, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return c.AddMetalink(ctx, data, opts)
}
// ---------------------------------------------------------------------------
// Controlling downloads
// ---------------------------------------------------------------------------
// Pause pauses a download.
func (c *Client) Pause(ctx context.Context, gid string) error {
return c.Call(ctx, "aria2.pause", nil, gid)
}
// ForcePause pauses without contacting trackers/servers.
func (c *Client) ForcePause(ctx context.Context, gid string) error {
return c.Call(ctx, "aria2.forcePause", nil, gid)
}
// PauseAll pauses every download.
func (c *Client) PauseAll(ctx context.Context) error {
return c.Call(ctx, "aria2.pauseAll", nil)
}
// Unpause resumes a paused download.
func (c *Client) Unpause(ctx context.Context, gid string) error {
return c.Call(ctx, "aria2.unpause", nil, gid)
}
// UnpauseAll resumes every paused download.
func (c *Client) UnpauseAll(ctx context.Context) error {
return c.Call(ctx, "aria2.unpauseAll", nil)
}
// Remove removes an active/waiting download (moves it to stopped).
func (c *Client) Remove(ctx context.Context, gid string) error {
return c.Call(ctx, "aria2.remove", nil, gid)
}
// ForceRemove removes without any cleanup steps.
func (c *Client) ForceRemove(ctx context.Context, gid string) error {
return c.Call(ctx, "aria2.forceRemove", nil, gid)
}
// RemoveDownloadResult erases a stopped download from aria2's memory.
func (c *Client) RemoveDownloadResult(ctx context.Context, gid string) error {
return c.Call(ctx, "aria2.removeDownloadResult", nil, gid)
}
// PurgeDownloadResult erases all completed/errored/removed downloads.
func (c *Client) PurgeDownloadResult(ctx context.Context) error {
return c.Call(ctx, "aria2.purgeDownloadResult", nil)
}
// ChangePosition moves a waiting download in the queue.
// how is one of "POS_SET", "POS_CUR", "POS_END".
func (c *Client) ChangePosition(ctx context.Context, gid string, pos int, how string) (int, error) {
var newPos int
err := c.Call(ctx, "aria2.changePosition", &newPos, gid, pos, how)
return newPos, err
}
// ---------------------------------------------------------------------------
// Querying
// ---------------------------------------------------------------------------
// TellStatus fetches full status for one download. keys narrows returned fields (nil = all).
func (c *Client) TellStatus(ctx context.Context, gid string, keys ...string) (Status, error) {
var st Status
var err error
if len(keys) > 0 {
err = c.Call(ctx, "aria2.tellStatus", &st, gid, keys)
} else {
err = c.Call(ctx, "aria2.tellStatus", &st, gid)
}
return st, err
}
// TellActive lists downloads currently in progress.
func (c *Client) TellActive(ctx context.Context) ([]Status, error) {
var list []Status
err := c.Call(ctx, "aria2.tellActive", &list)
return list, err
}
// TellWaiting lists queued/paused downloads.
func (c *Client) TellWaiting(ctx context.Context, offset, num int) ([]Status, error) {
var list []Status
err := c.Call(ctx, "aria2.tellWaiting", &list, offset, num)
return list, err
}
// TellStopped lists finished/errored/removed downloads.
func (c *Client) TellStopped(ctx context.Context, offset, num int) ([]Status, error) {
var list []Status
err := c.Call(ctx, "aria2.tellStopped", &list, offset, num)
return list, err
}
// GetURIs lists the URIs of a download.
func (c *Client) GetURIs(ctx context.Context, gid string) ([]URI, error) {
var list []URI
err := c.Call(ctx, "aria2.getUris", &list, gid)
return list, err
}
// GetFiles lists the files of a download.
func (c *Client) GetFiles(ctx context.Context, gid string) ([]File, error) {
var list []File
err := c.Call(ctx, "aria2.getFiles", &list, gid)
return list, err
}
// GetPeers lists BitTorrent peers of a download.
func (c *Client) GetPeers(ctx context.Context, gid string) ([]Peer, error) {
var list []Peer
err := c.Call(ctx, "aria2.getPeers", &list, gid)
return list, err
}
// GetServers lists currently connected HTTP/FTP servers of a download.
func (c *Client) GetServers(ctx context.Context, gid string) ([]ServerGroup, error) {
var list []ServerGroup
err := c.Call(ctx, "aria2.getServers", &list, gid)
return list, err
}
// GetGlobalStat returns overall transfer statistics.
func (c *Client) GetGlobalStat(ctx context.Context) (GlobalStat, error) {
var st GlobalStat
err := c.Call(ctx, "aria2.getGlobalStat", &st)
return st, err
}
// GetVersion returns the aria2 version and enabled features.
func (c *Client) GetVersion(ctx context.Context) (VersionInfo, error) {
var v VersionInfo
err := c.Call(ctx, "aria2.getVersion", &v)
return v, err
}
// GetSessionInfo returns the aria2 session id.
func (c *Client) GetSessionInfo(ctx context.Context) (SessionInfo, error) {
var s SessionInfo
err := c.Call(ctx, "aria2.getSessionInfo", &s)
return s, err
}
// ---------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------
// GetOption returns per-download options.
func (c *Client) GetOption(ctx context.Context, gid string) (Options, error) {
var o Options
err := c.Call(ctx, "aria2.getOption", &o, gid)
return o, err
}
// ChangeOption updates per-download options.
func (c *Client) ChangeOption(ctx context.Context, gid string, opts Options) error {
return c.Call(ctx, "aria2.changeOption", nil, gid, opts)
}
// GetGlobalOption returns daemon-wide options.
func (c *Client) GetGlobalOption(ctx context.Context) (Options, error) {
var o Options
err := c.Call(ctx, "aria2.getGlobalOption", &o)
return o, err
}
// ChangeGlobalOption updates daemon-wide options.
func (c *Client) ChangeGlobalOption(ctx context.Context, opts Options) error {
return c.Call(ctx, "aria2.changeGlobalOption", nil, opts)
}
// ---------------------------------------------------------------------------
// Session control
// ---------------------------------------------------------------------------
// SaveSession persists the current session to the --save-session file.
func (c *Client) SaveSession(ctx context.Context) error {
return c.Call(ctx, "aria2.saveSession", nil)
}
// Shutdown asks the daemon to exit gracefully.
func (c *Client) Shutdown(ctx context.Context) error {
return c.Call(ctx, "aria2.shutdown", nil)
}
// ForceShutdown asks the daemon to exit immediately.
func (c *Client) ForceShutdown(ctx context.Context) error {
return c.Call(ctx, "aria2.forceShutdown", nil)
}
// ---------------------------------------------------------------------------
// system.multicall
// ---------------------------------------------------------------------------
// MulticallCall describes one method invocation inside a batch.
type MulticallCall struct {
Method string `json:"methodName"`
Params []any `json:"params"`
}
// Multicall executes several methods in one round trip. Each result element
// is the raw JSON result for the corresponding call; per-call errors are
// returned in errs (nil when the call succeeded).
func (c *Client) Multicall(ctx context.Context, calls []MulticallCall) (results []json.RawMessage, errs []error, err error) {
prepared := make([]MulticallCall, len(calls))
for i, call := range calls {
p := call.Params
if c.secret != "" && len(call.Method) > 6 && call.Method[:6] == "aria2." {
p = append([]any{"token:" + c.secret}, p...)
}
if p == nil {
p = []any{}
}
prepared[i] = MulticallCall{Method: call.Method, Params: p}
}
var raw []json.RawMessage
if err := c.Call(ctx, "system.multicall", &raw, prepared); err != nil {
return nil, nil, err
}
results = make([]json.RawMessage, len(raw))
errs = make([]error, len(raw))
for i, item := range raw {
var asArray []json.RawMessage
if e := json.Unmarshal(item, &asArray); e == nil && len(asArray) == 1 {
results[i] = asArray[0]
continue
}
var rpcErr RPCError
if e := json.Unmarshal(item, &rpcErr); e == nil && rpcErr.Message != "" {
errs[i] = &rpcErr
continue
}
results[i] = item
}
return results, errs, nil
}