<commit_before>import logging

from django.db import transaction
from django.utils import timezone
from modularodm import Q

from framework.celery_tasks import app as celery_app
from osf.models import OSFUser as User
from osf.models.queued_mail import NO_LOGIN_TYPE, NO_LOGIN, QueuedMail, queue_mail
from website.app import init_app
from website import settings

from scripts.utils import add_file_logger

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def main(dry_run=True):
    for user in find_inactive_users_with_no_inactivity_email_sent_or_queued():
        if dry_run:
            logger.warn('Dry run mode')
        logger.warn('Email of type no_login queued to {0}'.format(user.username))
        if not dry_run:
            with transaction.atomic():
                queue_mail(
                    to_addr=user.username,
                    mail=NO_LOGIN,
                    send_at=timezone.now(),
                    user=user,
                    fullname=user.fullname,
                )


def find_inactive_users_with_no_inactivity_email_sent_or_queued():
    inactive_users = User.find(
        (Q('date_last_login', 'lt', timezone.now() - settings.NO_LOGIN_WAIT_TIME) & Q('tags__name', 'ne', 'osf4m')) |
        (Q('date_last_login', 'lt', timezone.now() - settings.NO_LOGIN_OSF4M_WAIT_TIME) & Q('tags__name', 'eq', 'osf4m'))
    )
    inactive_emails = QueuedMail.find(Q('email_type', 'eq', NO_LOGIN_TYPE))

    #This is done to prevent User query returns comparison to User, as equality fails
    #on datetime fields due to pymongo rounding. Instead here _id is compared.
    users_sent_id = [email.user._id for email in inactive_emails]
    inactive_ids = [user._id for user in inactive_users if user.is_active]
    users_to_send = [User.load(id) for id in (set(inactive_ids) - set(users_sent_id))]
    return users_to_send


@celery_app.task(name='scripts.triggered_mails')
def run_main(dry_run=True):
    init_app(routes=False)
    if not dry_run:<commit_msg>Reduce num of queries made in triggered mails script.<commit_after>import logging

from django.db import transaction, Q
from django.utils import timezone

from framework.celery_tasks import app as celery_app
from osf.models import OSFUser as User
from osf.models.queued_mail import NO_LOGIN_TYPE, NO_LOGIN, QueuedMail, queue_mail
from website.app import init_app
from website import settings

from scripts.utils import add_file_logger

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def main(dry_run=True):
    for user in find_inactive_users_with_no_inactivity_email_sent_or_queued():
        if dry_run:
            logger.warn('Dry run mode')
        logger.warn('Email of type no_login queued to {0}'.format(user.username))
        if not dry_run:
            with transaction.atomic():
                queue_mail(
                    to_addr=user.username,
                    mail=NO_LOGIN,
                    send_at=timezone.now(),
                    user=user,
                    fullname=user.fullname,
                )


def find_inactive_users_with_no_inactivity_email_sent_or_queued():
    users_sent_ids = QueuedMail.objects.filter(email_type=NO_LOGIN_TYPE).values_list('user__guids___id')
    return (User.objects
        .filter(
            (Q(date_last_login__lt=timezone.now() - settings.NO_LOGIN_WAIT_TIME) & ~Q(tags__name='osf4m')) |
            Q(date_last_login__lt=timezone.now() - settings.NO_LOGIN_OSF4M_WAIT_TIME, tags__name='osf4m'),
            is_active=True)
        .exclude(guids___id__in=users_sent_ids))

@celery_app.task(name='scripts.triggered_mails')
def run_main(dry_run=True):
    init_app(routes=False)
    if not dry_run:
{'fraction_non_alphanumeric': 0.08831448572967152, 'fraction_numerical': 0.002154011847065159, 'mean_word_length': 3.2898383371824482, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '2197894', 'n_tokens_mistral': 1208, 'n_tokens_neox': 1176, 'n_words': 258}