Пример #1
0
    def update(self):
        list = List(
            {
                "api_key":
                Configuration.instance.get_setting("campaign_monitor_api_key")
            }, self.list_id)
        details = list.details()

        if self.confirmation_success_page:
            confirmation_success_page = self.confirmation_success_page.get_uri(
                host=".")
        else:
            confirmation_success_page = None

        if self.unsubscribe_page:
            unsubscribe_page = self.unsubscribe_page.get_uri(
                host=".") + "?email=[email]"
        else:
            unsubscribe_page = None

        list.update(details.Title,
                    unsubscribe_page,
                    details.ConfirmedOptIn,
                    confirmation_success_page,
                    unsubscribe_setting=details.UnsubscribeSetting)
Пример #2
0
    def get_or_create_cm_list(client_id, group):
        """Get or create the list on compaign monitor
        """
        try:
            # add the list with the group name to campaign monitor
            cm_list = List(auth)
            list_id = cm_list.create(client_id, group.name, "", False, "")
        except:
            # add group to the queue for later process
            # might log exception reason in the queue
            gq = GroupQueue(group=group)
            gq.save()
            list_id = None

        return list_id
Пример #3
0
    def delete_cm_list(sender, instance=None, **kwargs):
        """Delete the list from campaign monitor
        """
        if instance:
            try:
                list_map = ListMap.objects.get(group=instance)
                list_id = list_map.list_id
                alist = List(auth, list_id)

                if alist:
                    try:
                        alist.delete()
                    except:
                        pass
                list_map.delete()

            except ListMap.DoesNotExist:
                pass
Пример #4
0
def users_to_unsubscribe(cm_list_id, current_perma_user_emails):
    '''
        Returns a list of any email addresses marked as active in
        a given Campaign Monitor subscriber list, but not appearing in
        a passed-in iterable of currely active Perma user email addresses.
    '''
    page = 0
    to_unsubscribe = []
    current_users = set(current_perma_user_emails)
    cm_list = List(settings.CAMPAIGN_MONITOR_AUTH, cm_list_id)
    while True:
        page += 1
        result = cm_list.active(page=page, page_size=1000)
        if result.NumberOfPages <= 0:
            return []
        for subscriber in result.Results:
            if subscriber.EmailAddress not in current_users:
                to_unsubscribe.append(subscriber.EmailAddress)
        if result.PageNumber == result.NumberOfPages:
            return to_unsubscribe
Пример #5
0
    def delete_cm_subscriber(sender, instance=None, **kwargs):
        """Delete the subscriber from the campaign monitor list
        """
        from tendenci.apps.base.utils import validate_email

        (name, email) = get_name_email(instance)
        if email and validate_email(email):
            try:
                list_map = ListMap.objects.get(group=instance.group)
                list_id = list_map.list_id
                alist = List(auth, list_id)

                if alist:
                    subscriber_obj = Subscriber(auth, list_id, email)
                    try:
                        subscriber_obj.unsubscribe()
                    except:
                        pass

            except ListMap.DoesNotExist:
                pass
Пример #6
0
    def delete_cm_subscriber(sender, instance=None, **kwargs):
        """Delete the subscriber from the campaign monitor list
        """
        from django.core.validators import email_re

        (name, email) = get_name_email(instance)        
        if email and email_re.match(email):
            try:
                list_map = ListMap.objects.get(group=instance.group)
                list_id = list_map.list_id
                list = List(list_id)
                
                if list:
                    subscriber_obj = Subscriber(list_id, email)
                    try:
                        subscriber_obj.unsubscribe()
                    except:
                        pass
                   
            except ListMap.DoesNotExist:
                pass
Пример #7
0
    def update(self):
        list = List({"api_key": get_setting("x_campaign3_api_key")},
                    self.list_id)
        details = list.details()

        if self.confirmation_success_page:
            confirmation_success_page = \
                self.confirmation_success_page.get_uri(host = "!")
        else:
            confirmation_success_page = None

        if self.unsubscribe_page:
            unsubscribe_page = (self.unsubscribe_page.get_uri(host="!").merge(
                URL(query={"email": "[email]"})))
        else:
            unsubscribe_page = None

        list.update(details.Title,
                    unsubscribe_page,
                    details.ConfirmedOptIn,
                    confirmation_success_page,
                    unsubscribe_setting=details.UnsubscribeSetting)
