1

I am trying to orchestrate a downloading of files with aria2 tool. There is an example in the documentation like:

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"}'

It starts download of http://example.org/file and returns some GID (download ID) 2089b05ecca3d829...

Aria2 supports notifications. But no any examples how to get a notification, for example, onDownloadComplete, onDownloadError, etc. I assume, there is a way to request the aria2 to call me through JSON-RPC (HTTP) on some (my) IP and port. But I cannot find a way how to request aria2 to do it (how to subscribe to the notifications with my IP, port). Any example in Python, Ruby or similar will be very helpful.

RandomB
  • 3,367
  • 19
  • 30
  • 1
    This is the related example how to do it - https://github.com/pawamoy/aria2p/blob/master/src/aria2p/client.py. Aria2 sends notifications through WebSockets only. – RandomB Nov 19 '20 at 10:01

1 Answers1

1

Refered to aria2 docs You should use websocket to communicate with RPC server:

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()

after you get the message (json object), you'll get the onDownloadComplete event, then you can do whatever you like. I suggest you use ariap (above @RandomB Mentioned it), https://pawamoy.github.io/aria2p/reference/api/#aria2p.api.API.listen_to_notifications

set notification with a callback.

 ......
 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()