<commit_before>"""General event callbacks."""

from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.template import Template, Context

from modoboa.lib import events, parameters

from modoboa_admin.models import DomainAlias

from .lib import (
    create_user_and_policy, update_user_and_policy, delete_user_and_policy,
    create_user_and_use_policy, delete_user, manual_learning_enabled
)
from .models import Policy, Users


def create_relay_domains_records():
    """Create records for existing relay domains."""
    from modoboa.extensions.postfix_relay_domains.models import RelayDomain

    for rdom in RelayDomain.objects.all():
        policy = create_user_and_policy("@{0}".format(rdom.name))
        for rdomalias in rdom.relaydomainalias_set.all():
            rdomalias_pattern = "@{0}".format(rdomalias.name)
            create_user_and_use_policy(rdomalias_pattern, policy)


@events.observe("InitialDataLoaded")
def load_relay_domains_dependant_data(name):
    """Load relay domains dependant data."""
    if name != "postfix_relay_domains":
        return
    create_relay_domains_records()


@events.observe("UserMenuDisplay")
def menu(target, user):
    if target == "top_menu":
        return [
            {"name": "quarantine",
             "label": _("Quarantine"),
             "url": reverse('modoboa_amavis:index')}
        ]
    return []


@events.observe("DomainCreated")
def on_domain_created(user, domain):
    create_user_and_policy("@{0}".format(domain.name))


@events.observe("DomainModified")
def on_domain_modified(domain):
    update_user_and_policy(
        "@{0}".format(domain.oldname),
        "@{0}".format(domain.name)
    )


@events.observe("DomainDeleted")
def on_domain_deleted(domain):
    delete_user_and_policy("@{0}".format(domain.name))


@events.observe("DomainAliasCreated")
def on_domain_alias_created(user, domainalias):
    create_user_and_use_policy(
        "@{0}".format(domainalias.name),
        "@{0}".format(domainalias.target.name)
    )


@events.observe("DomainAliasDeleted")
def on_domain_alias_deleted(domainaliases):
    if isinstance(domainaliases, DomainAlias):
        domainaliases = [domainaliases]
    for domainalias in domainaliases:
        delete_user("@{0}".format(domainalias.name))


@events.observe("MailboxModified")
def on_mailbox_modified(mailbox):
    """Update amavis records if address has changed."""
    if parameters.get_admin("MANUAL_LEARNING") == "no" or \
       not hasattr(mailbox, "old_full_address") or \
       mailbox.full_address == mailbox.old_full_address:
        return
    user = Users.objects.select_related.get(email=mailbox.old_full_address)
    full_address = mailbox.full_address
    user.email = full_address
    user.policy.policy_name = full_address[:32]
    user.policy.sa_username = full_address
    user.policy.save()
    user.save()


@events.observe("MailboxDeleted")
def on_mailbox_deleted(mailbox):
    """Clean amavis database when a mailbox is removed."""
    if parameters.get_admin("MANUAL_LEARNING") == "no":
        return
    delete_user_and_policy("@{0}".format(mailbox.full_address))


@events.observe("MailboxAliasCreated")
def on_mailboxalias_created(user, alias):
    """Create amavis record for the new alias.

    FIXME: how to deal with distibution lists ?
    """
    if not manual_learning_enabled(user) or alias.type != "alias":
        return
    try:
        policy = Policy.objects.get(
            policy_name=alias.mboxes.all()[0].full_address
        )
    except Policy.DoesNotExist:
        return
    else:
        email = alias.full_address
        Users.objects.create(
            email=email, policy=policy, fullname=email, priority=7
        )


@events.observe("MailboxAliasDeleted")
def on_mailboxalias_deleted(alias):
    """Clean amavis database when an alias is removed."""
    if parameters.get_admin("MANUAL_LEARNING") == "no":
        return
    if Users.objects.filter(email=alias.full_address).exists():
        Users.objects.delete(email=alias.full_address)


