def send_push_course_update(course_key_string, course_subscription_id,
                            course_display_name):
    """
    Sends a push notification for a course update, given the course's subscription_id and display_name.
    """
    if settings.PARSE_KEYS:
        try:
            register(
                settings.PARSE_KEYS["APPLICATION_ID"],
                settings.PARSE_KEYS["REST_API_KEY"],
            )
            Push.alert(
                data={
                    "course-id": course_key_string,
                    "action": "course.announcement",
                    "action-loc-key": "VIEW_BUTTON",
                    "loc-key": "COURSE_ANNOUNCEMENT_NOTIFICATION_BODY",
                    "loc-args": [course_display_name],
                    "title-loc-key": "COURSE_ANNOUNCEMENT_NOTIFICATION_TITLE",
                    "title-loc-args": [],
                },
                channels=[course_subscription_id],
            )
        except ParseError as error:
            log_exception(error.message)
示例#2
0
def new_message_email(sender, instance, created, **kwargs):
    """
    This function sends an email and is called via Django's signal framework.
    Optional arguments:
        ``template_name``: the template to use
        ``subject_prefix``: prefix for the email subject.
        ``default_protocol``: default protocol in site URL passed to template
    """
    if created and instance.recipient.email:
        context = {'message': instance}
        message = create_alternative_email('django_messages/new_message',
                                           context,
                                           settings.DEFAULT_FROM_EMAIL,
                                           [instance.recipient.email])
        message.send()
        #Parse notification
        print instance.recipient.email
        print instance.recipient.device_token
        if instance.recipient.device_token:
            print "NOTIFICATION"
            register(settings.PARSE_APPLICATION_ID,
                     settings.PARSE_REST_API_KEY)
            unread_count = instance.recipient.received_messages.filter(
                read_at=None).count()
            Push.alert(
                {
                    "alert": "Vous avez reçu un nouveau message",
                    "type": "MSG_NEW",
                    "user_id": instance.recipient.pk,
                    "count": unread_count,
                    "badge": unread_count,
                    "sound": "default"
                },
                where={"deviceToken": instance.recipient.device_token})
示例#3
0
def send_push_course_update(course_key_string, course_subscription_id, course_display_name):
    """
    Sends a push notification for a course update, given the course's subscription_id and display_name.
    """
    if settings.PARSE_KEYS:
        try:
            register(settings.PARSE_KEYS["APPLICATION_ID"], settings.PARSE_KEYS["REST_API_KEY"])
            push_payload = {
                "action": "course.announcement",
                "notification-id": unicode(uuid4()),
                "course-id": course_key_string,
                "course-name": course_display_name,
            }
            push_channels = [course_subscription_id]

            # Push to all Android devices
            Push.alert(data=push_payload, channels={"$in": push_channels}, where={"deviceType": "android"})

            # Push to all iOS devices
            # With additional payload so that
            # 1. The push is displayed automatically
            # 2. The app gets it even in the background.
            # See http://stackoverflow.com/questions/19239737/silent-push-notification-in-ios-7-does-not-work
            push_payload.update({"alert": "", "content-available": 1})
            Push.alert(data=push_payload, channels={"$in": push_channels}, where={"deviceType": "ios"})

        except ParseError as error:
            log_exception(error.message)
示例#4
0
    def pushtoken(pushtoken, os, event_type, trans_id, content, title='The Yub', data={}, uid=0, badge=1):
        """根据token推送
        pushtoken: 推送token
        os: 操作系统
        event_type: 事件类型
        trans_id: 交易id
        content: 显示内容
        title: 标题,只针对android用户
        data: 自定义报文,dict对象
        uid: 用户uid
        badge: APP右上角显示未阅读数
        """
        if not pushtoken or not os:
            log_info('[Push][PushError] pushtoken => %s, os => %s' % (pushtoken, os))
            return

        from parse_rest.connection import register
        from parse_rest.installation import Push as ParsePush
        parse_app_id  = current_app.config['PARSE_APP_ID']
        parse_app_key = current_app.config['PARSE_APP_KEY']
        register(parse_app_id, parse_app_key)

        where = {'objectId':pushtoken}
        push_params = {'badge':badge, 'uid':uid, 'data':data, 'sound':'default', 
            'event_type':event_type, 'trans_id':trans_id, 'alert':content, 'deviceType':os}

        ParsePush.alert(push_params, where=where)
