diff options
| author | jvoisin | 2018-03-31 21:20:21 +0200 |
|---|---|---|
| committer | jvoisin | 2018-03-31 21:20:21 +0200 |
| commit | 12b3b39d4d5520af04233578ec93138eb192621e (patch) | |
| tree | 80a4f97ba2cece14f40eee889a4330a828148062 /src | |
| parent | 0bbafc4cc52d02f763db93b67703113b88db9107 (diff) | |
Add support for .odt
Diffstat (limited to 'src')
| -rw-r--r-- | src/libreoffice.py | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/src/libreoffice.py b/src/libreoffice.py new file mode 100644 index 0000000..b7e0dfb --- /dev/null +++ b/src/libreoffice.py | |||
| @@ -0,0 +1,54 @@ | |||
| 1 | import re | ||
| 2 | import subprocess | ||
| 3 | import json | ||
| 4 | import zipfile | ||
| 5 | import tempfile | ||
| 6 | import shutil | ||
| 7 | import os | ||
| 8 | |||
| 9 | from . import abstract, parser_factory | ||
| 10 | |||
| 11 | class LibreOfficeParser(abstract.AbstractParser): | ||
| 12 | mimetypes = { | ||
| 13 | 'application/vnd.oasis.opendocument.text', | ||
| 14 | } | ||
| 15 | |||
| 16 | def get_meta(self): | ||
| 17 | """ | ||
| 18 | Yes, I know that parsing xml with regexp ain't pretty, | ||
| 19 | be my guest and fix it if you want. | ||
| 20 | """ | ||
| 21 | metadata = {} | ||
| 22 | zipin = zipfile.ZipFile(self.filename) | ||
| 23 | for item in zipin.namelist(): | ||
| 24 | if item == 'meta.xml': | ||
| 25 | content = zipin.read(item).decode('utf-8') | ||
| 26 | for (key, value) in re.findall(r"<((?:meta|dc).+?)>(.+)</\1>", content, re.I): | ||
| 27 | metadata[key] = value | ||
| 28 | if not metadata: # better safe than sorry | ||
| 29 | metadata[item] = 'harmful content' | ||
| 30 | zipin.close() | ||
| 31 | return metadata | ||
| 32 | |||
| 33 | def remove_all(self): | ||
| 34 | zin = zipfile.ZipFile(self.filename, 'r') | ||
| 35 | zout = zipfile.ZipFile(self.output_filename, 'w') | ||
| 36 | temp_folder = tempfile.mkdtemp() | ||
| 37 | |||
| 38 | for item in zin.infolist(): | ||
| 39 | if item.filename[-1] == '/': | ||
| 40 | continue # `is_dir` is added in Python3.6 | ||
| 41 | elif item.filename == 'meta.xml': | ||
| 42 | continue # don't keep metadata files | ||
| 43 | |||
| 44 | zin.extract(member=item, path=temp_folder) | ||
| 45 | tmp_parser = parser_factory.get_parser(os.path.join(temp_folder, item.filename)) | ||
| 46 | if tmp_parser is None: | ||
| 47 | print("%s isn't supported" % item.filename) | ||
| 48 | continue | ||
| 49 | tmp_parser.remove_all() | ||
| 50 | zout.write(tmp_parser.output_filename, item.filename) | ||
| 51 | shutil.rmtree(temp_folder) | ||
| 52 | zout.close() | ||
| 53 | zin.close() | ||
| 54 | return True | ||
