| 1 |
# Copyright 2022 Nitrokey Developers |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or |
| 4 |
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or |
| 5 |
# http://opensource.org/licenses/MIT>, at your option. This file may not be |
| 6 |
# copied, modified, or distributed except according to those terms. |
| 7 |
|
| 8 |
import os.path |
| 9 |
import urllib.parse |
| 10 |
from dataclasses import dataclass |
| 11 |
from typing import Any, BinaryIO, Callable, Dict, Generator, Optional, Pattern |
| 12 |
|
| 13 |
import requests |
| 14 |
|
| 15 |
API_BASE_URL = "https://api.github.com" |
| 16 |
|
| 17 |
|
| 18 |
ProgressCallback = Callable[[int, int], None] |
| 19 |
|
| 20 |
|
| 21 |
class DownloadError(Exception): |
| 22 |
def __init__(self, msg: str) -> None: |
| 23 |
super().__init__("Cannot download firmware: " + msg) |
| 24 |
|
| 25 |
|
| 26 |
class OverwriteError(Exception): |
| 27 |
def __init__(self, path: str) -> None: |
| 28 |
super().__init__(f"File {path} already exists and may not be overwritten") |
| 29 |
self.path = path |
| 30 |
|
| 31 |
|
| 32 |
@dataclass |
| 33 |
class Asset: |
| 34 |
tag: str |
| 35 |
url: str |
| 36 |
|
| 37 |
def download(self, f: BinaryIO, callback: Optional[ProgressCallback] = None) -> None: |
| 38 |
for chunk in self._get_chunks(callback=callback): |
| 39 |
f.write(chunk) |
| 40 |
|
| 41 |
def download_to_dir( |
| 42 |
self, d: str, overwrite: bool = False, callback: Optional[ProgressCallback] = None |
| 43 |
) -> str: |
| 44 |
if not os.path.exists(d): |
| 45 |
raise DownloadError(f"Directory {d} does not exist") |
| 46 |
if not os.path.isdir(d): |
| 47 |
raise DownloadError(f"{d} is not a directory") |
| 48 |
url = urllib.parse.urlparse(self.url) |
| 49 |
filename = os.path.basename(url.path) |
| 50 |
path = os.path.join(d, filename) |
| 51 |
if os.path.exists(path) and not overwrite: |
| 52 |
raise OverwriteError(path) |
| 53 |
with open(path, "wb") as f: |
| 54 |
self.download(f, callback=callback) |
| 55 |
return path |
| 56 |
|
| 57 |
def read(self, callback: Optional[ProgressCallback] = None) -> bytes: |
| 58 |
result = bytes() |
| 59 |
for chunk in self._get_chunks(callback=callback): |
| 60 |
result += chunk |
| 61 |
return result |
| 62 |
|
| 63 |
def _get_chunks( |
| 64 |
self, chunk_size: int = 1024, callback: Optional[ProgressCallback] = None |
| 65 |
) -> Generator[bytes, None, None]: |
| 66 |
response = self._get(stream=True) |
| 67 |
total = int(response.headers.get("content-length", 0)) |
| 68 |
if callback: |
| 69 |
callback(0, total) |
| 70 |
|
| 71 |
for chunk in response.iter_content(chunk_size=chunk_size): |
| 72 |
if callback: |
| 73 |
callback(len(chunk), total) |
| 74 |
yield chunk |
| 75 |
|
| 76 |
def _get(self, stream: bool = False) -> requests.Response: |
| 77 |
response = requests.get(self.url, stream=stream) |
| 78 |
response.raise_for_status() |
| 79 |
return response |
| 80 |
|
| 81 |
def __str__(self) -> str: |
| 82 |
return self.url |
| 83 |
|
| 84 |
|
| 85 |
@dataclass |
| 86 |
class Release: |
| 87 |
tag: str |
| 88 |
assets: list[str] |
| 89 |
|
| 90 |
def __str__(self) -> str: |
| 91 |
return self.tag |
| 92 |
|
| 93 |
def find_asset(self, url_pattern: Pattern[str]) -> Optional[Asset]: |
| 94 |
urls = [] |
| 95 |
for asset in self.assets: |
| 96 |
if url_pattern.search(asset): |
| 97 |
urls.append(asset) |
| 98 |
|
| 99 |
if len(urls) == 1: |
| 100 |
return Asset(tag=self.tag, url=urls[0]) |
| 101 |
elif len(urls) > 1: |
| 102 |
raise ValueError(f"Found multiple assets for release {self.tag} matching {url_pattern}") |
| 103 |
else: |
| 104 |
return None |
| 105 |
|
| 106 |
def require_asset(self, url_pattern: Pattern[str]) -> Asset: |
| 107 |
update = self.find_asset(url_pattern) |
| 108 |
if not update: |
| 109 |
raise ValueError(f"Failed to find asset for release {self.tag} matching {url_pattern}") |
| 110 |
return update |
| 111 |
|
| 112 |
@classmethod |
| 113 |
def _from_api_response(cls, release: dict[Any, Any]) -> "Release": |
| 114 |
tag = release["tag_name"] |
| 115 |
assets = [asset["browser_download_url"] for asset in release["assets"]] |
| 116 |
if not assets: |
| 117 |
raise ValueError(f"No update files for firmware release {tag}") |
| 118 |
return cls(tag=tag, assets=assets) |
| 119 |
|
| 120 |
|
| 121 |
@dataclass |
| 122 |
class Repository: |
| 123 |
owner: str |
| 124 |
name: str |
| 125 |
|
| 126 |
def get_latest_release(self) -> Release: |
| 127 |
release = self._call(f"/repos/{self.owner}/{self.name}/releases/latest") |
| 128 |
return Release._from_api_response(release) |
| 129 |
|
| 130 |
def get_release(self, tag: str) -> Release: |
| 131 |
release = self._call( |
| 132 |
f"/repos/{self.owner}/{self.name}/releases/tags/{tag}", |
| 133 |
{404: f"Failed to find firmware release {tag}"}, |
| 134 |
) |
| 135 |
return Release._from_api_response(release) |
| 136 |
|
| 137 |
def get_release_or_latest(self, tag: Optional[str] = None) -> Release: |
| 138 |
if tag: |
| 139 |
return self.get_release(tag) |
| 140 |
return self.get_latest_release() |
| 141 |
|
| 142 |
def _call(self, path: str, errors: Optional[Dict[int, str]] = None) -> dict[Any, Any]: |
| 143 |
if errors is None: |
| 144 |
errors = {} |
| 145 |
|
| 146 |
url = self._get_url(path) |
| 147 |
response = requests.get(url) |
| 148 |
for code in errors: |
| 149 |
if response.status_code == code: |
| 150 |
raise ValueError(errors[code]) |
| 151 |
response.raise_for_status() |
| 152 |
data = response.json() |
| 153 |
assert isinstance(data, dict) |
| 154 |
return data |
| 155 |
|
| 156 |
def _get_url(self, path: str) -> str: |
| 157 |
return API_BASE_URL + path |