mailchimp_sync_announcements.py 2.47 KB
Newer Older
1 2 3
"""
Synchronizes the announcement list with all active students.
"""
4 5 6 7 8 9 10
import logging
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

from django.contrib.auth.models import User

11 12 13 14 15
from .mailchimp_sync_course import (
    connect_mailchimp, get_cleaned,
    get_subscribed, get_unsubscribed,
    subscribe_with_data
)
16 17 18 19 20

log = logging.getLogger('edx.mailchimp')


class Command(BaseCommand):
21 22 23
    """
    Synchronizes the announcement list with all active students.
    """
24
    args = '<mailchimp_key mailchimp_list course_id>'
25
    help = 'Synchronizes the announcement list with all active students.'
26 27 28 29 30 31 32 33

    option_list = BaseCommand.option_list + (
        make_option('--key', action='store', help='mailchimp api key'),
        make_option('--list', action='store', dest='list_id',
                    help='mailchimp list id'),
    )

    def parse_options(self, options):
34
        """Parses `options` of the command."""
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
        if not options['key']:
            raise CommandError('missing key')

        if not options['list_id']:
            raise CommandError('missing list id')

        return (options['key'], options['list_id'])

    def handle(self, *args, **options):
        key, list_id = self.parse_options(options)

        log.info('Syncronizing announcement mailing list')

        mailchimp = connect_mailchimp(key)

        subscribed = get_subscribed(mailchimp, list_id)
        unsubscribed = get_unsubscribed(mailchimp, list_id)
        cleaned = get_cleaned(mailchimp, list_id)
        non_subscribed = unsubscribed.union(cleaned)

        enrolled = get_enrolled()
        exclude = subscribed.union(non_subscribed)
        to_subscribe = get_data(enrolled, exclude=exclude)

        subscribe_with_data(mailchimp, list_id, to_subscribe)


def get_enrolled():
63 64 65
    """
    Filter out all users who signed up via a Microsite, which UserSignupSource tracks
    """
66
    ## TODO (Feanil) This grabs all inactive students and MUST be changed (or, could exclude inactive users in get_data)
67 68 69 70
    return User.objects.raw('SELECT * FROM auth_user where id not in (SELECT user_id from student_usersignupsource)')


def get_data(users, exclude=None):
71 72 73 74 75 76
    """
    users: set of Django users
    exclude [optional]: set of Django users to exclude

    returns: {'EMAIL': u.email} for all users in users less those in `exclude`
    """
77 78 79
    exclude = exclude if exclude else set()
    emails = (u.email for u in users)
    return ({'EMAIL': e} for e in emails if e not in exclude)