Example #1
0
 def send2(self,
           msg_content,
           title,
           content_type,
           extras,
           tag=None,
           alias=None):
     """
     增加alias发送方法
     by: 尚宗凯 at:2015-04-09
     修改alias用法
     by: 尚宗凯 at:2015-04-09
     ios通知无声
     by:尚宗凯 at:2015-04-10
     解决ios无法收到推送的问题
     by:尚宗凯 at:2015-04-15
     修改ios alert内容
     by:尚宗凯 at:2015-04-16
     修改ios 推送增加字段
     by:尚宗凯 at:2015-04-22
     修改ios 推送alias
     by:尚宗凯 at:2015-04-23
     增加badge+1
     by:尚宗凯 at:2015-04-29
     如果alias为空则不发送
     by:尚宗凯 at:2015-04-04
     极光推送改为+1
     by:尚宗凯 at:2015-05-18
     """
     if not alias:
         return False
     self.push_android.platform = "android"
     self.push_ios.platform = "ios"
     if ENVIRONMENT == 'aliyun':
         self.push_ios.options = {"apns_production": True}  #生产环境
     else:
         self.push_ios.options = {"apns_production": False}  #开发环境
     if tag:
         self.push_android.audience = jpush.audience(
             # jpush.tag("p_44","p_45")
             jpush.tag(tag))
         self.push_ios.audience = jpush.audience(jpush.tag(tag))
     elif alias:
         self.push_android.audience = jpush.alias(alias)
         self.push_ios.audience = jpush.alias(alias)
     # else:
     #     self.push_android.audience = jpush.all_
     #     self.push_ios.audience = jpush.all_
     self.push_android.message = jpush.message(msg_content=msg_content,
                                               title=title,
                                               content_type=content_type,
                                               extras=json.dumps(extras))
     self.push_ios.sound_disable = True
     ios_msg = jpush.ios(alert=u'%s,%s' % (title, msg_content),
                         extras=extras,
                         badge="+1")
     self.push_ios.notification = jpush.notification(alert=u'%s,%s' %
                                                     (title, msg_content),
                                                     ios=ios_msg)
     self.start()
Example #2
0
 def send(self, msg_content, title, content_type, extras, tag=None):
     # self.push_android = _jpush.create_push()
     # self.push_ios = _jpush.create_push()
     # self.push.platform = jpush.all_
     self.push_android.platform = "android"
     self.push_ios.platform = "ios"
     if tag:
         self.push_android.audience = jpush.audience(
             # jpush.tag("p_44","p_45")
             jpush.tag(tag)
         )
         self.push_ios.audience = jpush.audience(
             jpush.tag(tag)
         )
     else:
         self.push_android.audience = jpush.all_
         self.push_ios.audience = jpush.all_
     self.push_android.message = jpush.message(msg_content=msg_content, title=title, content_type=content_type, extras=json.dumps(extras))
     self.push_ios.notification = jpush.notification(alert=msg_content)
     try:
         if PUSH_ON:
             self.push_android.send()
             self.push_ios.send()
     except Exception as e:
         print e
Example #3
0
 def send(self, msg_content, title, content_type, extras, tag=None):
     # self.push_android = _jpush.create_push()
     # self.push_ios = _jpush.create_push()
     # self.push.platform = jpush.all_
     self.push_android.platform = "android"
     self.push_ios.platform = "ios"
     if tag:
         self.push_android.audience = jpush.audience(
             # jpush.tag("p_44","p_45")
             jpush.tag(tag))
         self.push_ios.audience = jpush.audience(jpush.tag(tag))
     else:
         self.push_android.audience = jpush.all_
         self.push_ios.audience = jpush.all_
     self.push_android.message = jpush.message(msg_content=msg_content,
                                               title=title,
                                               content_type=content_type,
                                               extras=json.dumps(extras))
     self.push_ios.notification = jpush.notification(alert=msg_content)
     try:
         if PUSH_ON:
             self.push_android.send()
             self.push_ios.send()
     except Exception as e:
         print e
Example #4
0
 def send2(self, msg_content, title, content_type, extras, tag=None, alias=None):
     """
     增加alias发送方法
     by: 尚宗凯 at:2015-04-09
     修改alias用法
     by: 尚宗凯 at:2015-04-09
     ios通知无声
     by:尚宗凯 at:2015-04-10
     解决ios无法收到推送的问题
     by:尚宗凯 at:2015-04-15
     修改ios alert内容
     by:尚宗凯 at:2015-04-16
     修改ios 推送增加字段
     by:尚宗凯 at:2015-04-22
     修改ios 推送alias
     by:尚宗凯 at:2015-04-23
     增加badge+1
     by:尚宗凯 at:2015-04-29
     如果alias为空则不发送
     by:尚宗凯 at:2015-04-04
     极光推送改为+1
     by:尚宗凯 at:2015-05-18
     """
     if not alias:
         return False
     self.push_android.platform = "android"
     self.push_ios.platform = "ios"
     if ENVIRONMENT == 'aliyun':
         self.push_ios.options = {"apns_production":True}     #生产环境
     else:
         self.push_ios.options = {"apns_production":False}    #开发环境
     if tag:
         self.push_android.audience = jpush.audience(
             # jpush.tag("p_44","p_45")
             jpush.tag(tag)
         )
         self.push_ios.audience = jpush.audience(
             jpush.tag(tag)
         )
     elif alias:
         self.push_android.audience = jpush.alias(
             alias
         )
         self.push_ios.audience = jpush.alias(
             alias
         )
     # else:
     #     self.push_android.audience = jpush.all_
     #     self.push_ios.audience = jpush.all_
     self.push_android.message = jpush.message(msg_content=msg_content, title=title, content_type=content_type, extras=json.dumps(extras))
     self.push_ios.sound_disable=True
     ios_msg = jpush.ios(alert=u'%s,%s'%(title, msg_content), extras=extras, badge="+1")
     self.push_ios.notification = jpush.notification(alert=u'%s,%s'%(title, msg_content), ios=ios_msg)
     self.start()
