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