Esempio n. 1
0
def update_card():
    print('start update card')
    users = User.objects.all()
    for user in users:
        if user.card_drawer_of_next_day != '10102347454878415':
            user.update(card_drawer=None, draw_card_status='undraw')
        user.card_drawer = user.card_drawer_of_next_day
        user.card_drawer_of_next_day = None
        user.save()

    # send push notification
    print('send notification')
    try:
        user_list = User.objects.all()
        for user in user_list:
            if user.card_drawer != '10102347454878415':
                if user.device.ios != '':
                    custom_payload = {'type': 'card'}
                    payload = Payload(alert='已經有新的卡片囉!',
                                      sound="default",
                                      badge=1,
                                      custom=custom_payload)
                    client = APNsClient(APNS_CERT,
                                        use_sandbox=USE_SANDBOX,
                                        use_alternative_port=False)
                    client.send_notification(user.device.ios, payload,
                                             APNS_TOPIC)
        print('succeed')
    except Exception as e:
        print(e)
Esempio n. 2
0
    def _push(self, _apns, _body, _user_config):
        _ios_token = _user_config.get("device_ios_token")
        if _ios_token == None or len(_ios_token) == 0:
            return

        _user_language = _user_config.get("user_language") or "en_US"

        _title = push_title(_body.get("mt"), _body.get("ms"), _body.get("bo"),
                            _user_language)

        _sound = None
        if not _user_config.get("user_silence_notification"):
            _sound = "beep.wav"

        _count = _user_config.get("unacked_notification_count")
        _m = {"alert": _title, "sound": _sound, "badge": _count}

        from apns2.client import APNsClient
        from apns2.payload import Payload

        _dev = _user_config.get("is_development")
        _client = APNsClient(_apns.get("combination_pem"),
                             use_sandbox=False,
                             use_alternative_port=False)
        if _dev != None and _dev == True:
            _client = APNsClient(_apns.get("combination_pem"),
                                 use_sandbox=True,
                                 use_alternative_port=False)

        _payload = Payload(**_m)
        _client.send_notification(_ios_token, _payload)
        return
Esempio n. 3
0
def test_send_notification_failure_410():
    with patch("apns2.credentials.CertificateCredentials.create_connection"
               ) as create_connection_mock:
        http_client_mock = MagicMock()
        http_client_mock.post.return_value = Response(status_code=410,
                                                      json={
                                                          "reason":
                                                          "BadDeviceToken",
                                                          "timestamp":
                                                          time.time()
                                                      })

        create_connection_mock.return_value = http_client_mock

        client = APNsClient(CertificateCredentials("test/mycert.pem"))

        exception_raised = False
        try:
            client.send_notification(
                token_hex=TOKEN,
                notification=Payload(alert="Test alert"),
                topic=TOPIC,
            )
        except BadDeviceToken:
            exception_raised = True

        http_client_mock.post.assert_called_once()
        assert exception_raised is True
def send_Notification( message, key):

    token_hex = 'e4d3e8cb6e8c29d0dd6af4926e698c69632e2a8965cd17d66ed2d0cdd7869269'
    payload = Payload(alert="Hello World!", sound="default", badge=1)
    topic = 'ASU.SeatsFinderBot'
    client = APNsClient(key, use_sandbox=True, use_alternative_port=False)
    client.send_notification(token_hex, payload, topic)
    def send_Notification(self, message, key, device_id):

        token_hex = device_id
        payload = Payload(alert=message, sound="default", badge=1)
        topic = 'ASU.SeatsFinderBot'
        client = APNsClient(key, use_sandbox=False, use_alternative_port=False)
        client.send_notification(token_hex, payload, topic)
Esempio n. 6
0
class NotificationService:
    def __init__(self):
        self.topic = 'com.epage.QuietMind'
        self.token_map = {}
        self.client = APNsClient(DEV_CERT_FILE,
                                 use_sandbox=True,
                                 use_alternative_port=False)
        # self.apns = APNs(use_sandbox=True, cert_file=CERT_FILE, key_file=KEY_FILE)
        # self.apns = APNs(use_sandbox=True, cert_file=CERT_FILE, enhanced=True)
        # self.client = APNSClient(certificate=CERT_FILE,
        #                     default_error_timeout=10,
        #                     default_expiration_offset=2592000,
        #                     default_batch_size=100,
        #                     default_retries=3)

    def register_token(self, userId, token):
        print('register notification token', userId, token)
        self.token_map[userId] = token

    def get_token(self, userId):
        if userId in self.token_map:
            return self.token_map[userId]
        return DEFAULT_TOKEN

    def send_notification(self, userId, message="Hello World!"):

        token_hex = self.get_token(userId)
        payload = Payload(alert=message, sound="default", badge=1)
        print(payload.__dict__)
        topic = 'com.epage.QuietMind'

        self.client = APNsClient(DEV_CERT_FILE,
                                 use_sandbox=True,
                                 use_alternative_port=False)
        self.client.send_notification(token_hex, payload, topic)
Esempio n. 7
0
    def _push(self, _apns, _body, _user_config):
        _ios_token = _user_config.get("device_ios_token")
        if _ios_token == None or len(_ios_token) == 0:
            return

        _user_language = _user_config.get("user_language") or "en_US"
        
        _title = push_title(_body.get("mt"), _body.get("ms"), _body.get("bo"), _user_language)

        _sound = None
        if not _user_config.get("user_silence_notification"):
            _sound = "beep.wav"

        _count = _user_config.get("unacked_notification_count")
        _m = {"alert": _title, "sound": _sound, "badge": _count}

        from apns2.client import APNsClient
        from apns2.payload import Payload

        _dev = _user_config.get("is_development")
        _client = APNsClient(_apns.get("combination_pem"), use_sandbox=False, use_alternative_port=False)
        if _dev != None and _dev == True:
            _client = APNsClient(_apns.get("combination_pem"), use_sandbox=True, use_alternative_port=False)

        _payload = Payload(**_m)
        _client.send_notification(_ios_token, _payload)
        return
