-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlibaria2.go
More file actions
301 lines (256 loc) · 7.88 KB
/
libaria2.go
File metadata and controls
301 lines (256 loc) · 7.88 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
// Copyright (C) 2019 Vincent Chueng (coolingfall@gmail.com).
package aria2go
/*
#cgo CXXFLAGS: -std=c++11 -I./aria2-lib/include
#cgo LDFLAGS: -L./aria2-lib/lib
#cgo LDFLAGS: -laria2 -lssh2 -lcrypto -lssl -lcares -lz
#include <stdlib.h>
#include "aria2_c.h"
*/
import "C"
import (
"errors"
"fmt"
"log"
"strconv"
"strings"
"unsafe"
)
// Type definition for lib aria2, it holds a notifier.
type Aria2 struct {
notifier Notifier
shutdownNotification chan bool
shouldShutdown bool
}
// Type definition of configuration for aria2.
type Config struct {
Options Options
Notifier Notifier
}
// NewAria2 creates a new instance of aria2.
func NewAria2(config Config) *Aria2 {
a := &Aria2{
notifier: newDefaultNotifier(),
shutdownNotification: make(chan bool),
}
a.SetNotifier(config.Notifier)
C.init(C.uint64_t(uintptr(unsafe.Pointer(a))),
C.CString(a.fromOptions(config.Options)))
return a
}
// Shutdown aria2, this must be invoked when process exit(signal handler is not
// used), so aria2 will be able to save session config.
func (a *Aria2) Shutdown() int {
C.shutdownSchedules(true)
a.shouldShutdown = true
// do nothing, just make thread waiting
select {
case <-a.shutdownNotification:
break
}
return int(C.deinit())
}
// Run starts event pooling. Note this will block current thread.
func (a *Aria2) Run() {
for {
if C.run() != 1 && a.shouldShutdown {
break
}
}
a.shutdownNotification <- true
}
// SetNotifier sets notifier to receive download notification from aria2.
func (a *Aria2) SetNotifier(notifier Notifier) {
if notifier == nil {
return
}
a.notifier = notifier
}
// AddUri adds a new download. The uris is an array of HTTP/FTP/SFTP/BitTorrent
// URIs (strings) pointing to the same resource. When adding BitTorrent Magnet
// URIs, uris must have only one element and it should be BitTorrent Magnet URI.
func (a *Aria2) AddUri(uri string, options Options) (gid string, err error) {
cUri := C.CString(uri)
cOptions := C.CString(a.fromOptions(options))
defer C.free(unsafe.Pointer(cUri))
defer C.free(unsafe.Pointer(cOptions))
ret := C.addUri(cUri, cOptions)
if ret == 0 {
return "", errors.New("libaria2: add uri failed")
}
return fmt.Sprintf("%x", uint64(ret)), nil
}
// AddTorrent adds a MetaInfo download with given torrent file path.
// This will return gid and files in torrent file if add successfully.
// User can choose specified files to download, change directory and so on.
func (a *Aria2) AddTorrent(filepath string, options Options) (gid string, err error) {
cFilepath := C.CString(filepath)
cOptions := C.CString(a.fromOptions(options))
defer C.free(unsafe.Pointer(cFilepath))
defer C.free(unsafe.Pointer(cOptions))
ret := C.addTorrent(cFilepath, cOptions)
if ret == 0 {
return "", errors.New("libaria2: add torrent failed")
}
return fmt.Sprintf("%x", uint64(ret)), nil
}
// ChangeOptions can change the options for aria2. See available options in
// https://aria2.github.io/manual/en/html/aria2c.html#input-file.
func (a *Aria2) ChangeOptions(gid string, options Options) error {
cOptions := C.CString(a.fromOptions(options))
defer C.free(unsafe.Pointer(cOptions))
if !C.changeOptions(a.hexToGid(gid), cOptions) {
return errors.New("libaria2: change options error")
}
return nil
}
// GetOptions gets all options for given gid.
func (a *Aria2) GetOptions(gid string) Options {
cOptions := C.getOptions(a.hexToGid(gid))
if cOptions == nil {
return make(Options)
}
return a.toOptions(C.GoString(cOptions))
}
// ChangeGlobalOptions changes global options. See available options in
// https://aria2.github.io/manual/en/html/aria2c.html#input-file except for
// `checksum`, `index-out`, `out`, `pause` and `select-file`.
func (a *Aria2) ChangeGlobalOptions(options Options) error {
cOptions := C.CString(a.fromOptions(options))
defer C.free(unsafe.Pointer(cOptions))
if !C.changeGlobalOptions(cOptions) {
return errors.New("libaria2: change global options error")
}
return nil
}
// GetGlobalOptions gets all global options of aria2.
func (a *Aria2) GetGlobalOptions() Options {
return a.toOptions(C.GoString(C.getGlobalOptions()))
}
// Pause pauses an active download for given gid. The status of the download
// will become `DOWNLOAD_PAUSED`. Use `Resume` to restart download.
func (a *Aria2) Pause(gid string) bool {
return bool(C.pause(a.hexToGid(gid)))
}
// Resume resumes an paused download for given gid.
func (a *Aria2) Resume(gid string) bool {
return bool(C.resume(a.hexToGid(gid)))
}
// Remove removes download no matter what status it was. This will stop
// downloading and stop seeding(for torrent).
func (a *Aria2) Remove(gid string) bool {
return bool(C.removeDownload(a.hexToGid(gid)))
}
// GetDownloadInfo gets current download information for given gid.
func (a *Aria2) GetDownloadInfo(gid string) DownloadInfo {
ret := C.getDownloadInfo(a.hexToGid(gid))
if ret == nil {
return DownloadInfo{}
}
defer C.free(unsafe.Pointer(ret))
// convert info hash to hex string
infoHash := fmt.Sprintf("%x", []byte(C.GoString(ret.infoHash)))
// retrieve BitTorrent meta information
var metaInfo = MetaInfo{}
mi := ret.metaInfo
if mi != nil {
announceList := strings.Split(C.GoString(mi.announceList), ";")
metaInfo = MetaInfo{
Name: C.GoString(mi.name),
Comment: C.GoString(mi.comment),
CreationUnix: int64(mi.creationUnix),
AnnounceList: announceList,
}
}
return DownloadInfo{
Status: int(ret.status),
TotalLength: int64(ret.totalLength),
BytesCompleted: int64(ret.bytesCompleted),
BytesUpload: int64(ret.uploadLength),
DownloadSpeed: int(ret.downloadSpeed),
UploadSpeed: int(ret.uploadSpeed),
NumPieces: int(ret.numPieces),
Connections: int(ret.connections),
InfoHash: infoHash,
MetaInfo: metaInfo,
Files: a.parseFiles(ret.files, ret.numFiles),
}
}
// fromOptions converts `Options` to string with ';' separator.
func (a *Aria2) fromOptions(options Options) string {
if options == nil {
return ""
}
var cOptions string
for k, v := range options {
cOptions += k + ";"
cOptions += v + ";"
}
return strings.TrimSuffix(cOptions, ";")
}
// fromOptions converts options string with ';' separator to `Options`.
func (a *Aria2) toOptions(cOptions string) Options {
coptions := strings.Split(strings.TrimSuffix(cOptions, ";"), ";")
var options = make(Options)
var index int
for index = 0; index < len(coptions); index += 2 {
options[coptions[index]] = coptions[index+1]
}
return options
}
// hexToGid convert hex to uint64 type gid.
func (a *Aria2) hexToGid(hex string) C.uint64_t {
id, err := strconv.ParseUint(hex, 16, 64)
if err != nil {
return 0
}
return C.uint64_t(id)
}
// parseFiles parses all files information from aria2.
func (a *Aria2) parseFiles(filesPointer *C.struct_FileInfo, length C.int) (files []File) {
cfiles := (*[1 << 20]C.struct_FileInfo)(unsafe.Pointer(filesPointer))[:length:length]
if cfiles == nil {
return
}
for _, f := range cfiles {
files = append(files, File{
Index: int(f.index),
Length: int64(f.length),
CompletedLength: int64(f.completedLength),
Name: C.GoString(f.name),
Selected: bool(f.selected),
})
}
// free c pointer resource
C.free(unsafe.Pointer(filesPointer))
return
}
//export notifyEvent
//noinspection GoUnusedFunction
func notifyEvent(ariagoPointer uint64, id uint64, event int) {
a := (*Aria2)(unsafe.Pointer(uintptr(ariagoPointer)))
if a == nil || a.notifier == nil {
return
}
// convert id to hex string
gid := fmt.Sprintf("%x", uint64(id))
switch event {
case onStart:
a.notifier.OnStart(gid)
case onPause:
a.notifier.OnPause(gid)
case onStop:
a.notifier.OnStop(gid)
case onComplete:
a.notifier.OnComplete(gid)
case onError:
a.notifier.OnError(gid)
case onBTComplete:
a.notifier.OnComplete(gid)
}
}
//export goLog
//noinspection GoUnusedFunction
func goLog(msg *C.char) {
log.Println(C.GoString(msg))
}