Example #5
0
def jpush_foundpage(channel_no, version, id, title, city):
    if JPUSH.SWITCH and channel_no == JPUSH.DEFAULT_CHANNELNO and version >= JPUSH.DEFAULT_VERSION:
        import jpush
        oCmsChannelJpush = CmsChannelJpush.objects.get(channel_no=channel_no)
        cities = city.split(",")
        new_cities = []
        for city in cities:
            if len(city) > 2 and city[-1] in ["市", "县"]:
                city = city[:-1]
            new_cities.append(city)
        cities = new_cities
        version = "Putao_" + version.replace(".", "_")
        app_key = oCmsChannelJpush.app_key
        master_secret = oCmsChannelJpush.master_secret
        _jpush = jpush.JPush(app_key, master_secret)
        push = _jpush.create_push()
        push.platform = jpush.all_
        for i in range(0, len(cities), 20):
            city = cities[i:i + 20]
            msg_time = int(time.time())
            city_list = []
            # push.audience = jpush.all_
            if "*" in city:
                push.audience = jpush.audience(jpush.tag(channel_no, version))
            else:
                push.audience = jpush.audience(
                    jpush.tag(*city), jpush.tag_and(channel_no, version))
                city_list = city
            # push.notification = jpush.notification(alert="new found page")

            messages = {
                "version":
                1,
                "data": [{
                    "msg_digest": title,
                    "msg_type": 10,
                    "msg_subject": title,
                    "msg_id": id,
                    "is_notify": 0,
                    "msg_expand_param": {
                        "tab_index": 1,
                        "city_list": city_list
                    },
                    "msg_time": msg_time,
                    "msg_product_type": "0"
                }]
            }
            push.message = {"msg_content": json.dumps(messages)}
            push.send()
Example #6
0
def AsyncSetProprtyRepair(apiKey, secretKey, currentCommunityId,
                          custom_content, message, customTitle, tagSuffix):
    #     import sys
    #     default_encoding = 'utf-8'
    #     if sys.getdefaultencoding() != default_encoding:
    #         reload(sys)
    #         sys.setdefaultencoding(default_encoding)
    tagName = tagSuffix + str(currentCommunityId)
    _jpush = jpush.JPush(apiKey, secretKey)
    pushExtra = {'pTitle': customTitle}
    pushExtra.update(custom_content)
    #    pushExtra = custom_content
    push = _jpush.create_push()
    push.audience = jpush.all_
    push.audience = jpush.audience(jpush.tag(tagName), )
    push.notification = jpush.notification(
        ios=jpush.ios(alert=message.encode('utf-8'),
                      badge="+1",
                      extras=pushExtra),
        android=jpush.android(message, customTitle, None, pushExtra))
    push.options = {
        "time_to_live": 86400,
        "sendno": 9527,
        "apns_production": PUSH_STATUS
    }
    push.platform = jpush.all_
    push.send()
Example #7
0
 def push_extra(self,
                extra,
                msg='test',
                platform='all',
                audience=jpush.all_):
     p = {
         'all': jpush.all_,
         'android': jpush.platform('android'),
         'ios': jpush.platform('ios')
     }
     if audience != jpush.all_:
         audience = jpush.audience(jpush.alias(str(audience)))
     try:
         msg = msg.encode('utf-8')
     except:
         pass
     a_msg = jpush.android(alert=msg, extras=extra)
     i_msg = jpush.ios(alert=msg, extras=extra)
     self.push = self._jpush.create_push()
     self.push.audience = audience
     self.push.platform = p.get(platform)
     self.push.notification = jpush.notification(alert=msg,
                                                 android=a_msg,
                                                 ios=i_msg)
     self.push.options = {
         "time_to_live": 86400,
         "sendno": 12345,
         "apns_production": False
     }
     for i in range(5):
         try:
             self.push.send()
             return True
         except Exception, e:
             print e.__repr__()
Example #8
0
    def iso_android(self, tagname, msg):
        """
        just send message to iso and android
        :param tagname:
        :param msg:
        :return:
        """
        try:
            ios = jpush.ios(alert=str(msg), sound='default')
            android = jpush.android(alert=str(msg))

            self.push.audience = jpush.audience(jpush.tag(tagname))
            self.push.notification = jpush.notification(alert=str(msg),
                                                        android=android,
                                                        ios=ios)
            self.push.options = {
                "time_to_live": 86400,
                "apns_production": IS_IOS_DEV
            }
            self.push.platform = jpush.all_
            try:
                response = self.push.send()
                print 'IOS_ANDROID RESPONSE>>>', response
            except Exception, e:
                print 'IOS_ANDROID ERROR>>>', e
        except:
            pass
Example #9
0
def push_message(tags, message, platform=jpush.all_, extras=None):
    push.audience = jpush.all_ if tags == jpush.all_ else jpush.audience(
        {"tag": tags})
    push.notification = jpush.notification(
        alert=message,
        ios=jpush.ios(message, extras=extras),
        android=jpush.android(message, extras=extras),
        winphone=jpush.winphone(message, extras=extras))
    push.message = jpush.message(message, extras=extras)
    push.platform = platform
    try:
        response = push.send()
    except jpush.common.Unauthorized as e:
        logging.error("JPush Unauthorized: %s" % str(e))
    except jpush.common.APIConnectionException as e:
        logging.error("JPushconn error: %s" % str(e))
    except jpush.common.JPushFailure as e:
        logging.error("JPush Failure: %s" % str(e))
    except Exception as e:
        raise e
    else:
        logging.info(response.payload)
        if response.status_code == 200 and response.payload['sendno'] == '0':
            return True
    return False
Example #10
0
def send_users_base_tags(tags, body, images='', extras={'link': ''}):
    _jpush = jpush.JPush(setting.jpush_key, setting.jpush_secret)
    push = _jpush.create_push()
    push.audience = jpush.audience()
    push.audience['tag'] = tags
    push.platform = jpush.all_

    if extras:
        extras['images'] = images
        ios_msg = jpush.ios(alert=body,
                            badge="+1",
                            sound="a.caf",
                            content_available=True,
                            mutable_content=True,
                            extras=extras)
        android_msg = jpush.android(alert=body,
                                    style=3,
                                    big_pic_path=images,
                                    extras=extras)
    else:
        ios_msg = jpush.ios(alert=body,
                            badge="+1",
                            sound="a.caf",
                            content_available=True,
                            mutable_content=True)
        android_msg = jpush.android(alert=body)
    push.notification = jpush.notification(alert=body,
                                           android=android_msg,
                                           ios=ios_msg)
    push.options = {"apns_production": True}

    result = push.send()
    print result.payload