Esempio n. 8
0
    def send_ios(self, story, user, usersub):
        if not self.is_ios:
            return

        tokens = MUserNotificationTokens.get_tokens_for_user(self.user_id)
        # To update APNS:
        # 1. Create certificate signing requeswt in Keychain Access
        # 2. Upload to https://developer.apple.com/account/resources/certificates/list
        # 3. Download to secrets/certificates/ios/aps.cer
        # 4. Open in Keychain Access and export as aps.p12
        # 4. Export private key as aps_key.p12 WITH A PASSPHRASE (removed later)
        # 5. openssl pkcs12 -in aps.p12 -out aps.pem -nodes -clcerts -nokeys
        # 6. openssl pkcs12 -clcerts -nokeys -out aps.pem -in aps.p12
        # 7. cat aps.pem aps_key.noenc.pem > aps.p12.pem
        # 8. Verify: openssl s_client -connect gateway.push.apple.com:2195 -cert aps.p12.pem
        # 9. Deploy: aps -l work -t apns,repo,celery
        apns = APNsClient(
            '/srv/newsblur/config/certificates/aps.p12.pem', use_sandbox=tokens.use_sandbox
        )

        notification_title_only = is_true(user.profile.preference_value('notification_title_only'))
        title, subtitle, body = self.title_and_body(story, usersub, notification_title_only)
        image_url = None
        if len(story['image_urls']):
            image_url = story['image_urls'][0]
            # print image_url

        confirmed_ios_tokens = []
        for token in tokens.ios_tokens:
            logging.user(
                user,
                '~BMStory notification by iOS: ~FY~SB%s~SN~BM~FY/~SB%s'
                % (story['story_title'][:50], usersub.feed.feed_title[:50]),
            )
            payload = Payload(
                alert={'title': title, 'subtitle': subtitle, 'body': body},
                category="STORY_CATEGORY",
                mutable_content=True,
                custom={
                    'story_hash': story['story_hash'],
                    'story_feed_id': story['story_feed_id'],
                    'image_url': image_url,
                },
            )
            try:
                apns.send_notification(token, payload, topic="com.newsblur.NewsBlur")
            except (BadDeviceToken, Unregistered):
                logging.user(user, '~BMiOS token expired: ~FR~SB%s' % (token[:50]))
            else:
                confirmed_ios_tokens.append(token)
                if settings.DEBUG:
                    logging.user(
                        user,
                        '~BMiOS token good: ~FB~SB%s / %s'
                        % (token[:50], len(confirmed_ios_tokens)),
                    )

        if len(confirmed_ios_tokens) < len(tokens.ios_tokens):
            tokens.ios_tokens = confirmed_ios_tokens
            tokens.save()
Esempio n. 9
0
    def send_message(self, message=None, **kwargs):
        """Send push message to registered devices."""
        from apns2.client import APNsClient
        from apns2.payload import Payload
        from apns2.errors import Unregistered

        apns = APNsClient(
            self.certificate,
            use_sandbox=self.sandbox,
            use_alternative_port=False)

        device_state = kwargs.get(ATTR_TARGET)
        message_data = kwargs.get(ATTR_DATA)

        if message_data is None:
            message_data = {}

        if isinstance(message, str):
            rendered_message = message
        elif isinstance(message, template_helper.Template):
            rendered_message = message.render()
        else:
            rendered_message = ""

        payload = Payload(
            alert=rendered_message,
            badge=message_data.get("badge"),
            sound=message_data.get("sound"),
            category=message_data.get("category"),
            custom=message_data.get("custom", {}),
            content_available=message_data.get("content_available", False))

        device_update = False

        for push_id, device in self.devices.items():
            if not device.disabled:
                state = None
                if device.tracking_device_id is not None:
                    state = self.device_states.get(
                        device.full_tracking_device_id)

                if device_state is None or state == str(device_state):
                    try:
                        apns.send_notification(
                            push_id,
                            payload,
                            topic=self.topic)
                    except Unregistered:
                        logging.error(
                            "Device %s has unregistered.",
                            push_id)
                        device_update = True
                        device.disable()

        if device_update:
            self.write_devices()

        return True
Esempio n. 10
0
def send_apn(push_token: str):
    '''
    Sends an empty APN to the given device push_token
    '''
    payload = Payload()
    client = APNsClient(config.PASS_TYPE_CERTIFICATE_PATH,
                        use_sandbox=False,
                        use_alternative_port=False,
                        password=config.PEM_PASSWORD)
    client.send_notification(push_token, payload, config.PASS_TYPE_IDENTIFIER)
Esempio n. 11
0
    def send_message(self, message=None, **kwargs):
        """Send push message to registered devices."""
        from apns2.client import APNsClient
        from apns2.payload import Payload
        from apns2.errors import Unregistered

        apns = APNsClient(self.certificate,
                          use_sandbox=self.sandbox,
                          use_alternative_port=False)

        device_state = kwargs.get(ATTR_TARGET)
        message_data = kwargs.get(ATTR_DATA)

        if message_data is None:
            message_data = {}

        if isinstance(message, str):
            rendered_message = message
        elif isinstance(message, template_helper.Template):
            rendered_message = message.render()
        else:
            rendered_message = ""

        payload = Payload(
            alert=rendered_message,
            badge=message_data.get("badge"),
            sound=message_data.get("sound"),
            category=message_data.get("category"),
            custom=message_data.get("custom", {}),
            content_available=message_data.get("content_available", False),
        )

        device_update = False

        for push_id, device in self.devices.items():
            if not device.disabled:
                state = None
                if device.tracking_device_id is not None:
                    state = self.device_states.get(
                        device.full_tracking_device_id)

                if device_state is None or state == str(device_state):
                    try:
                        apns.send_notification(push_id,
                                               payload,
                                               topic=self.topic)
                    except Unregistered:
                        logging.error("Device %s has unregistered", push_id)
                        device_update = True
                        device.disable()

        if device_update:
            self.write_devices()

        return True
