try to load the public key if encrypt fails for 1st time

This commit is contained in:
Son NK 2020-06-10 22:28:15 +02:00
parent 2034225a37
commit 9e2f1c5f9f
1 changed files with 12 additions and 7 deletions

View File

@ -6,6 +6,7 @@ from memory_profiler import memory_usage
from app.config import GNUPGHOME from app.config import GNUPGHOME
from app.log import LOG from app.log import LOG
from app.models import Mailbox
from app.utils import random_string from app.utils import random_string
gpg = gnupg.GPG(gnupghome=GNUPGHOME) gpg = gnupg.GPG(gnupghome=GNUPGHOME)
@ -43,12 +44,16 @@ def encrypt_file(data: BytesIO, fingerprint: str) -> str:
r = gpg.encrypt_file(data, fingerprint, always_trust=True) r = gpg.encrypt_file(data, fingerprint, always_trust=True)
if not r.ok: if not r.ok:
# save the content for debugging # maybe the fingerprint is not loaded on this host, try to load it
random_file_name = random_string(20) + ".eml" mailbox = Mailbox.get_by(pgp_finger_print=fingerprint)
full_path = f"/tmp/{random_file_name}" if mailbox:
with open(full_path, "wb") as f: LOG.d("(re-)load public key for %s", mailbox)
f.write(data.getbuffer()) load_public_key(mailbox.pgp_public_key)
LOG.error("PGP fail - log to %s", full_path)
raise PGPException("Cannot encrypt") LOG.d("retry to encrypt")
r = gpg.encrypt_file(data, fingerprint, always_trust=True)
if not r.ok:
raise PGPException(f"Cannot encrypt, status: {r.status}")
return str(r) return str(r)