Exemplo n.º 1
0
def update_user(self, sailthru_vars, email, site=None, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        sailthru_vars(dict): User profile information to pass as 'vars' to Sailthru
        email(str): User email address
        new_user(boolean): True if new registration
        activation(boolean): True if activation request
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_email_user_param(sailthru_vars, sailthru_client,
                                                                              email, new_user, email_config,
                                                                              site=site))

    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        if _retryable_sailthru_error(error):
            raise self.retry(countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)
        return

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        scheduled_datetime = datetime.utcnow() + timedelta(seconds=email_config.welcome_email_send_delay)
        try:
            sailthru_response = sailthru_client.api_post(
                "send",
                {
                    "email": email,
                    "template": email_config.sailthru_activation_template,
                    "schedule_time": scheduled_datetime.strftime('%Y-%m-%dT%H:%M:%SZ')
                }
            )
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", email, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
            if _retryable_sailthru_error(error):
                raise self.retry(countdown=email_config.sailthru_retry_interval,
                                 max_retries=email_config.sailthru_max_retries)
Exemplo n.º 2
0
def update_user(self, sailthru_vars, email, site=None, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        sailthru_vars(dict): User profile information to pass as 'vars' to Sailthru
        email(str): User email address
        new_user(boolean): True if new registration
        activation(boolean): True if activation request
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_email_user_param(sailthru_vars, sailthru_client,
                                                                              email, new_user, email_config,
                                                                              site=site))

    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        if _retryable_sailthru_error(error):
            raise self.retry(countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)
        return

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        scheduled_datetime = datetime.utcnow() + timedelta(seconds=email_config.welcome_email_send_delay)
        try:
            sailthru_response = sailthru_client.api_post(
                "send",
                {
                    "email": email,
                    "template": email_config.sailthru_activation_template,
                    "schedule_time": scheduled_datetime.strftime('%Y-%m-%dT%H:%M:%SZ')
                }
            )
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", email, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
            if _retryable_sailthru_error(error):
                raise self.retry(countdown=email_config.sailthru_retry_interval,
                                 max_retries=email_config.sailthru_max_retries)
