Example #1
0
def send_to(message, phone_number):
    """Send a message to a single phone number."""

    if not waffle.switch_is_active('notifications-sms'):
        return None

    # Phone numbers must use E.164 format: https://en.wikipedia.org/wiki/E.164
    # If not, assume we're in the US.
    numbers = format_numbers([phone_number])
    if len(numbers) > 0:
        phone_number = numbers[0]

    # limit to 140chars
    message = message[:140]
    if message and phone_number:
        try:
            sns_client = get_client()

            response = sns_client.publish(
                PhoneNumber=phone_number,
                Message=message
                # TopicArn='string', (Optional - can't be used with PhoneNumer)
                # TargetArn='string', (Optional - can't be used with PhoneNumer)
                # Subject='string', (Optional - not used with PhoneNumer)
                # MessageStructure='string' (Optional)
            )
            metric('SMS Message Sent', category='Notifications')
            return response
        except:
            metric('SMS Message Failed', category='Notifications')
            return None
Example #2
0
def action_completed(sender, instance, created, raw, using, **kwargs):
    """Record metrics when a UserCompletedAction status is updated."""
    if instance.state:
        key = "action-{}".format(instance.state)
        metric(key, category="User Interactions")

    # Kill all of the queued messages that match this action when the trigger's
    # stop_on_complete is True
    completed = instance.state == UserCompletedAction.COMPLETED

    # Try to get the trigger (custom or default)
    trigger = instance.useraction.trigger

    if completed and trigger and trigger.stop_on_complete:
        messages = instance.user.gcmmessage_set.filter(
            object_id=instance.action.id,
            content_type=ContentType.objects.get_for_model(Action))
        messages.delete()

    # Check the UserAction's primary goal. If all of the UserActions
    # within taht primary goal are completed, mark the UserGoal as completed.
    ug = instance.usergoal
    if ug and completed and instance.sibling_actions_completed():
        ug.complete()
        ug.save()
Example #3
0
    def process_response(self, request, response):
        if self._key and self._start_time:
            # Capture the ending time and update our gauge
            self._end_time = time.time()

            # Set the gauge
            gauge(self._key, self._current_average_response_time())

            # Inspect the original response to see which endpoint was called
            metric(self._key, category="API Metrics")

        return response
Example #4
0
    def _set_expiration(self, days=7):
        """Set the date/time at which this object should be expired (i.e.
        deleted) from our database. We want to set an expiration for some point
        in the future, so that users can receive these messages, but then snooze
        them for some time.

        The script that does the deletion runs nightly.

        """
        if self.success:
            # Expire at some point in the future.
            self.expire_on = timezone.now() + timedelta(days=days)
            metric('GCM Message Sent', category='Notifications')
Example #5
0
def enqueue(message):
    """Given a GCMMessage object, add it to the queue of messages to be sent.

    - message: An instance of a GCMMessage

    Returns an rq Job instance (see job.id) or None if the message could not
    be scheduled.

    NOTE: This function records one of the following metrics:

    - GCM Message Scheduled (when a message is scheduled successfully)
    - Message Scheduling Failed (when it is not)

    Additionally, if the `notifications-user-userqueue` switch is enabled,
    the message will get queued throught the UserQueue, otherwise it
    gets enqueued in the scheduler directly.

    """
    job = None

    # Only queue up messages for the future or messages that should
    # have been sent within the past hour
    now = timezone.now() - timedelta(hours=1)
    is_upcoming = now < message.deliver_on

    if message.user and is_upcoming:
        if waffle.switch_is_active('notifications-user-userqueue'):
            # Enqueue messages through the UserQueue.
            job = UserQueue(message).add()
        else:
            job = scheduler.enqueue_at(message.deliver_on, send, message.id)
    if job:
        # Record a metric so we can see queued vs sent?
        metric('GCM Message Scheduled', category='Notifications')
    else:
        # Record a metric so we can see queued vs sent?
        metric('Message Scheduling Failed', category='Notifications')

    return job
Example #6
0
    def get_queryset(self):
        message_type = self.request.GET.get('type', None)
        author = self.request.GET.get('author', None)
        keywords = self.request.GET.getlist('keywords', [])
        random = self.request.GET.get('random', False)

        # Track metrics on the number of random reward content objects requested
        if random:
            metric('viewed-random-reward', category="Rewards")
            return [
                models.FunContent.objects.random(message_type=message_type)
            ]

        queryset = super().get_queryset()
        if message_type is not None:
            queryset = queryset.filter(message_type=message_type)

        if author is not None:
            queryset = queryset.filter(author__icontains=author)

        if keywords:
            queryset = queryset.filter(keywords__contains=keywords)

        return queryset
Example #7
0
def DMmetric(name):
    if settings.PRODUCTION:
        metric(name)
Example #8
0
 def __init__(self, *args, **kwargs):
     key = "{} created".format(self.__class__.__name__)
     metric(key, category="Tombstones")
     return super().__init__(*args, **kwargs)
Example #9
0
def DMmetric(name):
    if settings.PRODUCTION:
        metric(name)
Example #10
0
def user_adopted_content(sender, instance, created, raw, using, **kwargs):
    """Record some metrics when a user adopts a piece of content."""
    if created:
        key = "{}-created".format(sender.__name__.lower())
        metric(key, category="User Interactions")
Example #11
0
def custom_trigger_updated(sender, instance, created, raw, using, **kwargs):
    """Record metrics when a User updates their custom triggers."""
    if instance.user:
        metric('custom-trigger-updated', category="User Interactions")