ovh-bills-pdf/src/main.py
Dryusdan 2e0dbaa3ce
All checks were successful
continuous-integration/drone/push Build is passing
Write it pylama friendly
2022-04-09 00:16:58 +02:00

92 lines
2.5 KiB
Python

#!/usr/bin/env python3
import ovh
import pendulum
import requests
import typer
import yaml
from pathlib import Path
app = typer.Typer()
home = str(Path.home())
with open(f"{home}/.config/ovh-bills-pdf/secrets.yaml", "r") as stream:
try:
secrets = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
@app.command()
def download_all():
typer.echo("Download all bills")
params = {}
download(params)
@app.command()
def download_week():
typer.echo("Download week")
now = pendulum.now(f"{secrets['timezone']}")
week_start = now.start_of('week')
week_end = now.end_of('week')
params = {}
params['date.from'] = week_start.isoformat()
params['date.to'] = week_end.isoformat()
typer.echo(f"Process from {params['date.from']} to {params['date.to']}")
download(params)
def download(params):
if not Path(secrets['download_path']).is_dir():
typer.echo(f"{secrets['download_path']} don't exist. Please create it")
raise SystemExit()
for account in secrets['accounts']:
typer.echo(f"Processing of {account['name']}")
client = ovh.Client(
endpoint=f"{account['region']}",
application_key=f"{account['app_key']}",
application_secret=f"{account['app_secret']}",
consumer_key=f"{account['consumer_key']}",
)
billIds = client.get('/me/bill', **params)
if billIds:
_processBill(client, billIds)
else:
typer.echo("No bill to download")
def _processBill(client, billIds):
for billId in billIds:
bill = client.get(f"/me/bill/{billId}")
try:
r = requests.get(bill['pdfUrl'])
r.raise_for_status()
except requests.exceptions.Timeout:
typer.echo("URL timeout")
continue
except requests.exceptions.TooManyRedirects:
typer.echo("To many redirect. URL is good ?")
continue
except requests.exceptions.RequestException as e:
raise SystemExit(e)
except requests.exceptions.HTTPError as err:
typer.echo(f"Error when getting PDF : {err}")
continue
typer.echo(f"Write {bill['billId']}.pdf")
try:
with open(f"{secrets['download_path']}/{bill['billId']}.pdf", 'wb') as f:
f.write(r.content)
except OSError:
typer.echo(f"Can't open {secrets['download_path']}/{bill['billId']}.pdf).")
typer.echo("Folder exist ?")
if __name__ == "__main__":
app()