Example #1
0
    def api(self, **kwargs):
        api_key = self.get_api_key()

        if api_key:
            api = greatape.MailChimp(api_key)

            def api(api=api, **kwargs):
                logger.info("mailchimp(%s)" %
                            (", ".join("%s=%r" % item
                                       for item in kwargs.items())))

                try:
                    return api(**kwargs)
                except greatape.MailChimpError, exc:
                    # http://apidocs.mailchimp.com/api/1.3/exceptions.field.php
                    if exc.code <= 0:
                        logger.critical(exc.msg)
                    elif exc.code < 120:
                        logger.warn(exc.msg)
                    elif exc.code < 200:
                        logger.info(exc.msg)
                except TypeError, exc:
                    logger.warn(exc.msg)

                return ()
def check_api_key(api_key):
    if not api_key:
        return True

    api = greatape.MailChimp(api_key)

    try:
        api(method="ping")
    except greatape.MailChimpError:
        pass
    except ValueError, exc:
        logger.warn(exc)
    def template(self):
        site = getToolByName(self.context, "portal_url").getPortalObject()
        settings = IFeedSettings(site)
        api_key = settings.mailchimp_api_key

        if not api_key:
            return

        try:
            api = greatape.MailChimp(api_key, debug=False)
            cid = self.request.get('cid', '')
            content = api(method="campaignContent", cid=cid)
        except greatape.MailChimpError:
            IStatusMessage(self.request).addStatusMessage(
                _(u"Unable to show content."), "error"
                )
            return

        return content['html']
Example #4
0
    def handleApply(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        settings = IFeedSettings(self.context)
        api_key = settings.mailchimp_api_key
        next_url = self.nextURL()

        try:
            list_id = (data.pop('list_id', None)
                       or self.getContent().mailinglist)
            try:
                name = data.pop('name')
            except KeyError:
                name = ''
            email = data.pop('email')
            interests = data.pop('interests')

            content = self.getContent()

            preselected = getattr(content, 'preselected_interest_groups', None)
            if preselected:
                if not interests:
                    interests = preselected
                else:
                    interests = interests + preselected

            if api_key:
                api = greatape.MailChimp(api_key, debug=False)

                # Negotiate language
                language = negotiate(self.request)

                # Split full name into first (given) and last name.
                try:
                    fname, lname = queryUtility(
                        INameSplitter,
                        name=language,
                        default=GenericNameSplitter).split_name(name)
                except AttributeError:
                    fname, lname = u'', u''

                # Log subscription attempt.
                logger.info(("listSubscribe(%r, %r, %r, %r)" %
                             (list_id, email, fname, lname)).encode('utf-8'))

                merge_vars = {
                    'FNAME':
                    fname.encode('utf-8'),
                    'LNAME':
                    lname.encode('utf-8'),
                    'GROUPINGS': [
                        dict(
                            id=grouping_id,
                            groups=",".join(
                                group.encode('utf-8').replace(',', '\\,')
                                for group in group_names),
                        ) for (grouping_id, group_names
                               ) in create_groupings(interests).items()
                    ]
                }

                for name, value in data.items():
                    if value is not None:
                        merge_vars[name.upper()] = value.encode('utf-8')

                try:
                    result = api(method="listSubscribe",
                                 id=list_id,
                                 email_address=email,
                                 update_existing=True,
                                 replace_interests=False,
                                 merge_vars=merge_vars)
                except greatape.MailChimpError, exc:
                    logger.warn(exc.msg)

                    # ... is not a valid interest grouping id for the list
                    if exc.code == 270:
                        return IStatusMessage(self.request).addStatusMessage(
                            _(u"There was a problem signing you up for "
                              u"the selected interest groups. This could "
                              u"mean that the subscription service is "
                              u"configured incorrectly. Please contact "
                              u"the webmaster."),
                            "error",
                        )
                else:
                    if result:
                        next_url += ('?' in next_url and '&'
                                     or '?') + 'success=yes'

                        return IStatusMessage(self.request).addStatusMessage(
                            _(u"Thank you for signing up. We'll send you a "
                              u"confirmation message by e-mail shortly."),
                            "info")

            IStatusMessage(self.request).addStatusMessage(
                _(
                    u"An error occurred while processing your "
                    u"request to sign up for ${email}. "
                    u"Please try again!",
                    mapping={'email': email}), "error")
Example #5
0
    def createCampaign(self,
                       api_key,
                       method,
                       subject,
                       create_draft,
                       schedule,
                       rendered,
                       next_url,
                       segment_opts={}):
        try:
            if not rendered.strip():
                IStatusMessage(self.request).addStatusMessage(
                    _(u"No content found; newsletter not created."), "info")

                return

            if api_key:
                api = greatape.MailChimp(api_key, debug=False)

                try:
                    for entry in api(method="lists"):
                        if entry['id'] == self.context.mailinglist:
                            break
                    else:
                        IStatusMessage(self.request).addStatusMessage(
                            _(u"Mailinglist not found."), "error")

                        return

                    if self.context.template:
                        section = 'html_%s' % self.context.section
                    else:
                        section = 'html'

                    args = {}

                    args['method'] = method
                    args['type'] = 'regular'
                    args['content'] = {section: rendered}
                    if segment_opts:
                        args['segment_opts'] = segment_opts

                    options = {}
                    options['subject'] = subject.encode("utf-8") or \
                        entry['default_subject']
                    options['from_email'] = entry['default_from_email']
                    options['from_name'] = \
                        entry['default_from_name'].encode("utf-8")
                    options['to_email'] = 0
                    options['list_id'] = self.context.mailinglist
                    options['template_id'] = self.context.template or None
                    options['generate_text'] = True

                    args['options'] = options

                    result = api(**args)

                    if result:
                        if not create_draft:
                            if schedule:
                                # Apply local time zone to get GMT
                                schedule = schedule + datetime.timedelta(
                                    seconds=time.timezone)

                                # Format time
                                schedule_time = time.strftime(
                                    "%Y-%m-%d %H:%M:%S",
                                    schedule.utctimetuple())

                                schedule = api(
                                    method="campaignSchedule",
                                    cid=result,
                                    schedule_time=schedule_time,
                                )

                                if not schedule:
                                    IStatusMessage(
                                        self.request
                                    ).addStatusMessage(
                                        _(u"Campaign created, but not scheduled."
                                          ), "error")

                                    return
                            else:
                                api(method="campaignSendNow", cid=result)

                        next_url = self.context.portal_url() + \
                            "/@@chimpfeed-content?cid=%s" % result

                except greatape.MailChimpError, exc:
                    IStatusMessage(self.request).addStatusMessage(
                        _(u"Unable to process request: ${message}",
                          mapping={'message': exc.msg}), "error")
                    logger.warn(exc.msg)
                    logger.warn(pprint.pformat(args))
                    return

                return bool(result)
        finally:
            self.request.response.redirect(next_url)