0

我正在尝试使用aria2工具来协调文件的下载。文档中有一个示例,例如:

import urllib2, json
jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
                      'method':'aria2.addUri',
                      'params':[['http://example.org/file']]})
c = urllib2.urlopen('http://localhost:6800/jsonrpc', jsonreq)
c.read()

# The result:
# '{"id":"qwer","jsonrpc":"2.0","result":"2089b05ecca3d829"}'

它开始下载http://example.org/file并返回一些 GID(下载 ID)2089b05ecca3d829......

Aria2 支持通知。但是没有任何示例如何获取通知,例如onDownloadCompleteonDownloadError等。我认为,有一种方法可以请求 aria2 通过 JSON-RPC (HTTP) 在某些(我的)IP 和端口上呼叫我。但是我找不到如何请求 aria2 来完成它的方法(如何使用我的 IP、端口订阅通知)。Python、Ruby 或类似的任何示例都会非常有帮助。

4

1 回答 1

0

参考 aria2 docs 您应该使用 websocket 与 RPC 服务器进行通信:

import websocket
from pprint import pprint
ws_server = "ws://localhost:6800/jsonrpc"
socket = websocket.create_connection(ws_server)
while 1:
                message = socket.recv()
                pprint(message)
                time.sleep(3)
                
socket.close()

收到消息(json 对象)后,您将获得 onDownloadComplete 事件,然后您可以做任何您想做的事情。我建议你使用 ariap(上面@RandomB 提到过),https: //pawamoy.github.io/aria2p/reference/api/#aria2p.api.API.listen_to_notifications

通过回调设置通知。

 ......
 def start_listen(self):
    self.api.listen_to_notifications(
        threaded=True,
        on_download_complete=self.done,
        timeout=1,
        handle_signals=False
    )
 def done(self, api, gid):
    down = api.get_download(gid)
    dataMedia = str(down.files[0].path)

 def stop_listen(self):
    while len(self.links) > 0:
        gids = list(self.links.keys())
        for down in self.api.get_downloads(gids):
            if down.status in ['waiting', 'active']:
                time.sleep(5)
                break
            else:
                del self.links[down.gid]
                if down.status in ['complete']:
                    #print(f'>>>>>{down.gid} Completed')
                    pass
                else:
                    print(Back.RED + f'{down.gid}|{down.files[0]}|{down.status}|error msg: {down.error_message}', end = '')
                    print(Style.RESET_ALL)
       
    print('all finished!!!!')
    self.api.stop_listening()
于 2021-10-15T15:36:28.620 回答