Example #11
0
    def send(self, *args, **kwargs):

        try:
            content = NoticeTemplate.objects.get(category=self.category)
        except NoticeTemplate.DoesNotExist:
            print u"没有发现模板"
            return False

        print content.content

        template = Template(content.content)
        messages = template.render(dict(*args, **kwargs))

        registration_id = kwargs.get('registration_id')

        opts = jpush.JPush(settings.JPUSH_APPKEY, settings.JPUSH_SECRET)
        push = opts.create_push()

        push.notification = jpush.notification(alert=messages)
        push.options = {
            "time_to_live": 86400,
            "apns_production": True,
            'extras': kwargs.get('extras')
        }
        push.audience = jpush.audience(jpush.registration_id(
            registration_id)) if registration_id else jpush.all_
        push.platform = jpush.all_
        push.send()
Example #12
0
def pushsinglemsg(apptype, body, receiver):
    key = 'bb9fc37f914d94589c6d7c4d'
    secret = '0b058bd331eae435fa38f20e'
    if apptype == 2:
        key = '382c5d880cae31ec81df46ff'
        secret = 'ac37c4c44a0b83539d469464'
    elif apptype == 3:
        key = '28e20ce5dcfd49511309806a'
        secret = 'b05bdc47c2cb686850a6c766'
    elif apptype == 4:
        key = '3c7971b2e03ef0f0df5c70b2'
        secret = 'ff57774954b9ed1f0771cef4'
    _jpush = jpush.JPush(key, secret)
    push = _jpush.create_push()
    push.audience = jpush.audience(jpush.alias(receiver))

    ios_msg = jpush.ios(alert=body,
                        badge="+1",
                        sound="a.caf",
                        extras={'k1': 'v1'})
    android_msg = jpush.android(alert=body)
    push.notification = jpush.notification(alert=body,
                                           android=android_msg,
                                           ios=ios_msg)

    push.platform = jpush.all_
    push.options = {"apns_production": False}
    re = push.send()
    print re
Example #13
0
 def push_with_alias(self, msg, alias=None, extra=None):
     if self.call_remote:
         self.call_in_remote_server('push_with_alias',
                                    msg=msg,
                                    alias=alias,
                                    extra=extra)
         return
     push = self._jpush.create_push()
     push.platform = jpush.all_
     if alias:
         push.audience = jpush.audience({'alias': alias})
     else:
         push.audience = jpush.all_
     android = jpush.android(alert=msg, extras=extra)
     ios = jpush.ios(alert="%s\n%s: %s" %
                     (extra['title'], extra['sender'], extra['content']))
     push.notification = jpush.notification(alert=msg,
                                            android=android,
                                            ios=ios)
     print(push.payload)
     retry_time = 3
     while retry_time:
         try:
             push.send()
             return
         except:
             retry_time -= 1
Example #14
0
 def alias(self, msg, alias):
     push = self._jpush.create_push()
     push.audience = jpush.audience({'alias': alias})
     push.platform = jpush.all_
     push.notification = jpush.notification(alert=msg)
     print(push.payload)
     push.send()
Example #15
0
def AsyncDelCommentPush(topicId, senderId, communityId, commentId,
                        commentCount):
    config = readIni()
    tagSuffix = config.get('topic', "tagSuffix")
    pushContent = str(topicId).encode('utf-8') + ":" \
                 +str(senderId).encode('utf-8') + ":" \
                 +str(communityId).encode('utf-8') + ":" \
                 +str(commentId).encode('utf-8') + ":" \
                 +str(commentCount).encode('utf-8')

    tagSuffix = config.get('topic', "tagSuffix")
    tagNormalName = tagSuffix + str(communityId)
    tagSuffix = config.get('report', "tagSuffix")
    tagAdminName = tagSuffix + str(communityId)
    tagSuffix = config.get('property', "tagSuffix")
    tagPropertyName = tagSuffix + str(communityId)

    apiKey = config.get("SDK", "apiKey")
    secretKey = config.get("SDK", "secretKey")
    _jpush = jpush.JPush(apiKey, secretKey)
    push = _jpush.create_push()
    push.audience = jpush.all_
    push.audience = jpush.audience(
        jpush.tag(tagNormalName, tagAdminName, tagPropertyName), )
    push.message = jpush.message(pushContent, u"push_del_comm", None, None)
    push.options = {
        "time_to_live": 0,
        "sendno": 9527,
        "apns_production": PUSH_STATUS
    }
    push.platform = jpush.all_
    push.send()
Example #16
0
def jpushMessageWithAlias(alias, msg, action):
    push = jpushCreateClient()
    push.audience = jpush.audience(jpush.alias(alias))
    push.notification = jpush.notification(
        android=jpush.android(alert=action, extras=msg))
    resp = jushPushMessageToJiGuang(push)
    return resp
Example #17
0
    def pushForAlias(self, id, title, subtitle, body, link):
        if len(title) == 0 and len(subtitle) == 0 and len(body) == 0:
            return

        push = self._jpush.create_push()
        alias = [id]
        alias1 = {"alias": alias}
        push.audience = jpush.audience(alias1)

        ios = jpush.ios(alert={
            "title": title,
            "subtitle": subtitle,
            "body": body
        },
                        sound="default",
                        extras={'link': link})
        push.notification = jpush.notification(alert=subtitle, ios=ios)
        push.options = {
            "time_to_live": 86400,
            "sendno": 12345,
            "apns_production": config.is_release
        }
        push.platform = "ios"
        print(push.payload)
        # push.send()
        try:
            response = push.send()
        except common.Unauthorized:
            raise common.Unauthorized("Unauthorized")
        except common.APIConnectionException:
            raise common.APIConnectionException("conn")
        except common.JPushFailure:
            print("JPushFailure")
        except:
            print("Exception")