Exemplo n.º 3
0
def update_user(self, username, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        username(str): A string representation of user identifier
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    # get user
    user = User.objects.select_related('profile').get(username=username)
    if not user:
        log.error("User not found during Sailthru update %s", username)
        return

    # get profile
    profile = user.profile
    if not profile:
        log.error("User profile not found during Sailthru update %s", username)
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_sailthru_user_parm(user, profile, new_user, email_config))
    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", username, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        # put out error and schedule retry
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        raise self.retry(countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        try:
            sailthru_response = sailthru_client.api_post("send",
                                                         {"email": user.email,
                                                          "template": email_config.sailthru_activation_template})
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", username, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            # probably an invalid template name, just put out error
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
Exemplo n.º 4
0
def update_user(self, sailthru_vars, email, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        sailthru_vars(dict): User profile information to pass as 'vars' to Sailthru
        email(str): User email address
        new_user(boolean): True if new registration
        activation(boolean): True if activation request
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_sailthru_user_parm(sailthru_vars, email,
                                                                                new_user, email_config))

    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        # put out error and schedule retry
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        raise self.retry(countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        try:
            sailthru_response = sailthru_client.api_post("send",
                                                         {"email": email,
                                                          "template": email_config.sailthru_activation_template})
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", email, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            # probably a disabled template, just put out error message
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
Exemplo n.º 5
0
def update_user_email(self, new_email, old_email):
    """
    Adds/updates Sailthru when a user email address is changed
     Args:
        username(str): A string representation of user identifier
        old_email(str): Original email address
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    # ignore if email not changed
    if new_email == old_email:
        return

    sailthru_parms = {"id": old_email, "key": "email", "keysconflict": "merge", "keys": {"email": new_email}}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to update email for %s in Sailthru - %s", old_email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        log.error("Error attempting to update user email address in Sailthru: %s", error.get_message())
        if _retryable_sailthru_error(error):
            raise self.retry(countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)
Exemplo n.º 6
0
def update_user_email(self, new_email, old_email):
    """
    Adds/updates Sailthru when a user email address is changed
     Args:
        username(str): A string representation of user identifier
        old_email(str): Original email address
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    # ignore if email not changed
    if new_email == old_email:
        return

    sailthru_parms = {"id": old_email, "key": "email", "keysconflict": "merge", "keys": {"email": new_email}}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to update email for %s in Sailthru - %s", old_email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        log.error("Error attempting to update user email address in Sailthru: %s", error.get_message())
        if _retryable_sailthru_error(error):
            raise self.retry(countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)
Exemplo n.º 7
0
def add_email_marketing_cookies(sender, response=None, user=None,
                                **kwargs):  # pylint: disable=unused-argument
    """
    Signal function for adding any cookies needed for email marketing

    Args:
        response: http response object
        user: The user object for the user being changed

    Returns:
        response: http response object with cookie added
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return response

    post_parms = {
        'id': user.email,
        'fields': {'keys': 1},
        'vars': {'last_login_date': datetime.datetime.now().strftime("%Y-%m-%d")}
    }

    # get anonymous_interest cookie to capture usage before logon
    request = crum.get_current_request()
    if request:
        sailthru_content = request.COOKIES.get('anonymous_interest')
        if sailthru_content:
            post_parms['cookies'] = {'anonymous_interest': sailthru_content}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        log.info(
            'Sending to Sailthru the user interest cookie [%s] for user [%s]',
            post_parms.get('cookies', ''),
            user.email
        )
        sailthru_response = \
            sailthru_client.api_post("user", post_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        return response

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']

            response.set_cookie(
                'sailthru_hid',
                cookie,
                max_age=365 * 24 * 60 * 60,  # set for 1 year
                domain=settings.SESSION_COOKIE_DOMAIN,
                path='/',
            )
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user.email)
    else:
        error = sailthru_response.get_error()
        # generally invalid email address
        log.info("Error attempting to obtain cookie from Sailthru: %s", error.get_message())
    return response
Exemplo n.º 8
0
def force_unsubscribe_all(sender, **kwargs):  # pylint: disable=unused-argument
    """
    Synchronously(!) unsubscribes the given user from all Sailthru email lists.

    In the future this could be moved to a Celery task, however this is currently
    only used as part of user retirement, where we need a very reliable indication
    of success or failure.

    Args:
        email: Email address to unsubscribe
        new_email (optional): Email address to change 3rd party services to for this user (used in retirement to clear
                              personal information from the service)
    Returns:
        None
    """
    email = kwargs.get('email', None)
    new_email = kwargs.get('new_email', None)

    if not email:
        raise TypeError(
            'Expected an email address to unsubscribe, but received None.')

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_parms = {
        "id": email,
        "optout_email": "all",
        "fields": {
            "optout_email": 1
        }
    }

    # If we have a new email address to change to, do that as well
    if new_email:
        sailthru_parms["keys"] = {"email": new_email}
        sailthru_parms["fields"]["keys"] = 1
        sailthru_parms["keysconflict"] = "merge"

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key,
                                         email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        error_msg = "Exception attempting to opt-out user {} from Sailthru - {}".format(
            email, text_type(exc))
        log.error(error_msg)
        raise Exception(error_msg)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        error_msg = "Error attempting to opt-out user {} from Sailthru - {}".format(
            email, error.get_message())
        log.error(error_msg)
        raise Exception(error_msg)
Exemplo n.º 9
0
def add_email_marketing_cookies(sender, response=None, user=None,
                                **kwargs):  # pylint: disable=unused-argument
    """
    Signal function for adding any cookies needed for email marketing

    Args:
        response: http response object
        user: The user object for the user being changed

    Returns:
        response: http response object with cookie added
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return response

    post_parms = {
        'id': user.email,
        'fields': {'keys': 1},
        'vars': {'last_login_date': datetime.datetime.now().strftime("%Y-%m-%d")}
    }

    # get sailthru_content cookie to capture usage before logon
    request = crum.get_current_request()
    if request:
        sailthru_content = request.COOKIES.get('sailthru_content')
        if sailthru_content:
            post_parms['cookies'] = {'sailthru_content': sailthru_content}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = \
            sailthru_client.api_post("user", post_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        return response

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']

            response.set_cookie(
                'sailthru_hid',
                cookie,
                max_age=365 * 24 * 60 * 60  # set for 1 year
            )
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user.email)
    else:
        error = sailthru_response.get_error()
        log.error("Error attempting to obtain cookie from Sailthru: %s", error.get_message())
    return response
Exemplo n.º 10
0
def force_unsubscribe_all(sender, **kwargs):  # pylint: disable=unused-argument
    """
    Synchronously(!) unsubscribes the given user from all Sailthru email lists.

    In the future this could be moved to a Celery task, however this is currently
    only used as part of user retirement, where we need a very reliable indication
    of success or failure.

    Args:
        email: Email address to unsubscribe
        new_email (optional): Email address to change 3rd party services to for this user (used in retirement to clear
                              personal information from the service)
    Returns:
        None
    """
    email = kwargs.get('email', None)
    new_email = kwargs.get('new_email', None)

    if not email:
        raise TypeError('Expected an email address to unsubscribe, but received None.')

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_parms = {
        "id": email,
        "optout_email": "all",
        "fields": {"optout_email": 1}
    }

    # If we have a new email address to change to, do that as well
    if new_email:
        sailthru_parms["keys"] = {
            "email": new_email
        }
        sailthru_parms["fields"]["keys"] = 1
        sailthru_parms["keysconflict"] = "merge"

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        error_msg = "Exception attempting to opt-out user {} from Sailthru - {}".format(email, text_type(exc))
        log.error(error_msg)
        raise Exception(error_msg)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        error_msg = "Error attempting to opt-out user {} from Sailthru - {}".format(email, error.get_message())
        log.error(error_msg)
        raise Exception(error_msg)
Exemplo n.º 11
0
def add_email_marketing_cookies(sender, response=None, user=None,
                                **kwargs):  # pylint: disable=unused-argument
    """
    Signal function for adding any cookies needed for email marketing

    Args:
        response: http response object
        user: The user object for the user being changed

    Returns:
        response: http response object with cookie added
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return response

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = \
            sailthru_client.api_post("user", {'id': user.email, 'fields': {'keys': 1},
                                              'vars': {'last_login_date':
                                                       datetime.datetime.now().strftime("%Y-%m-%d")}})
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        return response

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']

            response.set_cookie(
                'sailthru_hid',
                cookie,
                max_age=365 * 24 * 60 * 60  # set for 1 year
            )
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user.email)
    else:
        error = sailthru_response.get_error()
        log.error("Error attempting to obtain cookie from Sailthru: %s", error.get_message())
    return response
Exemplo n.º 12
0
def get_email_cookies_via_sailthru(self, user_email, post_parms):
    """
    Adds/updates Sailthru cookie information for a new user.
     Args:
        post_parms(dict): User profile information to pass as 'vars' to Sailthru
    Returns:
        cookie(str): cookie fetched from Sailthru
    """

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return None

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key,
                                         email_config.sailthru_secret)
        log.info(
            u'Sending to Sailthru the user interest cookie [%s] for user [%s]',
            post_parms.get('cookies', ''), user_email)
        sailthru_response = sailthru_client.api_post("user", post_parms)
    except SailthruClientError as exc:
        log.error(u"Exception attempting to obtain cookie from Sailthru: %s",
                  six.text_type(exc))
        raise SailthruClientError

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json[
                'keys']:
            cookie = sailthru_response.json['keys']['cookie']
            return cookie
        else:
            log.error(
                u"No cookie returned attempting to obtain cookie from Sailthru for %s",
                user_email)
    else:
        error = sailthru_response.get_error()
        # generally invalid email address
        log.info(u"Error attempting to obtain cookie from Sailthru: %s",
                 error.get_message())

    return None
def force_unsubscribe_all(sender, **kwargs):  # pylint: disable=unused-argument
    """
    Synchronously(!) unsubscribes the given user from all Sailthru email lists.

    In the future this could be moved to a Celery task, however this is currently
    only used as part of user retirement, where we need a very reliable indication
    of success or failure.

    Args:
        user(User): Django model of type returned from get_user_model()
    Returns:
        None
    """
    user = kwargs.get('user', None)

    if not user:
        raise TypeError('Expected a User type, but received None.')

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_parms = {"id": user.email, "keys": {"optout_email": "all"}}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key,
                                         email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        error_msg = "Exception attempting to opt-out user %s from Sailthru - %s" % (
            user.email, text_type(exc))
        log.error(error_msg)
        raise Exception(error_msg)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        error_msg = "Error attempting to opt-out user %s from Sailthru - %s" % (
            user.email, error.get_message())
        log.error(error_msg)
        raise Exception(error_msg)
Exemplo n.º 14
0
def get_email_cookies_via_sailthru(self, user_email, post_parms):
    """
    Adds/updates Sailthru cookie information for a new user.
     Args:
        post_parms(dict): User profile information to pass as 'vars' to Sailthru
    Returns:
        cookie(str): cookie fetched from Sailthru
    """

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return None

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        log.info(
            'Sending to Sailthru the user interest cookie [%s] for user [%s]',
            post_parms.get('cookies', ''),
            user_email
        )
        sailthru_response = sailthru_client.api_post("user", post_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        raise SailthruClientError

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']
            return cookie
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user_email)
    else:
        error = sailthru_response.get_error()
        # generally invalid email address
        log.info("Error attempting to obtain cookie from Sailthru: %s", error.get_message())

    return None
Exemplo n.º 15
0
        "vars": {
            "name": "Prajwal Tuladhar",
            "address": {
                "city": "New York",
                "state": "NY",
                "zip": 11372
            },
            "preferred_login": "******",
            "has_used_smartphone": true
        },
        "keys": {
            "fb": "infynyxx",
            "twitter": "infynyxx"
        }
    }
    response = sailthru_client.api_post("user", data)

    if response.is_ok():
        body = response.get_body()
        # handle body which is of type dictionary
        print body
    else:
        error = response.get_error()
        print "Error: " + error.get_message()
        print "Status Code: " + str(response.get_status_code())
        print "Error Code: " + str(error.get_error_code())
except SailthruClientError, e:
    # Handle exceptions
    print "Exception"
    print e
Exemplo n.º 16
0
        "vars": {
            "name": "Prajwal Tuladhar",
            "address": {
                "city": "New York",
                "state": "NY",
                "zip": 11372
            },
            "preferred_login": "******",
            "has_used_smartphone": true
        },
        "keys": {
            "fb": "infynyxx",
            "twitter": "infynyxx"
        }
    }
    response = sailthru_client.api_post("user", data)

    if response.is_ok():
        body = response.get_body()
        # handle body which is of type dictionary
        print(body)
    else:
        error = response.get_error()
        print("Error: " + error.get_message())
        print("Status Code: " + str(response.get_status_code()))
        print("Error Code: " + str(error.get_error_code()))
except SailthruClientError as e:
    # Handle exceptions
    print("Exception")
    print(e)
Exemplo n.º 17
0
class SailthruApiService(object):
    """The service to interface with Sailthru API"""
    def __init__(self, sailthru_key, sailthru_secret, content_url_root):
        self.sailthru_client = SailthruClient(sailthru_key, sailthru_secret)
        self.content_url_root = content_url_root

    def list(self, list_size=1000):
        sailthru_content_list = []
        response = self.sailthru_client.api_get('content', {'items': list_size})

        if not response.is_ok():
            logging.error(
                "Error code %d connecting to Sailthru content api: %s",
                response.json['error'],
                response.json['errormsg']
            )
        else:
            for body in response.json['content']:
                logging.info(body)
                sailthru_content_list.append(body)

        return sailthru_content_list

    def _upload_batch_file(self, filepath, report_email=None):
        """Use Sailthru job API to upload all content as a batch job"""
        logging.info("Uploading %s" % filepath)
        request_data = {
            'job': 'content_update',
            'file': filepath,
            'report_email': report_email
        }
        response = self.sailthru_client.api_post('job', request_data, {'file': 1})

        if response.is_ok():
            job_id = response.get_body().get("job_id")
            logging.info("Import job started on SailThru - JOB ID: " + job_id)

            # Keeping checking status until we find out that it's done
            while True:
                logging.info("waiting for import to complete...")
                time.sleep(10)
                response = self.sailthru_client.api_get('job', {'job_id': job_id})
                if response.get_body().get("status") == "completed":
                    return

        else:
            error = response.get_error()
            logging.error("Error: " + error.get_message())
            logging.error("Status Code: " + str(response.get_status_code()))
            logging.error("Error Code: " + str(error.get_error_code()))

    def upload(self, library_items, report_email=None):
        if not library_items:
            return

        with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
            for item in library_items:
                json.dump(item, tmp_file)
                tmp_file.write('\n')
            tmp_file.close()
            self._upload_batch_file(tmp_file.name, report_email)
            os.unlink(tmp_file.name)

    def clear(self):
        while True:
            response = self.sailthru_client.api_get('content', {'items': 4000})

            if not response.is_ok():
                logging.error(
                    "Error code %d connecting to Sailthru content api: %s",
                    response.json['error'],
                    response.json['errormsg']
                )
                return

            sailthru_content = response.json['content']
            if not sailthru_content:
                logging.info('Content cleared')
                return

            for body in sailthru_content:
                item_key = body.get('url')
                if item_key:
                    response = self.sailthru_client.api_delete('content', {'url': item_key})
                    if response.is_ok():
                        logging.info("content item %s deleted", item_key)
                    else:
                        logging.info("content item %s delete encountered errors", item_key)
Exemplo n.º 18
0
def update_user(self, sailthru_vars, email, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        sailthru_vars(dict): User profile information to pass as 'vars' to Sailthru
        email(str): User email address
        new_user(boolean): True if new registration
        activation(boolean): True if activation request
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_client = SailthruClient(email_config.sailthru_key,
                                     email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post(
            "user",
            _create_sailthru_user_parm(sailthru_vars, email, new_user,
                                       email_config))

    except SailthruClientError as exc:
        log.error(
            "Exception attempting to add/update user %s in Sailthru - %s",
            email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        # put out error and schedule retry
        log.error("Error attempting to add/update user in Sailthru: %s",
                  error.get_message())
        raise self.retry(countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        try:
            sailthru_response = sailthru_client.api_post(
                "send", {
                    "email": email,
                    "template": email_config.sailthru_activation_template
                })
        except SailthruClientError as exc:
            log.error(
                "Exception attempting to send welcome email to user %s in Sailthru - %s",
                email, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            # probably a disabled template, just put out error message
            log.error(
                "Error attempting to send welcome email to user in Sailthru: %s",
                error.get_message())
class SailthruApiService(object):
    """The service to interface with Sailthru API"""
    def __init__(self, sailthru_key, sailthru_secret, content_url_root):
        self.sailthru_client = SailthruClient(sailthru_key, sailthru_secret)
        self.content_url_root = content_url_root

    def list(self, list_size=1000):
        sailthru_content_list = []
        response = self.sailthru_client.api_get('content',
                                                {'items': list_size})

        if not response.is_ok():
            logging.error(
                "Error code %d connecting to Sailthru content api: %s",
                response.json['error'], response.json['errormsg'])
            raise RuntimeError('Failed to connect with Sailthru API')
        else:
            for body in response.json['content']:
                logging.info(body)
                sailthru_content_list.append(body)

        return sailthru_content_list

    def _upload_batch_file(self, filepath, report_email=None):
        """Use Sailthru job API to upload all content as a batch job"""
        logging.info("Uploading %s" % filepath)
        request_data = {
            'job': 'content_update',
            'file': filepath,
            'report_email': report_email
        }
        response = self.sailthru_client.api_post('job', request_data,
                                                 {'file': 1})

        if response.is_ok():
            job_id = response.get_body().get("job_id")
            logging.info("Import job started on SailThru - JOB ID: " + job_id)

            # Keeping checking status until we find out that it's done
            while True:
                logging.info("waiting for import to complete...")
                time.sleep(10)
                response = self.sailthru_client.api_get(
                    'job', {'job_id': job_id})
                if response.get_body().get("status") == "completed":
                    return

        else:
            error = response.get_error()
            logging.error("Error: " + error.get_message())
            logging.error("Status Code: " + str(response.get_status_code()))
            logging.error("Error Code: " + str(error.get_error_code()))
            raise RuntimeError('Failed to connect with Sailthru API')

    def upload(self, library_items, report_email=None):
        if not library_items:
            return

        with tempfile.NamedTemporaryFile(delete=False, mode='w+t') as tmp_file:
            for item in library_items:
                json.dump(item, tmp_file)
                tmp_file.write('\n')
            tmp_file.close()
            self._upload_batch_file(tmp_file.name, report_email)
            os.unlink(tmp_file.name)

    def clear(self):
        while True:
            response = self.sailthru_client.api_get('content', {'items': 4000})

            if not response.is_ok():
                logging.error(
                    "Error code %d connecting to Sailthru content api: %s",
                    response.json['error'], response.json['errormsg'])
                raise RuntimeError('Failed to connect with Sailthru API')

            sailthru_content = response.json['content']
            if not sailthru_content:
                logging.info('Content cleared')
                return

            for body in sailthru_content:
                item_key = body.get('url')
                if item_key:
                    response = self.sailthru_client.api_delete(
                        'content', {'url': item_key})
                    if response.is_ok():
                        logging.info("content item %s deleted", item_key)
                    else:
                        logging.info(
                            "content item %s delete encountered errors",
                            item_key)