# Path: humans/models.py
# class User(AbstractUser):
#     """
#         Project's base user model
#     """
#     LANGUAGE_CHOICES = (
#         ('en-us', 'English'),
#         ('pt-pt', _('Portuguese')),
#     )
# 
#     organization = models.CharField(
#         null=True, blank=True, max_length=80, verbose_name=_('Organization'))
#     public_key = models.TextField(
#         blank=True, null=True, verbose_name=_('Public key'))
#     fingerprint = models.CharField(
#         null=True, blank=True, max_length=50, verbose_name=_('Fingerprint'))
#     keyserver_url = models.URLField(
#         null=True, blank=True, verbose_name=_('Key server URL'))
#     timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone'))
#     language = models.CharField(
#         default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language'))
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.base_fingerprint = self.fingerprint
# 
#     def save(self, *args, **kwargs):
#         ip = kwargs.pop('ip', None)
#         agent = kwargs.pop('agent', '')
#         with transaction.atomic():
#             super().save(*args, **kwargs)
#             if self.base_fingerprint != self.fingerprint:
#                 self.keychanges.create(user=self,
#                                        prev_fingerprint=self.base_fingerprint,
#                                        to_fingerprint=self.fingerprint,
#                                        ip_address=ip,
#                                        agent=agent)
#                 self.base_fingerprint = self.fingerprint
# 
#     def has_setup_complete(self):
#         if self.public_key and self.fingerprint:
#             return True
#         return False
# 
#     @property
#     def has_github_login(self):
#         return self.socialaccount_set.filter(provider='github').count() >= 1
# 
#     @property
#     def has_public_key(self):
#         return True if self.public_key else False
# 
#     @property
#     def has_keyserver_url(self):
#         return True if self.keyserver_url else False
# 
# class Notification(models.Model):
#     """ These notifications are emails sent to all users (or some subset)
#         by an Administrator. Just once.
#     """
# 
#     subject = models.CharField(
#         null=False, blank=False, max_length=150, verbose_name=_('Subject'))
#     body = models.TextField(null=False, blank=False, verbose_name=_('Body'))
# 
#     created_at = models.DateTimeField(
#         auto_now_add=True, verbose_name=_('Created at'))
#     updated_at = models.DateTimeField(
#         auto_now=True, verbose_name=_('Updated at'))
# 
#     sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at'))
#     send_to = models.ForeignKey(
#         Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to'))
# 
#     class Meta:
#         verbose_name = _('Notification')
#         verbose_name_plural = _('Notifications')
# 
#     def __str__(self):
#         return self.subject
# 
#     def delete(self):
#         return super().delete() if not self.sent_at else False
# 
# Path: humans/utils.py
# @with_gpg_obj
# def key_state(key, gpg):
#     INVALID = (None, "invalid", -1)
#     if not key:
#         return INVALID
#     results = gpg.import_keys(key).results
#     if not results:
#         return INVALID
#     # Key data is present in the last element of the list
#     key_fingerprint = results[-1].get("fingerprint")
#     if not key_fingerprint:
#         return INVALID
# 
#     # Since the keyring is exclusive for this import
#     # only the imported key exists in it.
#     key = gpg.list_keys()[0]
#     exp_timestamp = int(key["expires"]) if key["expires"] else 0
#     expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)
#     to_expire = expires - timezone.now()
#     days_to_expire = to_expire.days
# 
#     if key["trust"] == "r":
#         state = "revoked"
#     elif exp_timestamp and expires < timezone.now():
#         state = "expired"
#     else:
#         state = "valid"
# 
#     return key_fingerprint, state, days_to_expire


from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery import shared_task
from celery.utils.log import get_task_logger
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from .models import User, Notification
from .utils import key_state
import requests
        fingerprint, *state = key_state(key)

        if state[0] == "expired":
            # Email user and disable/remove key
            send_email(user, _('Hawkpost: {} key').format(state[0]),
                       "humans/emails/key_{}.txt".format(state[0]))
            user.fingerprint = ""
            user.public_key = ""
            user.save()

        elif state[0] == "valid":
            # Checks if key is about to expire
            days_to_expire = state[1]
            if days_to_expire == 7 or days_to_expire == 1:
                # Warns user if key about to expire
                send_email(user,
                           _('Hawkpost: Key will expire in {} day(s)').format(days_to_expire),
                           "humans/emails/key_will_expire.txt")


@shared_task
def send_email_notification(subject, body, email):
    email = EmailMultiAlternatives(subject, body,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [email])
    email.send()


@shared_task
def enqueue_email_notifications(notification_id, group_id):

