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