Example #18
0
    def pushMessage(self, audience, message_dict):
        try:
            push = self._jpush.create_push()
            if not audience:
                raise JpushException('audience is empty', self.JPUSH_AUDIENCE_EMPTY)
            if audience == 'all':
                push.audience = jpush.all_
            else:
                push.audience = jpush.audience(
                    jpush.alias(*audience)
                )
            #android_msg = jpush.android(alert="Hello, android msg")
            if not message_dict:
                raise JpushException('message_dict is empty', self.MESSAGE_DICT_EMPTY)

            alert_message = message_dict.get('content', '')
            if not alert_message:
                raise JpushException('message_content is empty', self.MESSAGE_CONTENT_EMPTY)
            msg_content = json.dumps(message_dict)

            push.message = jpush.message(msg_content=msg_content)
            push.platform = jpush.all_
            return push.send()
        except jpush.common.JPushFailure, e:
            print e
            return False
Example #19
0
def jpush_alias(message, *args, **kwargs):
    '''
    别名推送
    * @param  推送消息
    * @param  推送别名

    '''
    _jpush = JPush(settings.JPUSH_APPKEY, settings.JPUSH_SECRET)
    _jpush.set_logging("DEBUG") and settings.DEBUG

    push = _jpush.create_push()
    push.options = {
        "time_to_live": 86400,
        "sendno": 12345,
        "apns_production": not settings.DEBUG
    }
    push.audience = jpush.audience({"alias": args})

    push.notification = jpush.notification(alert=message)
    push.platform = jpush.all_

    try:
        return push.send()
    except common.Unauthorized:
        raise common.Unauthorized("Unauthorized")
    except common.APIConnectionException:
        raise common.APIConnectionException("conn")
    except common.JPushFailure as e:
        raise e
    except Exception as e:
        raise e
Example #20
0
def send_message(title, **kwargs):
    push = _jpush.create_push()
    push.audience = jpush.audience(kwargs)
    push.options = {"apns_production": False}
    push.notification = jpush.notification(
        alert={"title": title},
        android={"extras": {
            "android-key1": "android-value1"
        }},
        ios={
            "sound": "sound.caf",
            "badge": "+1",
            "extras": {
                "ios-key1": "ios-value1"
            }
        })
    push.platform = jpush.all_
    try:
        response = push.send()
    except jpush.common.Unauthorized:
        raise jpush.common.Unauthorized("Unauthorized")
    except jpush.common.APIConnectionException:
        raise jpush.common.APIConnectionException("conn")
    except jpush.common.JPushFailure:
        print("JPushFailure")
    except:
        print("Exception")
Example #21
0
 def push_extra(self,
                extra,
                msg='test',
                platform='all',
                audience=jpush.all_):
     p = {
         'all': jpush.all_,
         'android': jpush.platform('android'),
         'ios': jpush.platform('ios')
     }
     if audience != jpush.all_:
         audience = jpush.audience(jpush.alias(str(audience)))
     try:
         msg = msg.encode('utf-8')
     except:
         pass
     a_msg = jpush.android(alert=msg, extras=extra)
     i_msg = jpush.ios(alert=msg, extras=extra)
     self.push = self._jpush.create_push()
     self.push.audience = audience
     self.push.platform = p.get(platform)
     self.push.notification = jpush.notification(alert=msg,
                                                 android=a_msg,
                                                 ios=i_msg)
     return self.push.send()
Example #22
0
    def test_audience(self):
        _jpush = jpush.JPush(app_key, master_secret)

        push = _jpush.create_push()
        push.audience = jpush.audience(
            jpush.tag("tag1", "tag2"),
            jpush.alias("alias1", "alias2")
        )
        push.notification = jpush.notification(alert="Hello world with audience!")
        push.platform = jpush.all_
        try:
            response = push.send()

            self.assertEqual(response.status_code, 200)
        except common.Unauthorized as e:
            self.assertFalse(isinstance(e, common.Unauthorized))
            raise common.Unauthorized("Unauthorized")
        except common.APIConnectionException as e:
            self.assertFalse(isinstance(e, common.APIConnectionException))
            raise common.APIConnectionException("conn")
        except common.JPushFailure as e:
            self.assertFalse(isinstance(e, common.JPushFailure))
            print ("JPushFailure")
        except:
            self.assertFalse(1)
            print ("Exception")
Example #23
0
 def test_basic_push(self):
     self.push.platform = platform("ios", "android")
     self.push.audience = audience()
     with self.assertRaises(ValidateError):
         self.push.send_validate()
     self.push.notification = notification(alert="alert")
     self.push.send_validate()
Example #24
0
 def push_by_id(self, notification, registration_id):
     self.push.platform = jpush.all_
     self.push.audience = jpush.audience(jpush.registration_id(registration_id))
     self.push.notification = jpush.notification(alert=notification)
     self.__push()
     tip_message = 'JPush SUCCESS.To: %s'% (registration_id)
     _LOGGER.info(tip_message)
Example #25
0
def jpushios(obj):
    _jpush = jpush.JPush(app_key, master_secret)
    push = _jpush.create_push()
    push.audience = jpush.all_

    name = Name(obj)
    project = Project(obj)
    content = obj.content
    version = Version(obj)
    urgency = Urgency(obj)
    module = Module(obj)
    distribter = Distribter(obj)

    msgdict = [
        name, u'在', project, version, u'版本', module, u'中', u'发现一个', urgency,
        u'问题', u':', content
    ]
    msg = ''.join(msgdict)

    push.audience = jpush.audience(jpush.alias(distribter))
    ios_msg = jpush.ios(alert=msg,
                        badge="+1",
                        sound="a.caf",
                        extras={'k': 'v'})
    push.options = {
        "time_to_live": 86400,
        "sendno": 12345,
        "apns_production": False
    }
    push.notification = jpush.notification(alert="", ios=ios_msg)
    push.platform = jpush.platform("ios")
    push.send()