Пример #8
0
    def handle(self, *args, **options):
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.profiles.models import Profile
        from tendenci.addons.campaign_monitor.models import (
            ListMap, Campaign, Template, setup_custom_fields)
        from tendenci.addons.campaign_monitor.utils import sync_campaigns, sync_templates
        from createsend import (CreateSend, Client, List, Subscriber,
                                BadRequest, Unauthorized)

        verbosity = 1
        if 'verbosity' in options:
            verbosity = options['verbosity']

        def subscribe_to_list(subscriber_obj, list_id, name, email,
                              custom_data):
            # check if this user has already subscribed, if not, subscribe it
            try:
                subscriber = subscriber_obj.get(list_id, email)
                if str(subscriber.State).lower() == 'active':
                    print name, email, ' - UPDATED'
                    subscriber = subscriber_obj.update(email, name,
                                                       custom_data, True)
            except BadRequest as br:
                print br
                try:
                    email_address = subscriber_obj.add(list_id, email, name,
                                                       custom_data, True)
                    if verbosity >= 2:
                        print "%s (%s)" % (name, email)
                except BadRequest as br:
                    print name, email, ' - NOT ADDED: %s' % br

        api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None)
        client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', None)
        #CreateSend.api_key = api_key
        auth = {'api_key': api_key}
        cl = Client(auth, client_id)

        lists = cl.lists()
        list_ids = [list.ListID for list in lists]
        list_names = [list.Name for list in lists]
        list_ids_d = dict(zip(list_names, list_ids))

        groups = Group.objects.filter(status=1,
                                      status_detail='active',
                                      sync_newsletters=1)
        listmaps = ListMap.objects.filter(group__sync_newsletters=1)
        syncd_groups = [listmap.group for listmap in listmaps]
        cm_list = List(auth)

        print "Starting to sync groups with campaign monitor..."
        print

        for group in groups:
            if group not in syncd_groups:
                # get the list id or create a list if not exists
                # campaing monitor requires the list title
                if group.name in list_names:
                    list_id = list_ids_d[group.name]
                else:
                    # add group to the campaign monitor
                    list_id = cm_list.create(client_id, group.name, "", False,
                                             "")
                    print "Added group '%s' to the C.M. list." % group.name
                    print

                # insert to the listmap
                list_map = ListMap(group=group, list_id=list_id)
                list_map.save()
            else:
                list_map = ListMap.objects.filter(group=group)[0]
                list_id = list_map.list_id

            # if a previous added list is deleted on campaign monitor, add it back
            # TODO: we might need a setting to decide whether we want to add it back or not.

            a_list = List(list_id)
            try:
                list_stats = a_list.stats()
                # set up custom fields
                print "Setting up custom fields..."
                setup_custom_fields(a_list)
                #num_unsubscribed = list_stats.TotalUnsubscribes
                #if num_unsubscribed > 0:
                #    # a list of all unsubscribed
                #    unsubscribed_obj = a_list.unsubscribed('2011-5-1')
                #    unsubscribed_emails = [res.EmailAddress for res in unsubscribed_obj.Results]
                #    unsubscribed_names = [res.Name for res in unsubscribed_obj.Results]
                #   unsubscribed_list = zip(unsubscribed_emails, unsubscribed_names)
            except Unauthorized as e:
                if 'Invalid ListID' in e:
                    # this list might be deleted on campaign monitor, add it back
                    list_id = cm_list.create(client_id, group.name, "", False,
                                             "")
                    # update the list_map
                    list_map.list_id = list_id
                    list_map.save()

            # sync subscribers in this group
            print "Subscribing users to the C.M. list '%s'..." % group.name
            members = group.members.all()
            for i, member in enumerate(members, 1):
                # Append custom fields from the profile
                try:
                    profile = member.profile
                except Profile.DoesNotExist:
                    profile = None
                custom_data = []
                if profile:
                    fields = [
                        'city', 'state', 'zipcode', 'country', 'sex',
                        'member_number'
                    ]
                    for field in fields:
                        data = {}
                        data['Key'] = field
                        data['Value'] = getattr(profile, field)
                        if not data['Value']:
                            data['Clear'] = True
                        custom_data.append(data)
                email = member.email
                name = member.get_full_name()
                subscriber_obj = Subscriber(auth, list_id, email)
                subscribe_to_list(subscriber_obj, list_id, name, email,
                                  custom_data)

        print 'Done'

        print 'Starting to sync campaigns with campaign monitor...'
        sync_campaigns()
        print "Done"

        print 'Syncing templates...'
        sync_templates()
        print "Done"