示例#5
0
 def testCanAlert(self):
     Push.alert(
         {
             "alert": "The Mets scored! The game is now tied 1-1.",
             "badge": "Increment",
             "title": "Mets Score"
         },
         channels=["Mets"],
         where={"scores": True})
示例#6
0
def _send_push_notification(message, channels, **kwargs):
    try:
        if isinstance(message, basestring):
            Push.message(message, channels=channels, **kwargs)
        elif isinstance(message, dict):
            Push.alert(message, channels=channels, **kwargs)

    except Exception as e:
        logger.error(u'Failed to send push ({0}, {1}, {2}): {3}'.format(
            message, channels, kwargs, e))
    else:
        logger.info(u'Successfully sent push ({0}, {1}, {2})'.format(
            message, channels, kwargs))
    def dispatch_notification_to_user(self, user_id, msg, channel_context=None):
        """
        Send a notification to a user. It is assumed that
        'user_id' and 'msg' are valid and have already passed
        all necessary validations
        """

        # we ONLY can be called with user_id = _PARSE_SERVICE_USER_ID
        if user_id != _PARSE_SERVICE_USER_ID:
            raise ValueError(
                'You must call dispatch_notification_to_user with '
                'only the _PARSE_SERVICE_USER_ID constant!'
            )

        # we expect parse_channel_id in the channel_context
        if not channel_context or 'parse_channel_ids' not in channel_context:
            raise ValueError(
                'You must pass in a non-None channel_context with '
                'the "parse_channel_ids" defined!'
            )

        parse_channel_ids = channel_context.get('parse_channel_ids')

        # parse_channel_ids must be of type list
        if not isinstance(parse_channel_ids, list):
            raise TypeError(
                'The channel context parameter "parse_channel_ids" '
                'must be of python type "list"!'
            )

        # now connect to the Parse service and publish the mobile
        # push notification
        try:
            register(
                self.application_id,
                self.rest_api_key,
            )
            Push.alert(
                data=msg.payload,
                channels=parse_channel_ids,
            )
        except ParseError as error:
            # catch, log, and re-raise
            log.exception(error)

            # re-raise exception
            raise ChannelError(
                'ParsePushNotificationChannelProvider failed to call service. '
                'Error msg = {err_msg}'.format(err_msg=str(error))
            )
示例#8
0
    def dispatch_notification_to_user(self, user_id, msg, channel_context=None):
        """
        Send a notification to a user. It is assumed that
        'user_id' and 'msg' are valid and have already passed
        all necessary validations
        """

        # we ONLY can be called with user_id = _PARSE_SERVICE_USER_ID
        if user_id != _PARSE_SERVICE_USER_ID:
            raise ValueError(
                'You must call dispatch_notification_to_user with '
                'only the _PARSE_SERVICE_USER_ID constant!'
            )

        # we expect parse_channel_id in the channel_context
        if not channel_context or 'parse_channel_ids' not in channel_context:
            raise ValueError(
                'You must pass in a non-None channel_context with '
                'the "parse_channel_ids" defined!'
            )

        parse_channel_ids = channel_context.get('parse_channel_ids')

        # parse_channel_ids must be of type list
        if not isinstance(parse_channel_ids, list):
            raise TypeError(
                'The channel context parameter "parse_channel_ids" '
                'must be of python type "list"!'
            )

        # now connect to the Parse service and publish the mobile
        # push notification
        try:
            register(
                self.application_id,
                self.rest_api_key,
            )
            Push.alert(
                data=msg.payload,
                channels=parse_channel_ids,
            )
        except ParseError as error:
            # catch, log, and re-raise
            log.exception(error)

            # re-raise exception
            raise ChannelError(
                'ParsePushNotificationChannelProvider failed to call service. '
                'Error msg = {err_msg}'.format(err_msg=str(error))
            )
示例#9
0
 def send_notification(self, message, state, receiver):
     if receiver.device_token:
         register(settings.PARSE_APPLICATION_ID,
                  settings.PARSE_REST_API_KEY)
         Push.alert(
             {
                 "alert": message,
                 "booking_id": "%s" % self.uuid,
                 'type': state,
                 'user_id': receiver.pk,
                 'is_borrower':
                 True if receiver == self.borrower else False,
                 "sound": "default"
             },
             where={"deviceToken": receiver.device_token})
示例#10
0
    def send_tag(aps, tag_name):
        """parse 标签推送"""
        from parse_rest.connection import register
        from parse_rest.installation import Push as ParsePush
        parse_app_id  = "d44eWVZMfeiivL8vWg6S9mgiltSTQSrTyoT8sNOZ"
        parse_app_key = "RrvBWUH6FE1L1V2QcqyhNPbJKGtqKaBWuDWJGmlR"
        register(parse_app_id, parse_app_key)

        ParsePush.alert({'alert': aps['alert'],
                    'badge': aps['badge'],
                    'sound':aps['sound'],
                    'event_type':aps['event_type'],
                    'trans_id':aps['trans_id'],
                    'data':aps.get('data', {})},
                   where={"channels": tag_name})
示例#11
0
def send_push_course_update(course_key_string, course_subscription_id, course_display_name):
    """
    Sends a push notification for a course update, given the course's subscription_id and display_name.
    """
    if settings.PARSE_KEYS:
        try:
            register(
                settings.PARSE_KEYS["APPLICATION_ID"],
                settings.PARSE_KEYS["REST_API_KEY"],
            )
            push_payload = {
                "action": "course.announcement",
                "notification-id": unicode(uuid4()),

                "course-id": course_key_string,
                "course-name": course_display_name,
            }
            push_channels = [course_subscription_id]

            # Push to all Android devices
            Push.alert(
                data=push_payload,
                channels={"$in": push_channels},
                where={"deviceType": "android"},
            )

            # Push to all iOS devices
            # With additional payload so that
            # 1. The push is displayed automatically
            # 2. The app gets it even in the background.
            # See http://stackoverflow.com/questions/19239737/silent-push-notification-in-ios-7-does-not-work
            push_payload.update({
                "alert": "",
                "content-available": 1
            })
            Push.alert(
                data=push_payload,
                channels={"$in": push_channels},
                where={"deviceType": "ios"},
            )

        except ParseError as error:
            log_exception(text_type(error))
示例#12
0
def send_push_course_update(course_key_string, course_subscription_id, course_display_name):
    """
    Sends a push notification for a course update, given the course's subscription_id and display_name.
    """
    if settings.PARSE_KEYS:
        try:
            register(
                settings.PARSE_KEYS["APPLICATION_ID"],
                settings.PARSE_KEYS["REST_API_KEY"],
            )
            Push.alert(
                data={
                    "course-id": course_key_string,
                    "action": "course.announcement",
                    "action-loc-key": "VIEW_BUTTON",
                    "loc-key": "COURSE_ANNOUNCEMENT_NOTIFICATION_BODY",
                    "loc-args": [course_display_name],
                    "title-loc-key": "COURSE_ANNOUNCEMENT_NOTIFICATION_TITLE",
                    "title-loc-args": [],
                },
                channels=[course_subscription_id],
            )
        except ParseError as error:
            log_exception(error.message)
示例#13
0
文件: tests.py 项目: hsenju/Goober
 def testCanAlert(self):
     Push.alert(
         {"alert": "The Mets scored! The game is now tied 1-1.", "badge": "Increment", "title": "Mets Score"},
         channels=["Mets"],
         where={"scores": True},
     )