# Path: humans/models.py
# class User(AbstractUser):
#     """
#         Project's base user model
#     """
#     LANGUAGE_CHOICES = (
#         ('en-us', 'English'),
#         ('pt-pt', _('Portuguese')),
#     )
# 
#     organization = models.CharField(
#         null=True, blank=True, max_length=80, verbose_name=_('Organization'))
#     public_key = models.TextField(
#         blank=True, null=True, verbose_name=_('Public key'))
#     fingerprint = models.CharField(
#         null=True, blank=True, max_length=50, verbose_name=_('Fingerprint'))
#     keyserver_url = models.URLField(
#         null=True, blank=True, verbose_name=_('Key server URL'))
#     timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone'))
#     language = models.CharField(
#         default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language'))
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.base_fingerprint = self.fingerprint
# 
#     def save(self, *args, **kwargs):
#         ip = kwargs.pop('ip', None)
#         agent = kwargs.pop('agent', '')
#         with transaction.atomic():
#             super().save(*args, **kwargs)
#             if self.base_fingerprint != self.fingerprint:
#                 self.keychanges.create(user=self,
#                                        prev_fingerprint=self.base_fingerprint,
#                                        to_fingerprint=self.fingerprint,
#                                        ip_address=ip,
#                                        agent=agent)
#                 self.base_fingerprint = self.fingerprint
# 
#     def has_setup_complete(self):
#         if self.public_key and self.fingerprint:
#             return True
#         return False
# 
#     @property
#     def has_github_login(self):
#         return self.socialaccount_set.filter(provider='github').count() >= 1
# 
#     @property
#     def has_public_key(self):
#         return True if self.public_key else False
# 
#     @property
#     def has_keyserver_url(self):
#         return True if self.keyserver_url else False
# 
# class Notification(models.Model):
#     """ These notifications are emails sent to all users (or some subset)
#         by an Administrator. Just once.
#     """
# 
#     subject = models.CharField(
#         null=False, blank=False, max_length=150, verbose_name=_('Subject'))
#     body = models.TextField(null=False, blank=False, verbose_name=_('Body'))
# 
#     created_at = models.DateTimeField(
#         auto_now_add=True, verbose_name=_('Created at'))
#     updated_at = models.DateTimeField(
#         auto_now=True, verbose_name=_('Updated at'))
# 
#     sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at'))
#     send_to = models.ForeignKey(
#         Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to'))
# 
#     class Meta:
#         verbose_name = _('Notification')
#         verbose_name_plural = _('Notifications')
# 
#     def __str__(self):
#         return self.subject
# 
#     def delete(self):
#         return super().delete() if not self.sent_at else False
# 
# Path: humans/utils.py
# @with_gpg_obj
# def key_state(key, gpg):
#     INVALID = (None, "invalid", -1)
#     if not key:
#         return INVALID
#     results = gpg.import_keys(key).results
#     if not results:
#         return INVALID
#     # Key data is present in the last element of the list
#     key_fingerprint = results[-1].get("fingerprint")
#     if not key_fingerprint:
#         return INVALID
# 
#     # Since the keyring is exclusive for this import
#     # only the imported key exists in it.
#     key = gpg.list_keys()[0]
#     exp_timestamp = int(key["expires"]) if key["expires"] else 0
#     expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)
#     to_expire = expires - timezone.now()
#     days_to_expire = to_expire.days
# 
#     if key["trust"] == "r":
#         state = "revoked"
#     elif exp_timestamp and expires < timezone.now():
#         state = "expired"
#     else:
#         state = "valid"
# 
#     return key_fingerprint, state, days_to_expire


# Path: humans/tasks.py
from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery import shared_task
from celery.utils.log import get_task_logger
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from .models import User, Notification
from .utils import key_state
import requests

        fingerprint, *state = key_state(key)

        if state[0] == "expired":
            # Email user and disable/remove key
            send_email(user, _('Hawkpost: {} key').format(state[0]),
                       "humans/emails/key_{}.txt".format(state[0]))
            user.fingerprint = ""
            user.public_key = ""
            user.save()

        elif state[0] == "valid":
            # Checks if key is about to expire
            days_to_expire = state[1]
            if days_to_expire == 7 or days_to_expire == 1:
                # Warns user if key about to expire
                send_email(user,
                           _('Hawkpost: Key will expire in {} day(s)').format(days_to_expire),
                           "humans/emails/key_will_expire.txt")


@shared_task
def send_email_notification(subject, body, email):
    email = EmailMultiAlternatives(subject, body,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [email])
    email.send()


@shared_task
def enqueue_email_notifications(notification_id, group_id):

    notification = Notification.objects.get(id=notification_id)