Skip to content

Instantly share code, notes, and snippets.

@Holi0317
Last active March 6, 2021 02:30
Show Gist options
  • Save Holi0317/bd5f11c2da331131e85779dbf6f563d2 to your computer and use it in GitHub Desktop.
Save Holi0317/bd5f11c2da331131e85779dbf6f563d2 to your computer and use it in GitHub Desktop.
Sort aria2 downloads (See readme.md for details)

Sort aria2 paused requests.

Requirements:

  • Python 3
  • requests library
  • Aria2 RPC Server with secret enabled

Installation

  1. Download the script
  2. Install requests by pip install requests (May need sudo if error occured)
  3. Edit line 12 and 14 to meet your requirement

Run this script by python3 aria2-sort.py

NOTE: Only paused/panding downloads will be sorted

#!/usr/bin/env python3
"""
This script will sort all aria2 paused requests
"""
import json
import itertools
import requests
# Change your endpoint (Without token) here
ENDPOINT = 'http://localhost:6800/jsonrpc'
# Change #### to your token. Only token is allowed and it is required
TOKEN = 'token:####'
class MethodCall(object):
def __init__(self, method: str, *params):
self.method = method
self.params = list(params)
self.params.insert(0, TOKEN)
def toDict(self):
return {
'methodName': self.method,
'params': self.params
}
def __repr__(self):
return '<MethodCall object for {method}. params: {params}'.format(
method=self.method, params=self.params
)
def call(method: str, *params):
p = list(params)
p.insert(0, TOKEN)
jsonreq = json.dumps({
'jsonrpc': '2.0',
'id': 'qwer',
'method': method,
'params': p
})
res = requests.post(ENDPOINT, data=jsonreq)
if not res.ok:
print(res.json())
res.raise_for_status()
return res
def multicall(calls: list):
params = [x.toDict() for x in calls]
print(params)
jsonreq = json.dumps({
'jsonrpc': '2.0',
'id': 'qwer',
'method': 'system.multicall',
'params': [params]
})
res = requests.post(ENDPOINT, data=jsonreq)
if not res.ok:
print(res.json())
res.raise_for_status()
return res
def list_downloads():
KEYS = ['gid', 'files']
active = MethodCall('aria2.tellActive', KEYS)
waiting = MethodCall('aria2.tellWaiting', 0, 100, KEYS)
res = multicall([active, waiting])
results = res.json()['result']
return [item for sublist1 in results for sublist2 in sublist1 for item in sublist2]
def exert_path(stat):
return {
'gid': stat['gid'],
'path': stat['files'][0]['path']
}
def main():
downloads = [exert_path(stat) for stat in list_downloads()]
sorted_downloads = sorted(downloads, key=lambda x: x['path'])
gid_list = [x['gid'] for x in sorted_downloads]
# Issue multicall request
multicall([MethodCall('aria2.changePosition', x, gid_list.index(x), 'POS_SET') for x in gid_list])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment