import logging
import uuid

from django.db import models
from django.urls import reverse
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _

from model_utils.managers import InheritanceManager

from mayan.apps.django_gpg.exceptions import VerificationError
from mayan.apps.django_gpg.models import Key
from mayan.apps.documents.models import DocumentVersion
from mayan.apps.storage.classes import DefinedStorageLazy

from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE
from .managers import DetachedSignatureManager, EmbeddedSignatureManager

logger = logging.getLogger(name=__name__)


def upload_to(*args, **kwargs):
    return force_text(s=uuid.uuid4())


class SignatureBaseModel(models.Model):
    """
    Fields:
    * key_id - Key Identifier - This is what identifies uniquely a key. Not
    two keys in the world have the same Key ID. The Key ID is also used to
    locate a key in the key servers: http://pgp.mit.edu
    * signature_id - Signature ID - Every time a key is used to sign something
    it will generate a unique signature ID. No two signature IDs are the same,
    even when using the same key.
    """
    document_version = models.ForeignKey(
        editable=False, on_delete=models.CASCADE, related_name='signatures',
        to=DocumentVersion, verbose_name=_('Document version')
    )
    # Basic fields
    date = models.DateField(
        blank=True, editable=False, null=True, verbose_name=_('Date signed')
    )
    key_id = models.CharField(
        help_text=_('ID of the key that will be used to sign the document.'),
        max_length=40, verbose_name=_('Key ID')
    )
    # With proper key
    signature_id = models.CharField(
        blank=True, editable=False, null=True, max_length=64,
        verbose_name=_('Signature ID')
    )
    public_key_fingerprint = models.CharField(
        blank=True, editable=False, null=True, max_length=40,
        verbose_name=_('Public key fingerprint')
    )

    objects = InheritanceManager()

    class Meta:
        ordering = ('pk',)
        verbose_name = _('Document version signature')
        verbose_name_plural = _('Document version signatures')

    def __str__(self):
        return self.signature_id or '{} - {}'.format(self.date, self.key_id)

    def get_absolute_url(self):
        return reverse(
            viewname='signatures:document_version_signature_details',
            kwargs={'signature_id': self.pk}
        )

    def get_key_id(self):
        if self.public_key_fingerprint:
            return self.public_key_fingerprint[-16:]
        else:
            return self.key_id

    def get_signature_type_display(self):
        if self.is_detached:
            return _('Detached')
        else:
            return _('Embedded')

    @property
    def is_detached(self):
        return hasattr(self, 'signature_file')

    @property
    def is_embedded(self):
        return not hasattr(self, 'signature_file')


class EmbeddedSignature(SignatureBaseModel):
    objects = EmbeddedSignatureManager()

    class Meta:
        verbose_name = _('Document version embedded signature')
        verbose_name_plural = _('Document version embedded signatures')

    def save(self, *args, **kwargs):
        logger.debug(msg='checking for embedded signature')

        if self.pk:
            raw = True
        else:
            raw = False

        with self.document_version.open(raw=raw) as file_object:
            try:
                verify_result = Key.objects.verify_file(
                    file_object=file_object
                )
            except VerificationError as exception:
                # Not signed
                logger.debug(
                    'embedded signature verification error; %s', exception
                )
            else:
                self.date = verify_result.date
                self.key_id = verify_result.key_id
                self.signature_id = verify_result.signature_id
                self.public_key_fingerprint = verify_result.pubkey_fingerprint

                super(EmbeddedSignature, self).save(*args, **kwargs)


class DetachedSignature(SignatureBaseModel):
    signature_file = models.FileField(
        blank=True, help_text=_(
            'Signature file previously generated.'
        ), null=True, storage=DefinedStorageLazy(
            name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE
        ), upload_to=upload_to, verbose_name=_('Signature file')
    )

    objects = DetachedSignatureManager()

    class Meta:
        verbose_name = _('Document version detached signature')
        verbose_name_plural = _('Document version detached signatures')

    def __str__(self):
        return '{}-{}'.format(self.document_version, _('signature'))

    def delete(self, *args, **kwargs):
        if self.signature_file.name:
            self.signature_file.storage.delete(name=self.signature_file.name)
        super(DetachedSignature, self).delete(*args, **kwargs)

    def save(self, *args, **kwargs):
        with self.document_version.open() as file_object:
            try:
                verify_result = Key.objects.verify_file(
                    file_object=file_object, signature_file=self.signature_file
                )
            except VerificationError as exception:
                # Not signed
                logger.debug(
                    'detached signature verification error; %s', exception
                )
            else:
                self.signature_file.seek(0)

                self.date = verify_result.date
                self.key_id = verify_result.key_id
                self.signature_id = verify_result.signature_id
                self.public_key_fingerprint = verify_result.pubkey_fingerprint

        return super(DetachedSignature, self).save(*args, **kwargs)