Esempio n. 12
0
def send_notification(apns_token, message, sender, channel, badge=1, network=None, intent=None, private=False):
    global apns_client

    if apns_client is None:
        apns_client = APNsClient(os.path.join(DIRECTORY, 'production.pem'), heartbeat_period=30)

    query = None

    if channel:
        query = channel
    elif sender:
        query = sender

    if message and intent == 'ACTION':
        message = '* %s' % (message)

    sound = None
    alert = {}

    if message or private:
        sound = 'default'

    user_info = {}

    if query and network:
        user_info['n'] = network
        user_info['q'] = query

    if sender:
        alert['title'] = sender

    if channel:
        alert['subtitle'] = channel

    if private:
        alert['loc-key'] = 'INPUT_MESSAGE_PLACEHOLDER'
        alert['body'] = 'Message'
    elif message:
        alert['body'] = message

    payload = Payload(alert=alert, sound=sound, badge=badge, custom=user_info)

    apns_client.connect()

    try:
        apns_client.send_notification(apns_token, payload, TOPIC)
    except (BadDeviceToken, Unregistered) as e:
        with database.transaction():
            try:
                device = Device.get(Device.apns_token == apns_token)
                device.delete_instance(recursive=True)
            except Device.DoesNotExist:
                return
Esempio n. 13
0
def push(request):
    #fcm_device = GCMDevice.objects.create(registration_id="e--N1a4DuTg:APA91bGrwQnf8h5o3UHrVPx3PTkTVumOEfHP5dfAdvFDuBA2h6QZVG0MYuQtGRH21nvdnb44sThudENkAeEtrmBND3g1gv2A0IlLW4ZMsCGl_AsBDWCR4FJm6s57pf-PPz5BGTkIWCbw", cloud_message_type="FCM", user='******')
    #device = GCMDevice.objects.get(registration_id="e--N1a4DuTg:APA91bGrwQnf8h5o3UHrVPx3PTkTVumOEfHP5dfAdvFDuBA2h6QZVG0MYuQtGRH21nvdnb44sThudENkAeEtrmBND3g1gv2A0IlLW4ZMsCGl_AsBDWCR4FJm6s57pf-PPz5BGTkIWCbw")

    token_hex = '106ececed6c5985efb2afd75618a41120086e7e93488315dc03ccd9eff0be257'
    payload = Payload(alert="Hello World!", sound="default", badge=1)
    topic = 'com.example.App'
    client = APNsClient(
        'https://s3-us-west-1.amazonaws.com/blake-deets/aps_development.cer',
        use_sandbox=False,
        use_alternative_port=False)
    client.send_notification(token_hex, payload, topic)
Esempio n. 14
0
def sendpushnotification(DeviceToken, OrderID, StoreID, dev_flag, Message):
    #send the push notification
    custom = {'launchURL': 'x-com.petco.wrapper.sim://launch'}
    payload = Payload(alert=Message,
                      sound="popcorn.wav",
                      badge=0,
                      custom=custom)
    topic = 'com.petco.notifications'
    IOS_Client = APNsClient('./Apple_Certificate/server1.pem',
                            use_sandbox=dev_flag,
                            use_alternative_port=False)
    IOS_Client.send_notification(DeviceToken, payload, topic)
    return True
Esempio n. 15
0
class Notifier:
    def __init__(self):
        self.client = APNsClient(cert, use_sandbox=sandbox, use_alternative_port=False)
        
    def send(self, token, message, count, isSilent):
        if isSilent:
            payload = Payload(content_available=True, badge=count)
        else:
            # TODO create custom sound (more so on client)
            payload = Payload(alert=message, sound="default", badge=count)
        topic = 'com.bfichter.KookMachine'
        self.client.send_notification(token, payload, topic)
        
Esempio n. 16
0
    def send_ios(self, story, user, usersub):
        if not self.is_ios: return

        tokens = MUserNotificationTokens.get_tokens_for_user(self.user_id)
        apns = APNsClient('/srv/newsblur/config/certificates/aps.p12.pem',
                          use_sandbox=tokens.use_sandbox)

        notification_title_only = is_true(
            user.profile.preference_value('notification_title_only'))
        title, subtitle, body = self.title_and_body(story, usersub,
                                                    notification_title_only)
        image_url = None
        if len(story['image_urls']):
            image_url = story['image_urls'][0]
            # print image_url

        confirmed_ios_tokens = []
        for token in tokens.ios_tokens:
            logging.user(
                user, '~BMStory notification by iOS: ~FY~SB%s~SN~BM~FY/~SB%s' %
                (story['story_title'][:50], usersub.feed.feed_title[:50]))
            payload = Payload(alert={
                'title': title,
                'subtitle': subtitle,
                'body': body
            },
                              category="STORY_CATEGORY",
                              mutable_content=True,
                              custom={
                                  'story_hash': story['story_hash'],
                                  'story_feed_id': story['story_feed_id'],
                                  'image_url': image_url,
                              })
            try:
                apns.send_notification(token,
                                       payload,
                                       topic="com.newsblur.NewsBlur")
            except (BadDeviceToken, Unregistered):
                logging.user(user,
                             '~BMiOS token expired: ~FR~SB%s' % (token[:50]))
            else:
                confirmed_ios_tokens.append(token)
                if settings.DEBUG:
                    logging.user(
                        user, '~BMiOS token good: ~FB~SB%s / %s' %
                        (token[:50], len(confirmed_ios_tokens)))

        if len(confirmed_ios_tokens) < len(tokens.ios_tokens):
            tokens.ios_tokens = confirmed_ios_tokens
            tokens.save()
