Updates and fixes.
[wolnelektury.git] / src / contact / mailing.py
1 from hashlib import md5
2
3 from django.conf import settings
4 from mailchimp3 import MailChimp
5 from mailchimp3.mailchimpclient import MailChimpError
6
7
8 def subscriber_hash(email):
9     return md5(email.encode('utf-8')).hexdigest()
10
11
12 def remove_from_groups(email, client):
13     group_ids = []
14     categories = client.lists.interest_categories.all(list_id=settings.MAILCHIMP_LIST_ID)['categories']
15     for category in categories:
16         groups = client.lists.interest_categories.interests.all(
17             list_id=settings.MAILCHIMP_LIST_ID, category_id=category['id'])['interests']
18         group_ids += [group['id'] for group in groups]
19     interests = {group_id: False for group_id in group_ids}
20     client.lists.members.update(
21          settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
22          data={'interests': interests})
23
24
25 def subscribe(email, mailing_lists=None):
26     client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
27     try:
28         member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
29     except MailChimpError:
30         pass
31     else:
32         if member['status'] != 'subscribed':
33             remove_from_groups(email, client)
34     mailing_lists = mailing_lists or [settings.MAILCHIMP_DEFAULT_GROUP]
35     interests = {
36         settings.MAILCHIMP_GROUP_IDS[mailing_list]: True
37         for mailing_list in mailing_lists
38         if mailing_list in settings.MAILCHIMP_GROUP_IDS
39     }
40     client.lists.members.create_or_update(
41         settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
42         data={
43             'email_address': email,
44             'status_if_new': 'subscribed',
45             'status': 'subscribed',
46             'interests': interests,
47         }
48     )
49
50
51 def unsubscribe(email, mailing_lists=None):
52     client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
53     try:
54         member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
55     except MailChimpError:
56         return
57     else:
58         if member['status'] != 'subscribed':
59             return
60     mailing_lists = mailing_lists or settings.MAILCHIMP_GROUP_IDS
61     interests = {
62         settings.MAILCHIMP_GROUP_IDS[mailing_list]: False
63         for mailing_list in mailing_lists
64         if mailing_list in settings.MAILCHIMP_GROUP_IDS
65     }
66     client.lists.members.update(
67         settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
68         data={
69             'interests': interests,
70         }
71     )