Пример #9
0
    def sync_cm_subscriber(sender, instance=None, created=False, **kwargs):
        """Subscribe the subscriber to the campaign monitor list
           Check if sync_newsletters is True. Do nothing if False.
        """
        from tendenci.apps.base.utils import validate_email
        from tendenci.apps.profiles.models import Profile

        if instance and instance.group and not instance.group.sync_newsletters:
            return

        (name, email) = get_name_email(instance)
        if email and validate_email(email):
            add_list = False
            add_subscriber = True
            list_map = None

            # Append custom fields from the profile
            profile = None
            if hasattr(instance, 'member'):
                try:
                    profile = instance.member.profile
                except Profile.DoesNotExist:
                    profile = None
            custom_data = []
            if profile:
                fields = ['city', 'state', 'zipcode', 'country',
                          'sex', 'member_number']
                for field in fields:
                    data = {}
                    data['Key'] = field
                    data['Value'] = getattr(profile, field)
                    if not data['Value']:
                        data['Clear'] = True
                    custom_data.append(data)

            try:
                list_map = ListMap.objects.get(group=instance.group)
                list_id = list_map.list_id
                alist = List(auth, list_id)

                if alist:
                    # subscriber setup
                    subscriber_obj = Subscriber(auth, list_id)

                    try:
                        # check if this user has already subscribed, if not, subscribe it
                        try:
                            subscriber = subscriber_obj.get(list_id, email)
                            if str(subscriber.State).lower() == 'active':
                                subscriber = subscriber_obj.update(email, name,
                                                        custom_data, True)
                                add_subscriber = False
                        except BadRequest:
                            pass
                    except Unauthorized:
                        alist = List(auth)
                        add_list = True
                    except ServerError:
                        pass
            except ListMap.DoesNotExist:
                alist = List(auth)
                add_list = True

            try:
                if add_list:
                    # this list might be deleted on campaign monitor, add it back
                    list_id = alist.create(cm_client_id, instance.group.name,
                                          "", False, "")
                    # custom fields setup
                    setup_custom_fields(alist)
                    subscriber_obj = Subscriber(auth, list_id)
                    if not list_map:
                        list_map = ListMap()
                        list_map.group = instance.group
                    list_map.list_id = list_id
                    list_map.save()

                if add_subscriber:
                    subscriber_obj.add(list_id, email, name, custom_data, True)  # Returns email_address
            except BadRequest:
                pass
Пример #10
0
    def sync_cm_list(sender, instance=None, created=False, **kwargs):
        """Check if sync_newsletters. Do nothing if false.
            On Group Add:
                if group name does not exist on C. M,
                    add a list to C. M.
                add an entry to listmap

            On Group Edit:
                if group exists on C. M.,
                    if list.name <> group.name,
                        update list name
                else:
                    add a list on C. M.
                    add an entry to listmap
        """

        cl = Client(auth, cm_client_id)
        lists = cl.lists()
        list_ids = [alist.ListID for alist in lists]
        list_names = [alist.Name for alist in lists]
        list_ids_d = dict(zip(list_names, list_ids))
        list_d = dict(zip(list_ids, lists))

        if created and instance.sync_newsletters:
            if instance.name in list_names:
                list_id = list_ids_d[instance.name]

            else:
                list_id = get_or_create_cm_list(cm_client_id, instance)

            if list_id:
                # add an entry to the listmap
                listmap_insert(instance, list_id)

                # custom fields setup
                cm_list = List(auth, list_id)
                setup_custom_fields(cm_list)

        elif instance.sync_newsletters:  # update
            try:
                # find the entry in the listmap
                list_map = ListMap.objects.get(group=instance)
                list_id = list_map.list_id
            except ListMap.DoesNotExist:
                if instance.name in list_names:
                    list_id = list_ids_d[instance.name]
                else:
                    # hasn't be created on C. M. yet. create one
                    list_id = get_or_create_cm_list(cm_client_id, instance)

                if list_id:
                    listmap_insert(instance, list_id)

            if list_id and list_id in list_ids:
                alist = list_d[list_id]
                cm_list = List(auth, list_id)
                # setup custom fields
                setup_custom_fields(cm_list)
                # if the list title doesn't match with the group name, update the list title
                if instance.name != alist.Name:
                    try:
                        # trap the error for now
                        # TODO: update only if the list title does not exist
                        # within a client.
                        cm_list.update(instance.name, "", False, "")
                    except:
                        pass