Esempio n. 17
0
def send_apn_notification(message, endpoint):
    token = endpoint.device_token
    payload = Payload(alert=message, sound="default", badge=1)
    if settings.APNS_CERT_FILE:
        # allows for reuse of apns client and reuse of connections
        # TODO: handles errors by fcm client
        global apns_client
        if not apns_client:
            apns_client = APNsClient(settings.APNS_CERT_FILE,
                                     password=settings.APNS_CERT_PASSWORD,
                                     use_sandbox=settings.DEBUG,
                                     use_alternative_port=False)
        topic = settings.APNS_APP_BUNDLE_ID
        apns_client.send_notification(token, payload, topic)
Esempio n. 18
0
    def send_push(self, title, body):
        connects = UserConnectionField.objects.find_type_connection_by_user(
            self.user, UserConnectionField.APNS_TYPE)

        client = APNsClient(settings.APNS_KEY_LOCATION,
                            use_sandbox=settings.APNS_SENDBOX,
                            use_alternative_port=False)

        payload = Payload(alert=PayloadAlert(title=title, body=body),
                          sound="default",
                          badge=1)
        for connect in connects:
            client.send_notification(token_hex=connect.value,
                                     notification=payload,
                                     topic=settings.APNS_BUNDLE_ID)
Esempio n. 19
0
def push(category, title, body, device_token, params):
    payload = Payload(alert=PayloadAlert(title=None if title == '' else title,
                                         body=body),
                      sound='1107',
                      badge=int(params['badge']) if 'badge' in params else 0,
                      category=category,
                      mutable_content=True,
                      custom=params)
    client = APNsClient(CERT_PATH)

    try:
        client.send_notification(device_token, payload, 'me.fin.bark')
        return ''
    except APNsException as e:
        return str(e)
Esempio n. 20
0
def test_send_notification_success():
    with patch("apns2.credentials.CertificateCredentials.create_connection"
               ) as create_connection_mock:
        http_client_mock = MagicMock()
        http_client_mock.post.return_value = Mock(status_code=200)

        create_connection_mock.return_value = http_client_mock

        client = APNsClient(CertificateCredentials("test/mycert.pem"))
        client.send_notification(
            token_hex=TOKEN,
            notification=Payload(alert="Test alert"),
            topic=TOPIC,
        )

        http_client_mock.post.assert_called_once()
Esempio n. 21
0
def send_notification(user_id, st_code, condition, curr_value):

    logger.info("User to notify: %s" % user_id)
    notif_flag = False

    # Get the real name of the station
    station_name = Station.query.filter(Station.code == st_code).one().name
    logger.info("Station to be notified about: %s" % station_name)

    # Get the notification token from the users table
    token_hex = User.query.filter(User.device_id == user_id).one().notif_token
    logger.info("Notification token: %s" % token_hex)

    # Get the key, key path and team_id from the constants file and build
    # token credentials object
    token_credentials = TokenCredentials(auth_key_path=NOTIF_AUTH_KEY_PATH,
                                         auth_key_id=NOTIF_AUTH_KEY_ID,
                                         team_id=NOTIF_TEAM_ID)

    # Compose the text
    notif_text = notif_texts_format[condition['dimension']][condition['quantifier']] % \
                 (station_name,condition['value'],float(curr_value))
    logger.info("Sending notification: %s" % notif_text)

    # Compose the dict with the station code and station name
    custom_data = {'station_code': st_code, 'station_name': station_name}

    topic = NOTIF_TOPIC
    payload = Payload(alert=notif_text,
                      sound="default",
                      badge=0,
                      custom=custom_data)
    client = APNsClient(credentials=token_credentials, use_sandbox=True)
    try:
        #apns.gateway_server.send_notification(token_hex, payload,identifier=identifier)
        client.send_notification(token_hex, payload, topic)
        mark_as_notified(user_id, st_code, condition)
        logger.info("Notification sent!")
        notif_flag = True
    except:
        logger.error("Error sending notification!!")
        print("ERROR ENVIANDO NOTIFICACION")

    return notif_flag
Esempio n. 22
0
class NotificationPusher(object):
    def __init__(self,
                 topic,
                 auth_key_path,
                 auth_key_id,
                 team_id,
                 use_sandbox=False):
        self.topic = topic

        self.client = APNsClient(TokenCredentials(auth_key_path, auth_key_id,
                                                  team_id),
                                 use_sandbox=use_sandbox,
                                 use_alternative_port=False)

    def push(self, token_hex, beverage):
        payload = Payload(alert=f"{beverage} is ready!",
                          sound="default",
                          badge=1)
        self.client.send_notification(token_hex, payload, self.topic)
Esempio n. 23
0
class SMS:
    """ Push SMS via APNs """

    def __init__(self, text: str):
        self.__client = APNsClient(credentials=credentials, use_sandbox=use_sandbox)
        self.__payload = Payload(alert=text)

    def send(self, identifier: str) -> int:
        identifier = ID.parse(identifier=identifier)
        device = Device(identifier)
        tokens = device.tokens
        if tokens is None:
            print('Device token not found, failed to push message: %s' % self.__payload.alert)
            return 0
        count = 0
        for token in tokens:
            self.__client.send_notification(token_hex=token, notification=self.__payload)
            count += 1
        print('Message has been sent to %d device(s)' % count)
        return count