Example #26
0
def send_users_base_regid(reg_id, body, images='', extras=None):
    _jpush = jpush.JPush(setting.jpush_key, setting.jpush_secret)
    push = _jpush.create_push()
    alias1 = {"registration_id": [reg_id]}
    push.audience = jpush.audience(alias1)
    if extras:
        extras['images'] = images
        ios_msg = jpush.ios(alert=body,
                            badge="+1",
                            sound="a.caf",
                            content_available=True,
                            mutable_content=True,
                            extras=extras)
        android_msg = jpush.android(alert=body,
                                    style=3,
                                    big_pic_path=images,
                                    extras=extras)
    else:
        ios_msg = jpush.ios(alert=body,
                            badge="+1",
                            sound="a.caf",
                            content_available=True,
                            mutable_content=True)
        android_msg = jpush.android(alert=body)
    push.notification = jpush.notification(alert=body,
                                           android=android_msg,
                                           ios=ios_msg)

    push.platform = jpush.all_
    push.options = {"apns_production": True}

    result = push.send()
    # result = push.send_validate()
    print result.payload
    def notification_by_tag_or_alias(self, msg, tags, alias=None):
        """根据别名或tag推送消息"""
        push = self._jpush.create_push()

        if alias:
            push.audience = jpush.audience(
                jpush.tag(*tags),
                jpush.alias(*alias),
            )
        else:
            push.audience = jpush.audience(jpush.tag(*tags))

        push.notification = jpush.notification(alert=msg)
        push.platform = jpush.all_
        response = push.send()
        return response
Example #28
0
def AsyncAddressAuditSubmit(apiKey, secretKey, alias, user_id, customContent,
                            pushContent, pushTitle):
    from users.models import User
    uObectj = User.objects.get(user_id=long(user_id))
    userCache = uObectj.user_handle_cache
    addrCache = uObectj.addr_handle_cache
    uObectj.addr_handle_cache = (int(addrCache) + 1) % 1000
    uObectj.save()
    _jpush = jpush.JPush(apiKey, secretKey)
    pushExtra = {'pTitle': pushTitle}
    pushExtra.update(customContent)
    #    pushExtra = customContent
    currentAlias = alias + str(user_id)
    push = _jpush.create_push()
    push.audience = jpush.all_
    push.audience = jpush.audience(jpush.alias(currentAlias), )
    push.notification = jpush.notification(
        ios=jpush.ios(alert=pushContent.encode('utf-8'),
                      badge="+1",
                      extras=pushExtra),
        android=jpush.android(pushContent, pushTitle, None, pushExtra))
    push.options = {
        "time_to_live": 86400,
        "sendno": 9527,
        "apns_production": PUSH_STATUS
    }
    push.platform = jpush.all_
    push.send()
Example #29
0
def send_msg(username, target, title, msg):
	_jpush = jpush.JPush(app_key, master_secret)
	push = _jpush.create_push()
	push.audience = jpush.audience(jpush.alias(target))
	android_msg = jpush.android(alert=msg, title=title, extras={'username': username})
	push.notification = jpush.notification(alert=msg, android=android_msg)
	push.platform = jpush.all_
	push.send()
Example #30
0
 def broadcast_by_tags(self, notification, *tag_list):
     self.push.platform = jpush.all_
     if len(tag_list) > 0:
         self.push.audience = jpush.audience(jpush.tag(tag_list),)
     else:
         self.push.audience = jpush.all_
     self.push.notification = jpush.notification(alert=notification)
     self.__push()
Example #31
0
    def send_message(self, message, alias=None, **kwargs):

        if alias is not None:
            self.push.audience = jpush.audience(jpush.alias(*alias))

        self.push.message = jpush.message(msg_content=message, extras=kwargs)
        self.push.platform = jpush.platform('android', 'ios')
        self.push.send()
Example #32
0
def jpushMessageWithRegId(regid, msg, action):
    push = jpushCreateClient()
    push.audience = jpush.audience(jpush.registration_id(regid))
    push.notification = jpush.notification(
        android=jpush.android(alert=action, extras=msg))
    print msg, push.notification
    resp = jushPushMessageToJiGuang(push)
    return resp
Example #33
0
File: tests.py Project: cash2one/pt
def jpush_foundpage(channel_no, version, id, title, city):
    cities = city.split(",")
    new_cities = []
    for city in cities:
        if len(city) > 2 and city[-1] in ["市", "县"]:
            city = city[:-1]
        new_cities.append(city)
    cities = new_cities
    version = "Putao_" + version.replace(".", "_")
    app_key = "5e111aec05ad8a27b651624f"
    master_secret = "423462d8a3880ce786765d6b"
    _jpush = jpush.JPush(app_key, master_secret)
    push = _jpush.create_push()
    push.platform = jpush.all_
    for i in range(0, len(cities), 20):
        city = cities[i:i + 20]
        msg_time = int(time.time())
        city_list = []
        # push.audience = jpush.all_
        if "*" in city:
            push.audience = jpush.audience(jpush.tag(channel_no, version))
        else:
            push.audience = jpush.audience(jpush.tag(*city),
                                           jpush.tag_and(channel_no, version))
            city_list = city
        # push.notification = jpush.notification(alert="new found page")

        messages = {
            "version":
            1,
            "data": [{
                "msg_digest": title,
                "msg_type": 10,
                "msg_subject": title,
                "msg_id": id,
                "is_notify": 0,
                "msg_expand_param": {
                    "tab_index": 1,
                    "city_list": city_list
                },
                "msg_time": msg_time,
                "msg_product_type": "0"
            }]
        }
        push.message = {"msg_content": json.dumps(messages)}
        push.send()
Example #34
0
 def alias(self, alias: list, tags: list):
     push = self.my_push
     data = {'alias': alias}
     push.audience = jpush.audience(jpush.tag(*tags), data)
     push.notification = jpush.notification(
         alert="Hello world with audience!")
     push.platform = jpush.all_
     push.send()
Example #35
0
    def audience(self, alias: list, tags: list):
        push = self.my_push

        push.audience = jpush.audience(jpush.tag(tags), jpush.alias(alias))

        push.notification = jpush.notification(
            alert="Hello world with audience!")
        push.platform = jpush.all_
        push.send()
Example #36
0
def audience_for_alias(alias, msg):
    push = _jpush.create_push()

    push.audience = jpush.audience(jpush.alias(alias))

    push.notification = jpush.notification(alert=msg)
    push.platform = jpush.all_
    print(push.payload)
    push.send()
