1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from hashlib import md5
6 from django.conf import settings
7 from mailchimp3 import MailChimp
8 from mailchimp3.mailchimpclient import MailChimpError
11 def subscriber_hash(email):
12 return md5(email.encode('utf-8')).hexdigest()
15 def remove_from_groups(email, client):
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})
28 def subscribe(email, mailing_lists=None):
29 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
31 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
32 except MailChimpError:
35 if member['status'] != 'subscribed':
36 remove_from_groups(email, client)
37 mailing_lists = mailing_lists or [settings.MAILCHIMP_DEFAULT_GROUP]
39 settings.MAILCHIMP_GROUP_IDS[mailing_list]: True
40 for mailing_list in mailing_lists
41 if mailing_list in settings.MAILCHIMP_GROUP_IDS
43 client.lists.members.create_or_update(
44 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
46 'email_address': email,
47 'status_if_new': 'subscribed',
48 'status': 'subscribed',
49 'interests': interests,
54 def unsubscribe(email, mailing_lists=None):
55 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
57 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
58 except MailChimpError:
61 if member['status'] != 'subscribed':
63 mailing_lists = mailing_lists or settings.MAILCHIMP_GROUP_IDS
65 settings.MAILCHIMP_GROUP_IDS[mailing_list]: False
66 for mailing_list in mailing_lists
67 if mailing_list in settings.MAILCHIMP_GROUP_IDS
69 client.lists.members.update(
70 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
72 'interests': interests,