Esempio n. 24
0
 def push_notification(self, credentials, push_sandbox, pass_type_id, push_token):
     payload = Payload()
     try:
         client = APNsClient(
             credentials,
             use_sandbox=push_sandbox,
             use_alternative_port=False,
         )
         client.send_notification(
             push_token,
             payload,
             pass_type_id,
         )
     except SSLError as e:
         logger.error("django_walletpass SSLError: %s", e)
     except StreamResetError as e:
         logger.error("django_walletpass StreamResetError. Bad cert or token? %s", e)
     # Errors should never pass silently.
     except Exception as e:
         # Unless explicitly silenced.
         logger.error("django_walletpass uncaught error %s", e)
Esempio n. 25
0
def send_pushs(followers, ng_group, ng_news):
    father = ng_news
    while father.father != '':
        try:
            father = NGNews.objects.get(message_id=father.father)
        except NGNews.DoesNotExists:
            break
    data = {
        'event_type': 'NEW_NEWS',
        'host': ng_group.host.host,
        'newsgroup_id': ng_group.id,
        'newsgroup': ng_group.name,
        'news_id': ng_news.id,
        'news_uid': ng_news.message_id,
        'subject': ng_news.subject,
        'author': ng_news.email_from,
        'creation_date': ng_news.date.strftime("%Y-%m-%dT%H:%M:%S%z")
    }

    # Google Android devices
    android_devices = GCMDevice.objects.filter(user__in=followers, active=1)

    for android_device in android_devices:
        log = Log()
        log.type = 'N'
        log.group = ng_group
        log.user = android_device.user
        log.description = "Android notification (registration_id=%s) (subject=%s)"\
                          % (android_device.registration_id, ng_news.subject)
        log.save()
    android_devices.send_message(json.dumps(data))

    # Apple iOS devices
    ios_devices = APNSDevice.objects.filter(user__in=followers, active=1)

    apns_cert_prod = PUSH_NOTIFICATIONS_SETTINGS['APNS_CERTIFICATE']
    apns_cert_dev = PUSH_NOTIFICATIONS_SETTINGS['APNS_CERTIFICATE_DEV']
    apns_cert_password = PUSH_NOTIFICATIONS_SETTINGS[
        'APNS_CERTIFICATE_PASSWORD']
    topic = PUSH_NOTIFICATIONS_SETTINGS['APNS_TOPIC']
    payload = CustomPayload(group=data['newsgroup'],
                            title=data['subject'],
                            contents=ng_news.contents,
                            sound="default",
                            badge=1,
                            news_id=father.id,
                            author=ng_news.email_from)
    client_prod = APNsClient(apns_cert_prod,
                             use_sandbox=False,
                             use_alternative_port=False,
                             password=apns_cert_password)
    client_dev = APNsClient(apns_cert_dev,
                            use_sandbox=True,
                            use_alternative_port=False,
                            password=apns_cert_password)
    for ios_device in ios_devices:
        token = ios_device.registration_id
        success = False
        try:
            client_prod.send_notification(token, payload, topic)
            success = True
        except:
            try:
                client_dev.send_notification(token, payload, topic)
                success = True
            except Exception as e:
                print(str(e))
                pass
                #ios_device.active = False
                #ios_device.save()
        if success:
            log = Log()
            log.type = 'N'
            log.group = ng_group
            log.user = ios_device.user
            log.description = "iOs notification (registration_id=%s) (subject=%s)" \
                              % (token, ng_news.subject)
            log.save()
Esempio n. 26
0
    def receive(self, text_data):
        # get parameter
        text_data_json = json.loads(text_data)
        self.scope['user'] = text_data_json['user_id']
        content = text_data_json['content']
        time = text_data_json['time']

        # save message to DB
        message = Message.objects.get(message_id=self.scope['message_id'])
        id = len(message.messages) + 1
        new_message_content = MessageContent(id=id,
                                             user_id=self.scope['user'],
                                             time=time,
                                             content=content)
        message.update(add_to_set__messages=new_message_content)

        # Send Push Notifications
        if message.user_id.user_1 == self.scope['user']:
            receiver_user = message.user_id.user_2
            receiver_user_notification = message.notification.user_2
        else:
            receiver_user = message.user_id.user_1
            receiver_user_notification = message.notification.user_1
        send_user = User.objects.get(user_id=self.scope['user'])
        receiver_user = User.objects.get(user_id=receiver_user)
        receiver_user_ios_device_id = receiver_user.device.ios
        try:
            if receiver_user_ios_device_id != '' and receiver_user_notification:
                notification_content = send_user.english_name + ': ' + content
                custom_payload = {
                    'type': 'message',
                    'message_id': self.scope['message_id'],
                    'user_id': send_user.user_id,
                    'english_name': send_user.english_name,
                    'chinese_name': send_user.chinese_name,
                    'photo': send_user.photo
                }
                payload = Payload(alert=notification_content,
                                  sound="default",
                                  badge=1,
                                  custom=custom_payload)
                client = APNsClient(APNS_CERT,
                                    use_sandbox=USE_SANDBOX,
                                    use_alternative_port=False)
                client.send_notification(receiver_user_ios_device_id, payload,
                                         APNS_TOPIC)
        except Exception as e:
            print(e)

        # Send WebSocket
        async_to_sync(self.channel_layer.group_send)(
            self.scope['room_name'],
            {
                "type":
                "chat.message",
                "text":
                json.dumps({
                    "content_id": id,
                    "user_id": self.scope['user'],
                    "time": time,
                    "content": content,
                }),
            },
        )
Esempio n. 27
0
 def _send_via_apn(self, apns_token, data):
     payload = Payload(alert=data, sound="default", badge=1)
     client = APNsClient(self.external_config['ios_apns_cert'],
                         use_sandbox=self.external_config['is_sandbox'],
                         use_alternative_port=False)
     client.send_notification(apns_token, payload, 'io.wazo.songbird.voip')