Example #37
0
def send_tip(request):
	# save tip
	# notify receiver
	data = {}

	if request.method=='POST':		
		logger.debug(str(request.POST))

		mobile=request.POST.get('mobile')
		friend=request.POST.get('friend_mobile')
		try:
			client = User.objects.get(username=mobile)
			to_friend = User.objects.get(username=friend)
			to_friend_info = UserInfo.objects.get(user=to_friend)
		except ObjectDoesNotExist:
			logger.debug("user or friend do not exist!")
			data['status']=28
			data['error']='user have not register'
			return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json')

		
		content=request.POST.get('message')
		create_time=request.POST.get('create_time')
		audio_url=request.POST.get('audio_url')
		photo_url=request.POST.get('photo_url')

		tip = Tip(user=client)
		tip.receiver = friend
		tip.message = content
		tip.create_time = create_time
		if 'photo_file' in request.FILES:
			photo_name = request.FILES['photo_file']._get_name()
			tip.photo.save(photo_name, request.FILES['photo_file'])
		if 'audio_file' in request.FILES:
			audio_name = request.FILES['audio_file']._get_name()
			tip.audio.save(audio_name, request.FILES['audio_file'])
		tip.save()
		# retrieve tip id for next to get
		cacheID = tip.id
 	
		push_target = to_friend_info.imsi

		_jpush = jpush.JPush(app_key, master_secret)
		push = _jpush.create_push()
		push.audience = jpush.audience(
			jpush.tag(push_target)
		)
		push_data = {}
		push_data['from'] = mobile
		push_data['id'] = cacheID
		push.message = jpush.message(msg_content=302, extras=json.dumps(push_data,ensure_ascii=False))
		push.platform = jpush.all_
		push.send()

		data['status']=0
		return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json')
Example #38
0
def sent_msg_to_people(alias,alert):
    _jpush = jpush.JPush(app_key, master_secret)    
    push = _jpush.create_push()
    push.audience = jpush.audience(
                jpush.alias(alias)
            )
    push.notification = jpush.notification(alert=alert)
    push.platform = jpush.all_
    srecv = push.send()
    return srecv
Example #39
0
 def push_article(self,
                  t,
                  i,
                  msg='test',
                  platform='all',
                  audience=jpush.all_):
     if audience != jpush.all_:
         audience = jpush.audience(jpush.alias(str(audience)))
     extra = {'t': str(t), 'i': str(i)}
     return self.push_extra(extra, msg, platform, audience)
Example #40
0
    def send_notification(self, title, alert, alias=None, **kwargs):
        android = jpush.android(alert=alert, title=title, extras=kwargs)

        if alias is not None:
            self.push.audience = jpush.audience(jpush.alias(*alias))

        # ios = None
        self.push.notification = jpush.notification(alert=alert, android=android)
        self.push.platform = jpush.platform('android', 'ios')
        self.push.send()
Example #41
0
def push2user(user, type, data={}, alert=None, title=None, builder_id=1, badge="+1"):
    audience = jpush.audience(jpush.alias('u%s' % user.phone))
    extras = data

    code = push_helper(
        alert=alert, type=type, title=title, builder_id=builder_id, badge=badge,
        audience=audience, **extras)

    PushLog(user=user.id, type=type, data=json.dumps(data), alert=alert, title=title, code=code).save()

    return True if code == 0 else False
Example #42
0
def push_news(push_id, news):
    
    _jpush = jpush.JPush(app_key, master_secret)
    
    push = _jpush.create_push()
    push.audience = jpush.audience(
            jpush.registration_id(push_id)
        )
    push.notification = jpush.notification(alert=news)
    push.platform = jpush.all_
    push.send()
Example #43
0
def pushToUser(userId,userName,trendId):
    userId_str = str(userId)
    _jpush = jpush.JPush(AK, SK)
    _jpush.set_logging("DEBUG")
    push = _jpush.create_push()
    push.audience = jpush.audience(
                jpush.alias(userId_str)
            )
    andriod_msg = jpush.android(alert=userName+"评论了你的动态",title = "新消息" , extras = {'trendId':str(trendId)})
    push.notification = jpush.notification(alert="新消息",android=andriod_msg)
    push.platform = jpush.all_
    print (push.payload)
    push.send()
Example #44
0
def push(phone, msg):
    import jpush as jpush
    from conf import app_key, master_secret
    _jpush = jpush.JPush(app_key, master_secret)

    push = _jpush.create_push()
    push.audience = jpush.audience(
                jpush.alias(phone)
            )
    push.notification = jpush.notification(alert=msg)
    push.platform = jpush.all_
    push.message = {"msg_content":'test'}
    push.send()
Example #45
0
def push_message_to_alias(content, msg_type, alias, platform='android'):
    msg = {
        'msg_type': msg_type,
        'content': content
    }

    _jpush = jpush.JPush(app.config['JPUSH_APP_KEY'], app.config['JPUSH_MASTER_SECRET'])
    push = _jpush.create_push()
    push.message = jpush.message(json.dumps(msg))
    push.audience = jpush.audience(jpush.alias(alias))
    push.platform = jpush.platform(platform)
    ret = push.send()
    return ret.payload['sendno'].encode('utf-8')
Example #46
0
def send_direct_to_channel(channel):
    developer = get_developer()
    if developer is None:
        return jsonify({}), 404

    channel_to_post = Channel.query.filter_by(developer_id=developer.id,channel=channel).first()
    print(channel_to_post)
    if channel_to_post is None:
        return jsonify({}), 404
    message_url = ""
    if 'url' in request.json:
       message_url = request.json['url']
    _jpush = jpush.JPush(u'1c29cb5814072b5b1f8ef829', u'b46af6af73ee8f9480d4edad')
    push = _jpush.create_push()
    _jpush.set_logging("DEBUG")
    push.audience = jpush.audience(
        jpush.tag(developer.dev_key + '_' + channel)
    )
    android_msg = jpush.android(alert=request.json['title'], extras={'title': request.json['title'],
                                                                     'message': request.json['message']})
    ios_msg = jpush.ios(alert=request.json['title'], extras={'title': request.json['title'],
                                                             'message': request.json['message']})

    push.notification = jpush.notification(alert=request.json['title'], android=android_msg, ios=ios_msg)
    push.message = jpush.message(msg_content=request.json['message'], title=request.json['title'], content_type="tyope",
                                 extras={'dev_key': developer.dev_key, 'channel': channel,
                                         'datetime': int(time.time()),
                                         'icon': "",
                                         'url': message_url,
                                         'integration_name': ""})

    # push.options = {"time_to_live": 864000, "sendno": 12345, "apns_production": False}
    push.options = {"time_to_live": 864000, "sendno": 12345, "apns_production": True}
    push.platform = jpush.all_

    try:
        response = push.send()
        print(response)
    except common.Unauthorized:
        print("Unauthorized")
        return jsonify({'error': 'Unauthorized request'}), 401
    except common.APIConnectionException:
        print('connect error')
        return jsonify({'error': 'connect error, please try again later'}), 504
    except common.JPushFailure:
        print("JPushFailure")
        response = common.JPushFailure.response
        return jsonify({'error': 'JPush failed, please read the code and refer code document'}), 500
    except:
        print("Exception")
    return jsonify({}), 200