Пример #11
0
def create_new_list(client_id, list_name):
    my_list = List(account_auth)
    my_list.create(client_id, list_name, "", False, "")
Пример #12
0
account_admin=CreateSend(account_auth)

tz_list=account_admin.timezones()

country_list=account_admin.countries()

for c in country_list:
    print(c)
'''
#for t in tz_list:
#    print(t)




my_list = List(account_auth)

#my_list.create("9cde80d058d8e4955a076d33b6ec2294", "July 13 v8", "", False, "")
#print(my_list.list_id)


my_subscriber = Subscriber(a_test_client_auth)
'''
my_custom_fields = [{"Key": "Favorite Cuisine", "Value": "Pizza"},{'Key': 'Hobby', "Value": "Football"}]

new_custom_fields = [{"Key": "things i love", "Value": "new york"}, {"Key": "things i also love", "Value": "coding"}, {"Key": "things i hate", "Value": "watching tv"}]


#my_subscriber.add("5926ac888cffa2665144bae9127a89a5", "*****@*****.**", "Subscriber", my_custom_fields, True, "yes")

my_subscriber.add("5926ac888cffa2665144bae9127a89a5", "*****@*****.**", "Subscriber", new_custom_fields, True, "yes")
Пример #13
0
    def sync_cm_subscriber(sender, instance=None, created=False, **kwargs):
        """Subscribe the subscriber to the campaign monitor list
        """
        from django.core.validators import email_re

        (name, email) = get_name_email(instance)
        if email and email_re.match(email):
            add_list = False
            add_subscriber = True
            list_map = None

            # Append custom fields from the profile
            profile = None
            if hasattr(instance, 'member'):
                profile = instance.member.profile
            custom_data = []
            if profile:
                fields = ['city', 'state', 'zipcode', 'country', 'sex', 'member_number']
                for field in fields:
                    data = {}
                    data['Key'] = field
                    data['Value'] = getattr(profile, field)
                    if not data['Value']:
                        data['Clear'] = True
                    custom_data.append(data)

            try:
                list_map = ListMap.objects.get(group=instance.group)
                list_id = list_map.list_id
                list = List(list_id)
                
                if list:
                    # subscriber setup
                    subscriber_obj = Subscriber(list_id)
                    
                    try:
                        list_stats = list.stats()
                    
                        # check if this user has already subscribed, if not, subscribe it
                        try:
                            subscriber = subscriber_obj.get(list_id, email)
                            if str(subscriber.State).lower() == 'active':
                                subscriber = subscriber_obj.update(email, name, custom_data, True)
                                add_subscriber = False
                        except BadRequest as br:
                            pass
                    except Unauthorized as e:
                        list = List()
                        add_list = True
            except ListMap.DoesNotExist:
                list = List()
                add_list = True

            try:
                if add_list:
                    # this list might be deleted on campaign monitor, add it back
                    list_id = list.create(cm_client_id, instance.group.name, "", False, "")
                    # custom fields setup
                    setup_custom_fields(list)
                    subscriber_obj = Subscriber(list_id)
                    if not list_map:
                        list_map = ListMap()
                        list_map.group = instance.group
                    list_map.list_id = list_id
                    list_map.save()
                        
                if add_subscriber:
                    email_address = subscriber_obj.add(list_id, email, name, custom_data, True)
            except BadRequest as br:
                pass
Пример #14
0
def create_new_list(clientid, list_name="Main List 7"):
    my_list = List(account_auth)
    list_id=my_list.create(clientid, list_name, "", False, "")
    return list_id
Пример #15
0
def create_custom_fields(field_name,options,list_id="2345accabd471c4c45e5fc463c8353a1"):
    my_list = List(account_auth,list_id)
    create_custom_fields = my_list.create_custom_field(field_name=field_name,data_type="MultiSelectOne",options=options,visible_in_preference_center=True)