|
| 1 | +import re |
| 2 | +import shutil |
| 3 | +from collections.abc import Callable, Iterator |
| 4 | +from pathlib import Path |
| 5 | +from tempfile import TemporaryDirectory |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +import httpx |
| 9 | +from PIL import Image |
| 10 | + |
| 11 | +from . import Profile, __version__, favicon |
| 12 | +from .favicon import Icon |
| 13 | +from .utils import error, info |
| 14 | + |
| 15 | +# TODO more preferences: 16x16, 32, 0, other |
| 16 | +PREFERRED_ICONS = [ |
| 17 | + re.compile(p) |
| 18 | + for p in [ |
| 19 | + r"favicon.*\.svg$", |
| 20 | + r"favicon.*\.ico$", |
| 21 | + r"favicon.*\.png$", |
| 22 | + r"\.ico$", |
| 23 | + r"icon\.png$", |
| 24 | + r"\.svg$", |
| 25 | + ] |
| 26 | +] |
| 27 | + |
| 28 | + |
| 29 | +def choose_icon(icons: list[Icon]) -> Iterator[Icon]: |
| 30 | + preferred = PREFERRED_ICONS |
| 31 | + for pattern in preferred: |
| 32 | + for icon in icons: |
| 33 | + if pattern.search(icon.url.path): |
| 34 | + info(f"chose {icon.url}") |
| 35 | + yield icon |
| 36 | + icons.remove(icon) |
| 37 | + yield from choose_icon(icons) |
| 38 | + |
| 39 | + |
| 40 | +headers = {"user-agent": f"qbpm/{__version__}"} |
| 41 | + |
| 42 | + |
| 43 | +def download_icon(profile: Profile, home_page: str, overwrite: bool) -> Optional[Path]: |
| 44 | + base_url = httpx.URL(home_page) |
| 45 | + if not base_url.scheme: |
| 46 | + base_url = httpx.URL("https://" + home_page) |
| 47 | + client = httpx.Client(base_url=base_url, headers=headers, follow_redirects=True) |
| 48 | + tmp_dir = TemporaryDirectory() |
| 49 | + work_dir = Path(tmp_dir.name) |
| 50 | + try: |
| 51 | + for icon in choose_icon(favicon.get(client)): |
| 52 | + icon_body = client.get(icon.url) |
| 53 | + if icon_body.status_code != 200: |
| 54 | + info(f"got bad response code {icon_body.status_code} for {icon.url}") |
| 55 | + return None |
| 56 | + elif not icon_body.headers["Content-Type"].startswith("image"): |
| 57 | + info(f"{icon.url} is not an image") |
| 58 | + return None |
| 59 | + icon_body.raise_for_status() |
| 60 | + work_icon = work_dir / f"favicon{icon.format}" |
| 61 | + with work_icon.open("wb") as icon_file: |
| 62 | + for chunk in icon_body.iter_bytes(1024): |
| 63 | + icon_file.write(chunk) |
| 64 | + icon_path = install_icon_file(profile, work_icon, overwrite, icon.url) |
| 65 | + if icon_path: |
| 66 | + # print(f"installed {client.base_url.join(icon.url)}") |
| 67 | + return icon_path |
| 68 | + if not icon_path: |
| 69 | + # TODO pretty print |
| 70 | + info(f"no favicons found matching one of {PREFERRED_ICONS}") |
| 71 | + return None |
| 72 | + except Exception as e: |
| 73 | + # info(str(e)) |
| 74 | + raise e |
| 75 | + error(f"failed to fetch favicon from {home_page}") |
| 76 | + return None |
| 77 | + finally: |
| 78 | + tmp_dir.cleanup() |
| 79 | + client.close() |
| 80 | + |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | +def icon_for_profile(profile: Profile) -> Optional[str]: |
| 85 | + icon_file = next(find_icon_files(profile), None) |
| 86 | + if icon_file and icon_file.suffix == ".name": |
| 87 | + return icon_file.read_text() |
| 88 | + return str(icon_file) if icon_file else None |
| 89 | + |
| 90 | + |
| 91 | +def install_icon_file( |
| 92 | + profile: Profile, src: Path, overwrite: bool, origin: Optional[str] = None |
| 93 | +) -> Optional[Path]: |
| 94 | + clean_icons = check_for_icons(profile, overwrite) |
| 95 | + if clean_icons is None: |
| 96 | + return None |
| 97 | + icon_format = src.suffix |
| 98 | + dest = profile.root / f"icon{icon_format}" |
| 99 | + if icon_format not in {".png", ".svg"}: |
| 100 | + dest = dest.with_suffix(".png") |
| 101 | + try: |
| 102 | + image = Image.open(src) |
| 103 | + clean_icons(set()) |
| 104 | + image.save(dest, format="png") |
| 105 | + except Exception as e: |
| 106 | + error(str(e)) |
| 107 | + error(f"failed to convert {origin or src} to png") |
| 108 | + dest.unlink(missing_ok=True) |
| 109 | + return None |
| 110 | + else: |
| 111 | + if src.resolve() != dest: |
| 112 | + shutil.copy(src, dest) |
| 113 | + clean_icons({dest}) |
| 114 | + print(dest) |
| 115 | + return dest.absolute() |
| 116 | + |
| 117 | + |
| 118 | +def install_icon_by_name(profile: Profile, icon_name: str, overwrite: bool) -> bool: |
| 119 | + clean_icons = check_for_icons(profile, overwrite) |
| 120 | + if clean_icons is None: |
| 121 | + return False |
| 122 | + clean_icons(set()) |
| 123 | + file = profile.root / "icon.name" |
| 124 | + file.write_text(icon_name) |
| 125 | + return True |
| 126 | + |
| 127 | + |
| 128 | +def check_for_icons( |
| 129 | + profile: Profile, overwrite: bool |
| 130 | +) -> Callable[[set[Path]], None] | None: |
| 131 | + existing_icons = set(find_icon_files(profile)) |
| 132 | + if existing_icons and not overwrite: |
| 133 | + error(f"icon already exists in {profile.root}, pass --overwrite to replace it") |
| 134 | + return None |
| 135 | + |
| 136 | + def clean_icons(keep: set[Path]) -> None: |
| 137 | + for icon in existing_icons - keep: |
| 138 | + icon.unlink() |
| 139 | + |
| 140 | + return clean_icons |
| 141 | + |
| 142 | + |
| 143 | +def find_icon_files(profile: Profile) -> Iterator[Path]: |
| 144 | + for ext in ["png", "svg", "name"]: |
| 145 | + icon = profile.root / f"icon.{ext}" |
| 146 | + if icon.is_file(): |
| 147 | + yield icon.absolute() |
0 commit comments