示例#14
0
文件: actions.py 项目: mhkane/colis
def notify(request, source, origin, target, target_id, email, text="", link="", activity_id=""):
    template_name = 'notifications'
    #  template variables
    
    target_user = User.Query.get(objectId = target_id)
    target_user_notif = ''
    try:
        target_user_notif = Notifications.Query.get(targetUser = target_id)
    except (QueryResourceDoesNotExist):
        pass
    print target_user_notif
    if source =='accept_request':
        header = 'Request Accepted by ' + origin
        info = origin + " accepted you request."
        title="You made a request on " + origin + "'s trip earlier..."
        user = target
        action = 'Check Airdeal'
        link = request.build_absolute_uri(link)
        main = origin + " just accepted your request, you can now wrap up the details with the traveler and have your item delivered soon."
        subject = header + ':' + origin
        
        send_template(template_name=template_name,var_header=header, var_user = user, var_info=info, var_title=title,
                  var_main = main, var_action=action, subject=subject, email = email, 
                  from_name='Airspress',from_email = '*****@*****.**')
        try:
            push_alert = origin + ' accepted your request!'
            Push.alert({"alert": push_alert,"badge": "Increment"}, 
                   where={"appUser":{"__type":"Pointer","className":"_User","objectId":target_id}})
        except:
            pass
        try:
            if target_user_notif:
                try:
                    
                    target_user_notif.increment("notifOutDeals")
                except AttributeError:
                    target_user.notifications.notifOutDeals = 1    
            else:
                
                    target_user_notif = Notifications(notifInDeals = 0, notifOutDeals = 1, notifInbox = 0, targetUser = target_user.objectId)
               
                    
            target_user_notif.save()
        except AttributeError:
            pass

    elif source.startswith("message"):
        header = 'New Message from ' + origin
        info = origin + " sent you a message."
        title="This is " + origin + "'s message :"
        user = target
        action = 'Check your deal' if source.endswith('deal') else "Check your inbox"
        link = request.build_absolute_uri(link)
        main = text
        subject = header + ':' + origin
        
        # email alert
        send_template(template_name=template_name,var_header=header, var_user = user, var_info=info, var_title=title,
                  var_main = main, var_action=action, subject=subject, email = email, 
                  from_name='Airspress',from_email = '*****@*****.**')
        # Push to smartphone
        try:
            push_alert = origin + ' sent you a message!'
            Push.alert({"alert": push_alert,"badge": "Increment"}, 
                   where={"appUser":{"__type":"Pointer","className":"_User","objectId":target_id}})
        except:
            pass   
        # update User notifications counter
        print 'target_id : '+ target_id
        print target_user
        if not source.endswith('deal'):
         
            try:    
                if target_user_notif:
                    print 'notif exist'
                    try:
                        print 'should work'
                        target_user_notif.notifInbox += 1
                        print 'it works', target_user_notif.notifInbox
                    except AttributeError:
                        target_user_notif.notifInbox = 1    
                else:
                    target_user_notif = Notifications(notifInDeals = 0, notifOutDeals = 0, notifInbox = 1, targetUser = target_user.objectId)
                print 'it''s out'
                target_user_notif.save()
            except AttributeError:
                pass
            
        else:
            this_deal = trequests.Query.get(objectId=activity_id)
            try:
                if this_deal.tripId.traveler.username == target_user.username:
                    if getattr(this_deal,'notifTraveler',False):
                        this_deal.increment("notifTraveler")
                    else:
                        this_deal.notifTraveler = 1
                    this_deal.save()
                        
                    if target_user_notif:
                        try:
                            
                            target_user_notif.increment("notifInDeals")
                        except AttributeError:
                            target_user_notif.notifInDeals = 1    
                    else:
                        target_user_notif = Notifications(notifInDeals = 1, notifOutDeals = 0, notifInbox = 0, targetUser = target_user.objectId)
                    target_user_notif.save()
                    
                elif this_deal.Requester.username == target_user.username:
                    if getattr(this_deal,'notifRequester',False):
                        this_deal.increment("notifRequester")
                    else:
                        this_deal.notifRequester = 1
                    this_deal.save()
                    if target_user_notif:
                        try:
                            
                            target_user_notif.increment("notifOutDeals")
                        except AttributeError:
                            target_user_notif.notifOutDeals = 1    
                    else:
                        target_user_notif = Notifications(notifInDeals = 0, notifOutDeals = 1, notifInbox = 0, targetUser = target_user.objectId)
                    target_user_notif.save()
                    
            except AttributeError:
                pass        
            
    elif source=="new_request":
        
        header = 'Request Sent '
        info = origin + " sent you a request."
        title= origin + " made a request on your trip ..."
        user = target
        action = 'Check incoming requests'
        link = request.build_absolute_uri(link)
        main = origin + " just sent you a request, you can accept, check request details and carry on with the process."
        subject = header + ': ' + origin
        
        send_template(template_name=template_name,var_header=header, var_user = user, var_info=info, var_title=title,
                  var_main = main, var_action=action, subject=subject, email = email, 
                  from_name='Airspress',from_email = '*****@*****.**')
        try:
            push_alert = origin + ' sent you a request!'
            Push.alert({"alert": push_alert,"badge": "Increment"}, 
                   where={"appUser":{"__type":"Pointer","className":"_User","objectId":target_id}})
        except:
            pass
        target_user = User.Query.get(objectId = target_id)
        try:
            if target_user_notif:
                try:
                    target_user_notif.increment("notifInDeals")
                except AttributeError:
                    target_user_notif.notifInDeals = 1    
            else:
                target_user_notif = Notifications(notifInDeals = 1, notifOutDeals = 0, notifInbox = 0, targetUser = target_user.objectId)
            target_user_notif.save()
        except AttributeError:
            pass
    return True