Esempio n. 28
0
class ApplePushNotificationService:

    class Delegate(ABC):
        """
            APNs Delegate
            ~~~~~~~~~~~~~
        """

        @abstractmethod
        def device_tokens(self, identifier: ID) -> List[str]:
            """ get device tokens in hex format """
            pass

    def __init__(self, credentials, use_sandbox=False, use_alternative_port=False, proto=None, json_encoder=None,
                 password=None, proxy_host=None, proxy_port=None):
        super().__init__()
        # APNs client parameters
        self.credentials = credentials
        self.use_sandbox = use_sandbox
        self.use_alternative_port = use_alternative_port
        self.proto = proto
        self.json_encoder = json_encoder
        self.password = password
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.client = None  # APNsClient
        # topic
        self.topic = 'chat.dim.sechat'
        # delegate to get device token
        self.__delegate: weakref.ReferenceType = None  # APNs Delegate
        # counting offline messages
        self.badge_table = {}

    def debug(self, msg: str):
        Log.debug('%s >\t%s' % (self.__class__.__name__, msg))

    def info(self, msg: str):
        Log.info('%s >\t%s' % (self.__class__.__name__, msg))

    def warning(self, msg: str):
        Log.warning('%s >\t%s' % (self.__class__.__name__, msg))

    def error(self, msg: str):
        Log.error('%s >\t%s' % (self.__class__.__name__, msg))

    @property
    def delegate(self) -> Delegate:
        if self.__delegate is not None:
            return self.__delegate()

    @delegate.setter
    def delegate(self, value: Delegate):
        self.__delegate = weakref.ref(value)

    def badge(self, identifier: ID) -> int:
        num = self.badge_table.get(identifier)
        if num is None:
            num = 1
        else:
            num = num + 1
        self.badge_table[identifier] = num
        return num

    def clear_badge(self, identifier: ID) -> bool:
        if identifier in self.badge_table:
            self.badge_table.pop(identifier)
            return True

    def connect(self) -> bool:
        try:
            self.client = APNsClient(credentials=self.credentials, use_sandbox=self.use_sandbox,
                                     use_alternative_port=self.use_alternative_port,
                                     proto=self.proto, json_encoder=self.json_encoder, password=self.password,
                                     proxy_host=self.proxy_host, proxy_port=self.proxy_port)
            return True
        except IOError as error:
            self.error('failed to connect apple server: %s' % error)
            return False

    def send_notification(self, token_hex, notification, topic=None,
                          priority=NotificationPriority.Immediate, expiration=None, collapse_id=None) -> int:
        if self.client is None and self.connect() is False:
            self.error('cannot connect apple server, message dropped: %s' % notification)
            return -503  # Service Unavailable
        try:
            if topic is None:
                topic = self.topic
            # push to apple server
            self.client.send_notification(token_hex=token_hex, notification=notification, topic=topic,
                                          priority=priority, expiration=expiration, collapse_id=collapse_id)
            return 200  # OK
        except IOError as error:
            self.error('connection lost: %s' % error)
            return -408  # Request Timeout
        except APNsException as error:
            self.error('failed to push notification: %s, error %s' % (notification, error))
            return -400  # Bad Request

    def push(self, identifier: ID, message: str) -> bool:
        # 1. check
        tokens = self.delegate.device_tokens(identifier=identifier)
        if tokens is None:
            self.error('cannot get device token for user %s' % identifier)
            return False
        # 2. send
        badge = self.badge(identifier)
        payload = Payload(alert=message, badge=badge, sound='default')
        success = 0
        for token in tokens:
            self.debug('sending notification %s to user %s with token %s' % (message, identifier, token))
            # first try
            result = self.send_notification(token_hex=token, notification=payload)
            if result == -503:  # Service Unavailable
                # connection failed
                break
            elif result == -408:  # Request Timeout
                self.error('Broken pipe? try to reconnect again!')
                # reset APNs client
                self.client = None
                # try again
                result = self.send_notification(token_hex=token, notification=payload)
            if result == 200:  # OK
                success = success + 1
        if success > 0:
            self.info('sending notification success:%d badge=%d, %s' % (success, badge, identifier))
            return True
Esempio n. 29
0
from apns2.client import APNsClient
from apns2.payload import Payload

CERT_FILE = "./apns-dev.pem"
KEY_FILE = "./apns-dev-key-noenc.pem"

token_hex = 'f7ca3b57016e6882fe11b7253e16b2068bdee0f119800b4271456bb04e896149'
payload = Payload(alert="Hello World!", sound="default", badge=1)
print(payload.__dict__)
topic = 'com.epage.QuietMind'