Example #47
0
def push_msg(*, alias: str, msg: dict):
    try:
        jpush_ = jpush.JPush(_app_key, _master_secret)
        push = jpush_.create_push()
        push.audience = jpush.audience(jpush.alias(alias))
        msg = json.dumps(msg)
        push.message = jpush.message(msg_content=msg)
        push.platform = jpush.all_
        push.send()
    #terrible
    except JPushFailure:
        raise PushError
    except Unauthorized:
        raise PushError
Example #48
0
    def send_notification(self, _id, title, actors):
	for actor in actors:
            client_ids = self.get_actor_subscribers(actor)
            if client_ids:
                push = self._jpush.create_push()
                push.audience = jpush.audience(
                    jpush.registration_id(*client_ids)
                )
	        log.msg("client ids = " + json.dumps(client_ids))
	        message = jpush.android(alert=u'新片通知 : 您关注的艺人 ' + actor.encode('utf-8') + u' 有新片 %s ,点击查看详情。' %(title.encode('utf-8')), extras={'VideoID':str(_id)})
                push.notification = jpush.notification(alert=u'新片通知 : 您关注的艺人发布了新片,点击查看详情。', android=message)
	        log.msg("Sending push notification for %s and %s" %(title, actor))
                push.platform = jpush.all_
                push.send()
Example #49
0
    def save_model(self, request, obj, form, change):
        obj.save()
        '''x = xinge.XingeApp(2100130704, '82bbeb41db7f303a0f0f6521ddf23558')
        iosx=xinge.XingeApp(2200130705, 'd3156bf69ce4357382bfc8a93920582f')
        msg=xinge.Message()
        msg.type = xinge.Message.TYPE_NOTIFICATION
        msg.title = obj.title.encode('utf-8')
        msg.content = obj.content.encode('utf-8')
        msg.expireTime = 86400
        #msg.sendTime = '2012-12-12 18:48:00'
        # 自定义键值对,key和value都必须是字符串,非必须
        msg.custom = {'type':'1', 'id':str(obj.id)}
        style = xinge.Style(2, 1, 1, 1, 0)
        msg.style = style
        iosmsg=xinge.MessageIOS()
        iosmsg.alert = obj.title.encode('utf-8')
        iosmsg.custom = {'type':'1', 'id':str(obj.id)}
        iosmsg.sound='default'
        if obj.style==1:
            x.PushAllDevices(0, msg)
            iosx.PushAllDevices(0, iosmsg, 1)
        else:
            idlist=obj.members.values_list('id',flat=True)
            idlist=[str(i) for i in idlist]
            if len(idlist)>1:
                ret=x.PushTags(0, idlist, 'AND', msg)
                ret=iosx.PushTags(0, idlist, 'AND', iosmsg, 1)
            if len(idlist)==1:
                ret=x.PushTags(0, idlist, 'OR', msg)
                ret=iosx.PushTags(0, idlist, 'OR', iosmsg, 1)'''
        _jpush = jpush.JPush('65461ea95bac07cb5349907a', '5238c85d2eacd9cc6b80a225')
        push = _jpush.create_push()
        if obj.style==1:
            push.audience=jpush.all_
        else:
            idlist=request.POST.getlist('members','')
            idlistt=[str(i) for i in idlist]
            
            push.audience = jpush.audience(jpush.alias(*idlistt),)
        ios_msg = jpush.ios(alert=obj.title.encode('utf-8'), badge="+1", sound="a.caf",extras={'type':'1', 'id':str(obj.id)})
        android_msg = jpush.android(alert=obj.title,extras={'type':'1', 'id':str(obj.id)})

        push.notification = jpush.notification(android=android_msg, ios=ios_msg)
        push.platform = jpush.all_
        push.options = {"time_to_live":86400, "sendno":12345,"apns_production":True}
        
        push.send()
    def _push(self, _jpush, targets, data):
        '''
        '''
        targets = [str(target) for target in targets]
        # TODO: 测试环境写成愿愿的id
#         targets = ["341255"]
        push = _jpush.create_push()
        push.audience = jpush.audience(
                            jpush.tag(*targets)
                        )
        push.notification = jpush.notification(alert=data['content'],
                                               ios=jpush.ios(alert=data['content'], badge=1, sound='default', extras=data['extras']),
                                               android=jpush.android(alert=data['content'], extras=data['extras'])
                                               )
        push.options = jpush.options({'sendno': 123456, 'apns_production': True, 'big_push_duration': 0})
        push.platform = jpush.all_
        push.send() 
Example #51
0
 def single(self, reg_id):
     self.push.audience = jpush.audience( 
         jpush.registration_id('id1', reg_id) 
     ) 
     self.push.notification = jpush.notification(
         alert=self.msg, 
         android=self.android_msg, 
         ios=self.ios_msg
     ) 
     self.push.options = {
         "time_to_live":86400, 
         "sendno":12345,
         "apns_production":False
     }
     self.push.platform = jpush.all_ 
     try:
         self.push.send() 
     except Exception as e:
         print(e)
