Debian Codegraph @

download-docs

raw
1 #!/usr/bin/python3
2 import argparse
3 import logging
4 import sys
5 import requests
6 import re
7 import urllib.parse
8 import os
9 from lxml import etree as ET
10
11 log = logging.getLogger("download_docs")
12
13 DOCS = [
14 r"/Schema_del_file_xml.+\.xsd$",
15 r"/Specifiche_tecniche.+\.pdf$",
16 r"/Rappresentazione_tabellare_del_tracciato.+\.(?:pdf|xls)$",
17 r"/fatturaPA.+\.xsl$",
18 r"/fatturaordinaria.+\.xsl$"
19 r"/changelog_formato\.pdf$",
20 r"/Suggerimenti_Compilazione.+\.pdf$",
21 r"/fatturapa.+\.xsl$",
22 r"/fatturaordinaria.+\.xsl$",
23 r"/Elenco_Controlli.+\.pdf$",
24 ]
25
26 EXAMPLES = [
27 r"/IT01234567890_FP.+\.xml",
28 ]
29
30
31 def get_urls(index_url):
32 index = requests.get(index_url)
33 parser = ET.XMLParser(recover=True)
34 root = ET.fromstring(index.text, parser)
35 re_docs = [re.compile(r) for r in DOCS]
36 re_examples = [re.compile(r) for r in EXAMPLES]
37 links = []
38 for a in root.iter("a"):
39 href = a.attrib.get("href")
40 if href is None:
41 continue
42 # There seem to be various wrong links to this file, so we ignore
43 # them
44 if "IT01234567890_11111" in href:
45 continue
46 links.append(href)
47 for l in links:
48 for r in re_docs:
49 if r.search(l):
50 yield {"type": "doc", "href": l}
51 for r in re_examples:
52 if r.search(l):
53 yield {"type": "example", "href": l}
54
55
56 def download(index_url):
57 for el in get_urls(index_url):
58 url = urllib.parse.urljoin(index_url, el["href"])
59 parsed = urllib.parse.urlparse(url)
60 filename = os.path.basename(parsed.path)
61 if el["type"] == "doc":
62 dest = os.path.join("doc", filename)
63 elif el["type"] == "example":
64 dest = os.path.join("doc", filename)
65 if os.path.exists(dest):
66 log.info("%s: already downloaded", dest)
67 continue
68 res = requests.get(url, stream=True)
69 with open(dest, 'wb') as fd:
70 for chunk in res.iter_content(chunk_size=128):
71 fd.write(chunk)
72 log.info("%s: downloading", dest)
73
74
75 class Fail(Exception):
76 pass
77
78
79 def main():
80 parser = argparse.ArgumentParser(description="download documents and examples from www.fatturapa.gov.it")
81 parser.add_argument("--verbose", "-v", action="store_true", help="verbose output")
82 parser.add_argument("--debug", action="store_true", help="debug output")
83
84 args = parser.parse_args()
85
86 log_format = "%(asctime)-15s %(levelname)s %(message)s"
87 level = logging.WARN
88 if args.debug:
89 level = logging.DEBUG
90 elif args.verbose:
91 level = logging.INFO
92 logging.basicConfig(level=level, stream=sys.stderr, format=log_format)
93
94 download("https://www.fatturapa.gov.it/it/norme-e-regole/documentazione-fattura-elettronica/formato-fatturapa/")
95
96
97 if __name__ == "__main__":
98 try:
99 main()
100 except Fail as e:
101 print(e, file=sys.stderr)
102 sys.exit(1)
103 except Exception:
104 log.exception("uncaught exception")