Merge branch 'preview'
[wolnelektury.git] / src / contact / mailing.py
1 # -*- coding: utf-8 -*-
2
3 from hashlib import md5
4
5 import requests
6 from django.conf import settings
7 from mailchimp3 import MailChimp
8 from mailchimp3.mailchimpclient import MailChimpError
9
10 INTERESTS = {settings.MAILCHIMP_GROUP_ID: True}
11
12
13 def get_client():
14     headers = requests.utils.default_headers()
15     headers['User-Agent'] = '%s (%s)' % settings.MANAGERS[0]
16
17
18 def subscriber_hash(email):
19     return md5(email).hexdigest()
20
21
22 def remove_from_groups(email, client):
23     group_ids = []
24     categories = client.lists.interest_categories.all(list_id=settings.MAILCHIMP_LIST_ID)['categories']
25     for category in categories:
26         groups = client.lists.interest_categories.interests.all(
27             list_id=settings.MAILCHIMP_LIST_ID, category_id=category['id'])['interests']
28         group_ids += [group['id'] for group in groups]
29     interests = {group_id: False for group_id in group_ids}
30     client.lists.members.update(
31          settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
32          data={'interests': interests})
33
34
35 def subscribe(email):
36     client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
37     try:
38         member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
39     except MailChimpError:
40         pass
41     else:
42         if member['status'] != 'subscribed':
43             remove_from_groups(email, client)
44     client.lists.members.create_or_update(
45         settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
46         data={
47             'email_address': email,
48             'status_if_new': 'subscribed',
49             'status': 'subscribed',
50             'interests': INTERESTS,
51         }
52     )