Example #52
0
def pushProduct(id, operId):
	try:
		db.execute("SELECT * FROM " + getTableName('push', operId)+ " WHERE id=%s LIMIT 1", (id,))
		msg = db.get_rows(size=1, is_dict=True)

		db.execute("SELECT * FROM %s WHERE `status`=1" %getTableName('pusher', operId))
		pusher = db.get_rows(is_dict=True)

		_jpush = jpush.JPush(app_key, master_secret)
		push = _jpush.create_push()
		total = 0

		for vo in pusher:
			if vo['categories'] and msg['category'] not in vo['categories']:
				continue

			if vo['keyword'] and msg['keyword'] not in vo['keyword']:
				continue

			push.audience = jpush.audience(
	        	jpush.registration_id(vo['registration'])
		        )

			push.notification = jpush.notification(
			   android=jpush.android(
			      alert=msg['title'],
			      builder_id=getBuidlerId(vo['sound'], vo['vibrate']),
			      extras={"id": msg['product'], 'target': 'product'}
			   )
			)
			push.platform = jpush.platform('android')
			push.send()

			total = total + 1
			db.update(getTableName('pusher', operId), {'date': time2stamp(datetime.date.today().strftime('%Y-%m-%d'))}, 
				{'id': vo['id']})
	except Exception:
		db.update(getTableName('push', operId), {'status': 2}, {'id': id})
		return False
	else:
		db.update(getTableName('push', operId), {'status': 1, 'total': total}, {'id': id})
		return True
Example #53
0
def jpush_send_message(push_data, push_target, id):
	_jpush = jpush.JPush(app_key, master_secret)
	push = _jpush.create_push()
	push.audience = jpush.audience(
		# push_target may user account or phone number
		jpush.tag(push_target)
	)
	push.message = jpush.message(msg_content=id, extras=push_data)
	push.platform = jpush.all_
	push.options = {"time_to_live":86400}
	try:
		push.send()
	except common.Unauthorized:
	    raise common.Unauthorized("Unauthorized")
	except common.APIConnectionException:
	    raise common.APIConnectionException("conn error")
	except common.JPushFailure:
	    print ("JPushFailure")
	except:
	    print ("Exception")
Example #54
0
def pushMessage(registration, operId):
	db.execute("SELECT * FROM " + getTableName('pusher', operId)+ " WHERE registration=%s AND `status`=1 LIMIT 1", (registration,))
	if db.get_rows_num() == 0:
		return

	pusher = db.get_rows(size=1, is_dict=True)
	_jpush = jpush.JPush(app_key, master_secret)
	push = _jpush.create_push()	
	push.audience = jpush.audience(
	    jpush.registration_id(registration)
	)

	push.notification = jpush.notification(
	   android=jpush.android(
	      alert=u'你的吐槽信息有了新的回复~',
	      builder_id=getBuidlerId(pusher['sound'], pusher['vibrate']),
	      extras={'target': 'tucao'}
	   )
	)
	push.platform = jpush.platform('android')
	push.send()
Example #55
0
def push_alias(uid, message, **kargs):
    _jpush = jpush.JPush(config.JPUSH_APPKEY, config.JPUSH_SECRET)
    push = _jpush.create_push()
    push.audience = jpush.audience(jpush.alias(uid))
    #push.options
    android = jpush.android(alert=message, extras=kargs)
    push.notification = jpush.notification(android=android)
    push.platform = jpush.all_
    try:
        resp = push.send()
        success = True
    except jpush.JPushFailure:
        resp = 'JPushFailure %s %s' % (uid, message)
        success = False
    try:
        fp = open(config.BASE_DIR + 'log/push.log', 'a')
    except:
        fp = open(config.BASE_DIR + 'log/push.log', 'w')

    fp.write("%s\n" % resp)
    fp.close()
    return success
Example #56
0
def PushMessageUser(alert,title,n_type,n_id,user):
	push = _jpush.create_push()
	push.audience = jpush.audience(
		jpush.alias(user)
		)
	push.notification = jpush.notification(
			ios=jpush.ios(
			alert=alert,
			badge="+1",
			extras={"n_type":n_type,"n_id":n_id}
			),
		android=jpush.android(
			alert=alert,
			title=title,
			extras={"n_type":n_type,"n_id":n_id}
			)
		)
	push.platform = jpush.platform('ios', 'android')
	push.options = {"apns_production":True,"time_to_live":7200}
	try:
		push.send()
	except:
		traceback.print_exc()
Example #57
0
def jpushios(obj):
    _jpush = jpush.JPush(app_key, master_secret)
    push = _jpush.create_push()
    push.audience = jpush.all_

    name = Name(obj)
    project = Project(obj)
    content = obj.content
    version = Version(obj)
    urgency = Urgency(obj)
    module  = Module(obj)
    distribter = Distribter(obj)

    msgdict = [name, u'在', project,version,u'版本',module,u'中',u'发现一个',urgency,u'问题',u':',content]
    msg = ''.join(msgdict)

    push.audience = jpush.audience(
        jpush.alias(distribter)
    )
    ios_msg = jpush.ios(alert=msg, badge="+1", sound="a.caf", extras={'k':'v'})
    push.options = {"time_to_live": 86400, "sendno": 12345, "apns_production": False}
    push.notification = jpush.notification(alert="", ios=ios_msg)
    push.platform = jpush.platform("ios")
    push.send()
Example #58
0
# -*- coding: utf-8 -*-

"""
    alter by: Daemon
    alter on 2016-08-02
"""
import jpush as jpush
from jpush import common

_jpush = jpush.JPush("5d4173b694e8efa78d84fb41", "32801a523b363dae0ad2e378")

push = _jpush.create_push()
# if you set the logging level to "DEBUG",it will show the debug logging.
_jpush.set_logging("DEBUG")
push.audience = jpush.audience(
            jpush.alias("test")
)
push.notification = jpush.notification(alert="TEST ALERT !!!!!")
push.platform = jpush.all_
try:
    response=push.send()
except common.Unauthorized:
    raise common.Unauthorized("Unauthorized")
except common.APIConnectionException:
    raise common.APIConnectionException("conn error")
except common.JPushFailure:
    print ("JPushFailure")
except:
    print ("Exception")
import jpush as jpush
from conf import app_key, master_secret
_jpush = jpush.JPush(app_key, master_secret)

push = _jpush.create_push()
push.audience = jpush.audience(
            jpush.tag("tag1", "tag2"),
            jpush.alias("alias1", "alias2")
        )
push.notification = jpush.notification(alert="Hello, world with audience!")
push.platform = jpush.all_
push.send()