client = APNsClient(CERT_FILE, use_sandbox=True, use_alternative_port=False)
client.send_notification(token_hex, payload, topic)
Esempio n. 30
0
def draw_card():
    userList = list()
    users = User.objects.all()
    users.update(card_drawer=None, friend_invitation=None, is_draw_card=False)

    for user in users:
        # remove Thomas
        if user.user_id != '10102347454878415':
            userList.append(user)

    # need to handle this issue
    removed_user = ''
    if len(userList) % 2 != 0:
        print('remove one user')
        removed_user = random.SystemRandom().choice(userList)
        print(removed_user)
        for user_index in range(len(userList)):
            if userList[user_index].user_id == removed_user.user_id:
                lastUser = userList.pop(user_index)
                print(lastUser)
                break

        # give a card to removed user
        find_new_card = True
        while find_new_card:
            removed_user_card = random.SystemRandom().choice(userList)
            removed_user_instance = User.objects.get(
                user_id=removed_user.user_id)
            removed_user_friends = removed_user_instance.friends
            is_friend = False
            for friend in removed_user_friends:
                if friend.user_id == removed_user_card.user_id:
                    is_friend = True
                    break
            if not is_friend:
                removed_user_instance.update(
                    card_drawer=removed_user_card.user_id)
                find_new_card = False

    # assign removed user id to 'removed_user_id' if there is removed user
    if removed_user != '':
        removed_user_id = removed_user.user_id
    else:
        removed_user_id = ''

    loopTime = len(userList) / 2 - 1
    count = 0
    while count < loopTime:
        print(len(userList))
        pairUser = random.SystemRandom().sample(userList, 2)
        print(pairUser)

        firstUserId = str(pairUser[0])
        secondUserId = str(pairUser[1])

        firstUser = User.objects.get(user_id=firstUserId)
        friends = list(firstUser.friends)

        is_friend = False
        for friend in friends:
            if friend.user_id == secondUserId:
                print("these two users are already friends.")
                is_friend = True
                break
        if is_friend:
            continue

        firstUser.update(card_drawer=secondUserId)
        secondUser = User.objects.get(user_id=secondUserId)
        secondUser.update(card_drawer=firstUserId)

        for user in pairUser:
            userList.remove(user)
        print(len(userList))
        count += 1

    #   match last two users:
    #   need to check if last two users are already friends
    print('start to match last two users')
    is_friend = False
    first_user = User.objects.get(user_id=str(userList[0]))
    second_user = User.objects.get(user_id=str(userList[1]))
    first_user_friends = first_user.friends
    second_user_friends = second_user.friends

    for friend in first_user_friends:
        print('first user:'******'friend id:', friend.user_id)
        print('second user:'******'is_friend:', is_friend)

    if is_friend:
        check_list = list()
        check_list.append(str(first_user))
        check_list.append(str(second_user))
        for friend in first_user_friends:
            check_list.append(str(friend.user_id))

        for friend in second_user_friends:
            if not str(friend.user_id) in check_list:
                check_list.append(str(friend.user_id))

        selected_user_list = list()
        users = User.objects.all()
        removed_user_list = [
            str(first_user),
            str(second_user), removed_user_id, '10102347454878415'
        ]
        for user in users:
            if user.user_id not in removed_user_list and user.card_drawer != '':
                selected_user_list.append(user)
        print(selected_user_list)

        first_selected_user = None
        second_selected_user = None
        check_first_selected_user = False
        check_second_selected_user = False
        count_rematch_time = 0
        while not check_first_selected_user or not check_second_selected_user:
            count_rematch_time += 1
            print("check if the selected users are in the check list.")
            check_first_selected_user = False
            check_second_selected_user = False

            first_selected_user = random.SystemRandom().choice(
                selected_user_list)
            second_selected_user_id = User.objects.get(
                user_id=str(first_selected_user)).card_drawer
            second_selected_user = User.objects.get(
                user_id=str(second_selected_user_id))

            if not str(first_selected_user.user_id) in check_list:
                check_first_selected_user = True
                print("first selected user is not in the check list.")
            if not str(second_selected_user.user_id) in check_list:
                check_second_selected_user = True
                print("second selected user is not in the check list.")
            if count_rematch_time > 20:
                print('restart')
                return draw_card()

        first_user.update(card_drawer=str(first_selected_user.user_id))
        first_selected_user.update(card_drawer=str(first_user.user_id))
        second_user.update(card_drawer=str(second_selected_user.user_id))
        second_selected_user.update(card_drawer=str(second_user.user_id))
        print("first: ", first_user)
        print("first select: :", first_selected_user)
        print("second: ", second_user)
        print("second select: :", second_selected_user)
        print("match last two users with other two users.")

    else:
        print("match last two users.")
        second_user.update(card_drawer=str(first_user))
        first_user.update(card_drawer=str(second_user))

    print('start to send notifications')
    try:
        user_list = User.objects.all()
        for user in user_list:
            if user.device.ios != '':
                # print(user.device.ios)
                custom_payload = {'type': 'card'}
                payload = Payload(alert='已經有新的卡片囉!',
                                  sound="default",
                                  badge=1,
                                  custom=custom_payload)
                client = APNsClient(APNS_CERT,
                                    use_sandbox=USE_SANDBOX,
                                    use_alternative_port=False)
                client.send_notification(user.device.ios, payload, APNS_TOPIC)
        # me = User.objects.get(user_id='10210833777112798')
        # if me.device.ios != '':
        #     custome_payload = {
        #         'type': 'card'
        #     }
        #     payload = Payload(alert='已經有新的卡片囉!', sound="default", badge=1, custom=custome_payload)
        #     client = APNsClient(APNS_CERT, use_sandbox=USE_SANDBOX, use_alternative_port=False)
        #     client.send_notification(me.device.ios, payload, APNS_TOPIC)
    except Exception as e:
        print(e)
    print('finished')
Esempio n. 31
0
time_start = time.time()

db = pymysql.connect(config.SQL_SERVER_ADDRESS, config.SQL_SERVER_USER,
                     config.SQL_SERVER_PASSWORD, config.SQL_SERVER_DATABASE)

cursor = db.cursor()

cursor.execute("SELECT * FROM apns")
results = list(set(cursor.fetchall()))
invalid_list = []
for row in results:
    token_id = row[0]
    token = row[1]
    try:
        client.send_notification(token, Payload(content_available=1), TOPIC)
        time.sleep(0.08)
    except BadDeviceToken:
        invalid_list.append(token_id)
    except Unregistered:
        invalid_list.append(token_id)
for token_id in invalid_list:
    cursor.execute("DELETE FROM apns WHERE id = %d" % int(token_id))

db.commit()
db.close()
f = open("log", "a")
f.write(str(datetime.datetime.now()))
f.write("\nNotification Pushed. %d devices. %d devices are removed.\n" %
        (len(results), len(invalid_list)))
