Skip to content

Commit

Permalink
gw info, gw update: Add rate limit check for GitHub API
Browse files Browse the repository at this point in the history
Based on original patch by yzqzss <[email protected]>
  • Loading branch information
keirf committed Aug 21, 2024
1 parent 4a728e3 commit 3c31bc9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/greaseweazle/tools/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ def print_info_line(name: str, value: str, tab=0) -> None:
def latest_firmware() -> Tuple[int,int]:
rsp = requests.get('https://api.github.com/repos/keirf/'
'greaseweazle-firmware/releases/latest', timeout=5)
if int(rsp.headers.get('X-RateLimit-Remaining', 1)) == 0:
raise requests.RequestException('GitHub API Rate Limit exceeded')
tag = rsp.json()['tag_name']
r = re.match(r'v(\d+)\.(\d+)', tag)
assert r is not None
Expand Down
15 changes: 10 additions & 5 deletions src/greaseweazle/tools/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ def extract_update(usb, dat, args):

return (major, minor), dat

def gh_request_get(url, timeout):
rsp = requests.get(url, timeout=timeout)
if int(rsp.headers.get('X-RateLimit-Remaining', 1)) == 0:
raise requests.RequestException('GitHub API Rate Limit exceeded')
return rsp

def download(json):
# Look for a matching asset (greaseweazle-firmware-<ver>.zip)
Expand All @@ -96,15 +101,15 @@ def download(json):
# Download and unzip the asset
name = basename+'.upd'
print('Downloading latest firmware: '+name)
rsp = requests.get(url, timeout=10)
rsp = gh_request_get(url, timeout=10)
z = zipfile.ZipFile(io.BytesIO(rsp._content))
return name, z.read(basename+'/'+name)


def download_by_tag(tag_name):
'''Download the latest Update File from GitHub.'''
rsp = requests.get('https://api.github.com/repos/keirf/'
'greaseweazle-firmware/releases', timeout=5)
rsp = gh_request_get('https://api.github.com/repos/keirf/'
'greaseweazle-firmware/releases', timeout=5)
for release in rsp.json():
if release['tag_name'] == tag_name:
return download(release)
Expand All @@ -113,8 +118,8 @@ def download_by_tag(tag_name):

def download_latest():
'''Download the latest Update File from GitHub.'''
rsp = requests.get('https://api.github.com/repos/keirf/'
'greaseweazle-firmware/releases/latest', timeout=5)
rsp = gh_request_get('https://api.github.com/repos/keirf/'
'greaseweazle-firmware/releases/latest', timeout=5)
return download(rsp.json())


Expand Down

0 comments on commit 3c31bc9

Please sign in to comment.