@events.observe("GetStaticContent")
def extra_static_content(caller, st_type, user):
    if user.group == "SimpleUsers" or st_type != "js":
        return []

    if caller == 'domains':
        tpl = Template("""<script type="text/javascript">
$(document).bind('domform_init', function() {
    activate_widget.call($('#id_spam_subject_tag2_act'));
});
</script><commit_msg>This event can send list of alias too...<commit_after>"""General event callbacks."""

from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.template import Template, Context

from modoboa.lib import events, parameters

from modoboa_admin.models import DomainAlias, Alias

from .lib import (
    create_user_and_policy, update_user_and_policy, delete_user_and_policy,
    create_user_and_use_policy, delete_user, manual_learning_enabled
)
from .models import Policy, Users


def create_relay_domains_records():
    """Create records for existing relay domains."""
    from modoboa.extensions.postfix_relay_domains.models import RelayDomain

    for rdom in RelayDomain.objects.all():
        policy = create_user_and_policy("@{0}".format(rdom.name))
        for rdomalias in rdom.relaydomainalias_set.all():
            rdomalias_pattern = "@{0}".format(rdomalias.name)
            create_user_and_use_policy(rdomalias_pattern, policy)


@events.observe("InitialDataLoaded")
def load_relay_domains_dependant_data(name):
    """Load relay domains dependant data."""
    if name != "postfix_relay_domains":
        return
    create_relay_domains_records()


@events.observe("UserMenuDisplay")
def menu(target, user):
    if target == "top_menu":
        return [
            {"name": "quarantine",
             "label": _("Quarantine"),
             "url": reverse('modoboa_amavis:index')}
        ]
    return []


@events.observe("DomainCreated")
def on_domain_created(user, domain):
    create_user_and_policy("@{0}".format(domain.name))


@events.observe("DomainModified")
def on_domain_modified(domain):
    update_user_and_policy(
        "@{0}".format(domain.oldname),
        "@{0}".format(domain.name)
    )


@events.observe("DomainDeleted")
def on_domain_deleted(domain):
    delete_user_and_policy("@{0}".format(domain.name))


@events.observe("DomainAliasCreated")
def on_domain_alias_created(user, domainalias):
    create_user_and_use_policy(
        "@{0}".format(domainalias.name),
        "@{0}".format(domainalias.target.name)
    )


@events.observe("DomainAliasDeleted")
def on_domain_alias_deleted(domainaliases):
    if isinstance(domainaliases, DomainAlias):
        domainaliases = [domainaliases]
    for domainalias in domainaliases:
        delete_user("@{0}".format(domainalias.name))


@events.observe("MailboxModified")
def on_mailbox_modified(mailbox):
    """Update amavis records if address has changed."""
    if parameters.get_admin("MANUAL_LEARNING") == "no" or \
       not hasattr(mailbox, "old_full_address") or \
       mailbox.full_address == mailbox.old_full_address:
        return
    user = Users.objects.select_related.get(email=mailbox.old_full_address)
    full_address = mailbox.full_address
    user.email = full_address
    user.policy.policy_name = full_address[:32]
    user.policy.sa_username = full_address
    user.policy.save()
    user.save()


@events.observe("MailboxDeleted")
def on_mailbox_deleted(mailbox):
    """Clean amavis database when a mailbox is removed."""
    if parameters.get_admin("MANUAL_LEARNING") == "no":
        return
    delete_user_and_policy("@{0}".format(mailbox.full_address))


@events.observe("MailboxAliasCreated")
def on_mailboxalias_created(user, alias):
    """Create amavis record for the new alias.

    FIXME: how to deal with distibution lists ?
    """
    if not manual_learning_enabled(user) or alias.type != "alias":
        return
    try:
        policy = Policy.objects.get(
            policy_name=alias.mboxes.all()[0].full_address
        )
    except Policy.DoesNotExist:
        return
    else:
        email = alias.full_address
        Users.objects.create(
            email=email, policy=policy, fullname=email, priority=7
        )


@events.observe("MailboxAliasDeleted")
def on_mailboxalias_deleted(aliases):
    """Clean amavis database when an alias is removed."""
    if parameters.get_admin("MANUAL_LEARNING") == "no":
        return
    if isinstance(aliases, Alias):
        aliases = [aliases]
    aliases = [alias.full_address for alias in aliases]
    Users.objects.filter(email__in=aliases).delete()


@events.observe("GetStaticContent")
def extra_static_content(caller, st_type, user):
    if user.group == "SimpleUsers" or st_type != "js":
        return []

    if caller == 'domains':
        tpl = Template("""<script type="text/javascript">
$(document).bind('domform_init', function() {
    activate_widget.call($('#id_spam_subject_tag2_act'));
});
</script>
{'fraction_non_alphanumeric': 0.1210134459384376, 'fraction_numerical': 0.00333370374486054, 'mean_word_length': 3.97787610619469, 'pattern_counts': {'":': 18, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7302071', 'n_tokens_mistral': 2817, 'n_tokens_neox': 2784, 'n_words': 532}