f.write("Time Used = %ds\n" % (time.time() - time_start))
Esempio n. 32
0
def watch_rooms(docs, changes, read_time):
    for change in changes:
        try:
            if (change.type.name == "ADDED") or \
               (change.type.name == "MODIFIED") or \
               (change.type.name == "REMOVED"):
                room = change.document.to_dict()
                if (change.type.name == "REMOVED"):
                    room["users"] = []
                if (change.document.id not in last_rooms):
                    last_rooms[change.document.id] = {"users": []}
                last_room = last_rooms[change.document.id]

                isPrivate = room.get("isPrivate", False)
                for userid in room["users"]:
                    db.collection(USER_COLLECTION).document(userid).update(
                        {"inPrivate": isPrivate})
                    if userid not in last_room["users"]:
                        db.collection(EVENT_COLLECTION).document().set({
                            "type":
                            ROOM_JOIN_EVENT_TYPE,
                            "user":
                            userid,
                            "room":
                            change.document.id,
                            "isPrivate":
                            isPrivate,
                            "time":
                            firestore.SERVER_TIMESTAMP
                        })
                        notifData = {
                            "room": change.document.id,
                            "inCall": json.dumps(room["users"])
                        }
                        payload = Payload(alert="", custom=notifData)
                        if (userid in last_users) and \
                           ("controllingUUID" in last_users[userid]) and \
                           (last_users[userid]["controllingUUID"].startswith("mobile:")) and \
                           (not last_users[userid]["active"]):
                            # TODO slight race here where user is inaccessible after
                            # disconnecting from websocket but before we realize it
                            print(last_users[userid])
                            if "APNSPushToken" in last_users[userid]:
                                # TODO check if on mobile
                                isDev = ("APNSDev" in last_users[userid]) and \
                                        (last_users[userid]["APNSDev"])
                                apns_client = APNsClient('BLANK',
                                                         use_sandbox=isDev)
                                apns_client.send_notification(
                                    last_users[userid]["APNSPushToken"],
                                    payload, "BLANK")
                            if "FCMToken" in last_users[userid]:
                                message = messaging.Message(
                                    data=notifData,
                                    token=last_users[userid]['FCMToken'])
                                response = messaging.send(message)
                                print(
                                    'Sent call notification to {}, response {}'
                                    .format(userid, response))
                for userid in last_room["users"]:
                    if userid not in room["users"]:
                        db.collection(USER_COLLECTION).document(userid).update(
                            {"inPrivate": False})
                        db.collection(EVENT_COLLECTION).document().set({
                            "type":
                            ROOM_EXIT_EVENT_TYPE,
                            "user":
                            userid,
                            "room":
                            change.document.id,
                            "isPrivate":
                            isPrivate,
                            "time":
                            firestore.SERVER_TIMESTAMP
                        })
                if len(room["users"]) == 1:
                    last_user = list(room["users"].keys())[0]
                    db.collection(USER_COLLECTION).document(last_user).update(
                        {"roomId": ""})
                    change.document.reference.delete()

                last_rooms[change.document.id] = room

        except Exception as e:
            print(traceback.print_exc())
Esempio n. 33
0
    def _run_train(self, pid, category, network_model, task_id,
                   output_model_dir, num_epochs, finetune_last_layer,
                   push_message, final_train, queue):
        result = False
        try:
            finish, output_graph, quantized_graph, output_labels, global_step_count = controller.run_training(
                pid, category, task_id, self.upload_folder,
                self.unknown_folder, self.pretrained_folder,
                self.tensorflow_folder, output_model_dir, network_model,
                num_epochs, finetune_last_layer)

            if finish:
                # update model status
                controller.update_model_path(pid, category, output_graph,
                                             quantized_graph, output_labels,
                                             network_model)
                if final_train:
                    train_status = controller.TrainingStatus.final_trained
                else:
                    train_status = controller.TrainingStatus.basic_trained
                if finetune_last_layer:
                    train_mode = controller.TrainingMode.finetune
                else:
                    train_mode = controller.TrainingMode.full_train
                controller.update_model_status(
                    pid,
                    category,
                    train_status,
                    train_mode=train_mode,
                    global_step_count=global_step_count)

                # send push message to client
                if push_message:
                    bundle_ids, device_tokens = controller.get_train_wait_devices(
                        task_id)
                    for idx in range(len(bundle_ids)):
                        bundle_id = bundle_ids[idx]
                        device_token = device_tokens[idx]
                        if bundle_id in self.apns_settings:
                            apns_key_file = self.apns_settings[bundle_id][
                                "APNS_KEY_FILE"]
                            apns_use_sandbox = self.apns_settings[bundle_id][
                                "APNS_USE_SANDBOX"]
                            if os.path.exists(apns_key_file):
                                print("device waited for training : " +
                                      device_token)
                                if final_train:
                                    push_message = "Training finished completely."
                                else:
                                    push_message = "Initial training completed."
                                payload = Payload(alert=push_message,
                                                  sound="default",
                                                  badge=1)
                                client = APNsClient(
                                    apns_key_file,
                                    use_sandbox=apns_use_sandbox,
                                    use_alternative_port=False)
                                client.send_notification(device_token,
                                                         payload,
                                                         topic=bundle_id)
                                print("sent push message for device " +
                                      device_token)
                            else:
                                print("APNS key does not exists : " +
                                      apns_key_file)
                        else:
                            print("Bundle ID does not exists in settings : " +
                                  bundle_id)

                result = True
            else:
                controller.delete_train_task(pid, category, task_id)
                controller.delete_train_wait_devices(task_id)
        except Exception:
            controller.update_model_status(pid, category,
                                           controller.TrainingStatus.error)
            controller.delete_train_task(pid, category, task_id)
            controller.delete_train_wait_devices(task_id)
            traceback.print_exc()
            queue.put(result)
            return
        queue.put(result)
        return