wmts-exfiltrator/pkg/thread.py

43 lines
1.5 KiB
Python
Raw Normal View History

2023-11-03 16:31:53 -06:00
import shutil
from pathlib import Path
2023-11-02 23:35:43 -06:00
import requests
2023-11-03 16:31:53 -06:00
from tqdm import tqdm
2023-11-02 23:35:43 -06:00
from pkg.proxies import PROXIES
from .image import is_png
2023-11-03 16:31:53 -06:00
def del_path(p: Path):
if p.is_file() or p.is_symlink():
p.unlink(missing_ok=True)
else:
shutil.rmtree(p)
2023-11-02 23:35:43 -06:00
def download_tile(task):
2023-11-03 17:10:27 -06:00
row, col, base_url, r_headers, output, use_proxy = task
2023-11-03 16:31:53 -06:00
try:
output_path: Path = output / f"{row}_{col}.png"
if output_path.exists():
if not is_png(output_path):
2023-11-04 20:13:12 -06:00
# Delete the file and try again.
2023-11-03 16:31:53 -06:00
del_path(output_path)
2023-11-06 17:48:09 -07:00
tqdm.write(f'cannot identify image file: "{output_path}", deleting and retrying...')
2023-11-04 20:13:12 -06:00
else:
return row, col, 'exist'
2023-11-05 09:37:43 -07:00
tile_url = f"{base_url}/{row}/{col}".replace('//', '/').replace(':/', '://')
2023-11-03 17:10:27 -06:00
response = requests.get(tile_url, headers=r_headers, proxies=PROXIES if use_proxy else None, timeout=60)
2023-11-03 16:31:53 -06:00
if response.status_code == 200:
if not response.headers.get('Content-Type') == 'image/png':
raise Exception(f'Response gave Content-Type: {response.headers.get("Content-Type")}')
with open(output_path, "wb") as f:
f.write(response.content)
return row, col, 'success'
else:
print(f"Failed to download tile {row}_{col}")
except Exception as e:
# traceback.print_exc()
tqdm.write(f'Exception on {(row, col)} - {e.__class__.__name__}: {e}')
return row, col, 'failure'