[((624, 656), 'logging.getLogger', 'logging.getLogger', ([], {'name': '__name__'}), '(name=__name__)\n', (641, 656), False, 'import logging\n'), ((2025, 2045), 'model_utils.managers.InheritanceManager', 'InheritanceManager', ([], {}), '()\n', (2043, 2045), False, 'from model_utils.managers import InheritanceManager\n'), ((2113, 2144), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version signature"""'], {}), "('Document version signature')\n", (2114, 2144), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2175, 2207), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version signatures"""'], {}), "('Document version signatures')\n", (2176, 2207), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2357, 2461), 'django.urls.reverse', 'reverse', ([], {'viewname': '"""signatures:document_version_signature_details"""', 'kwargs': "{'signature_id': self.pk}"}), "(viewname='signatures:document_version_signature_details', kwargs={\n    'signature_id': self.pk})\n", (2364, 2461), False, 'from django.urls import reverse\n'), ((3118, 3158), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version embedded signature"""'], {}), "('Document version embedded signature')\n", (3119, 3158), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((3189, 3230), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version embedded signatures"""'], {}), "('Document version embedded signatures')\n", (3190, 3230), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4586, 4626), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version detached signature"""'], {}), "('Document version detached signature')\n", (4587, 4626), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4657, 4698), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version detached signatures"""'], {}), "('Document version detached signatures')\n", (4658, 4698), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((715, 727), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (725, 727), False, 'import uuid\n'), ((1358, 1379), 'django.utils.translation.ugettext_lazy', '_', (['"""Document version"""'], {}), "('Document version')\n", (1359, 1379), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1494, 1510), 'django.utils.translation.ugettext_lazy', '_', (['"""Date signed"""'], {}), "('Date signed')\n", (1495, 1510), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1566, 1624), 'django.utils.translation.ugettext_lazy', '_', (['"""ID of the key that will be used to sign the document."""'], {}), "('ID of the key that will be used to sign the document.')\n", (1567, 1624), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1662, 1673), 'django.utils.translation.ugettext_lazy', '_', (['"""Key ID"""'], {}), "('Key ID')\n", (1663, 1673), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1822, 1839), 'django.utils.translation.ugettext_lazy', '_', (['"""Signature ID"""'], {}), "('Signature ID')\n", (1823, 1839), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1976, 2003), 'django.utils.translation.ugettext_lazy', '_', (['"""Public key fingerprint"""'], {}), "('Public key fingerprint')\n", (1977, 2003), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2747, 2760), 'django.utils.translation.ugettext_lazy', '_', (['"""Detached"""'], {}), "('Detached')\n", (2748, 2760), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2794, 2807), 'django.utils.translation.ugettext_lazy', '_', (['"""Embedded"""'], {}), "('Embedded')\n", (2795, 2807), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4260, 4301), 'django.utils.translation.ugettext_lazy', '_', (['"""Signature file previously generated."""'], {}), "('Signature file previously generated.')\n", (4261, 4301), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4344, 4420), 'mayan.apps.storage.classes.DefinedStorageLazy', 'DefinedStorageLazy', ([], {'name': 'STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE'}), '(name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE)\n', (4362, 4420), False, 'from mayan.apps.storage.classes import DefinedStorageLazy\n'), ((4478, 4497), 'django.utils.translation.ugettext_lazy', '_', (['"""Signature file"""'], {}), "('Signature file')\n", (4479, 4497), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4776, 4790), 'django.utils.translation.ugettext_lazy', '_', (['"""signature"""'], {}), "('signature')\n", (4777, 4790), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((3526, 3574), 'mayan.apps.django_gpg.models.Key.objects.verify_file', 'Key.objects.verify_file', ([], {'file_object': 'file_object'}), '(file_object=file_object)\n', (3549, 3574), False, 'from mayan.apps.django_gpg.models import Key\n'), ((5155, 5244), 'mayan.apps.django_gpg.models.Key.objects.verify_file', 'Key.objects.verify_file', ([], {'file_object': 'file_object', 'signature_file': 'self.signature_file'}), '(file_object=file_object, signature_file=self.\n    signature_file)\n', (5178, 5244), False, 'from mayan.apps.django_gpg.models import Key\n')]