Esempio n. 1
0
    def set3rdNotifyInfo(self, notify):
        if notify.getTitle() is None or notify.getContent() is None:
            raise Exception("notify title or content cannot be null")

        notifyInfo = gt_req_pb2.NotifyInfo()
        notifyInfo.title = notify.getTitle().decode("utf-8")
        notifyInfo.content = notify.getContent().decode("utf-8")
        if notify.getType() is not None:
            notifyInfo.type = notify.getType()
            setPayloadInfo(notifyInfo, notify)
            if notify.getIntent() is not None:
                if len(notify.getIntent()) > GtConfig.getNotifyIntentLimit():
                    raise Exception('%s%s' % ('intent size overlimit ',
                                              GtConfig.getNotifyIntentLimit()))
                if not re.match(TransmissionTemplate.pattern,
                                notify.getIntent()):
                    raise Exception('%s%s' % (
                        'intent format error,should start with "intent:#Intent;",end with ";end"->',
                        notify.getIntent()))
                notifyInfo.intent = notify.getIntent()
            if notify.getUrl() is not None:
                notifyInfo.url = notify.getUrl()
        else:
            setPayloadInfo(notifyInfo, notify)
        self.getPushInfo().notifyInfo.CopyFrom(notifyInfo)
        self.getPushInfo().validNotify = True
Esempio n. 2
0
 def pushMessageToList(self, contentId, targets):
     params = dict()
     params['action'] = 'pushMessageToListAction'
     params['appkey'] = self.appKey
     params['contentId'] = contentId
     needDetails = GtConfig.isPushListNeedDetails()
     params['needDetails'] = GtConfig.isPushListNeedDetails()
     async = GtConfig.isPushListAsync()
     params["async"] = async
Esempio n. 3
0
 def pushMessageToList(self, contentId, targets):
     params = dict()
     params['action'] = 'pushMessageToListAction'
     params['appkey'] = self.appKey
     params['contentId'] = contentId
     needDetails = GtConfig.isPushListNeedDetails()
     params['needDetails'] = GtConfig.isPushListNeedDetails()
     async = GtConfig.isPushListAsync()
     params["async"] = async
Esempio n. 4
0
    def pushAPNMessageToList(self, appId, contentId, deviceTokenList):
        for deviceToken in deviceTokenList:
            if deviceToken is None or len(deviceToken) != 64:
                raise Exception("deviceToken " + deviceToken + " length must be 64.")

        params = dict()
        params['action'] = "apnPushToListAction"
        params['appkey'] = self.appKey
        params['appId'] = appId
        params['contentId'] = contentId
        params['DTL'] = deviceTokenList
        params['needDetails'] = GtConfig.isPushListNeedDetails()
        params['async'] = GtConfig.isPushListAsync()

        return self.httpPostJson(self.host, params)
Esempio n. 5
0
    def pushAPNMessageToList(self, appId, contentId, deviceTokenList):
        for deviceToken in deviceTokenList:
            if deviceToken is None or len(deviceToken) != 64:
                raise Exception("deviceToken " + deviceToken + " length must be 64.")

        params = dict()
        params['action'] = "apnPushToListAction"
        params['appkey'] = self.appKey
        params['appId'] = appId
        params['contentId'] = contentId
        params['DTL'] = deviceTokenList
        params['needDetails'] = GtConfig.isPushListNeedDetails()
        params['async'] = GtConfig.isPushListAsync()

        return self.httpPostJson(self.host, params)
Esempio n. 6
0
 def cycleInspect(self):
     if len(IGeTui.serviceMap[self.appKey]) == 0:
         raise ValueError("can't get fastest host from empty list")
     else:
         t = threading.Timer(GtConfig.getHttpInspectInterval(), self.getFastUrl)
         t.setDaemon(True)
         t.start()
Esempio n. 7
0
    def submit(self):
        requestId = str(uuid.uuid1())
        self.seqId = 0

        data = dict()
        data['requestId'] = requestId
        data['appkey'] = self.APPKEY
        data['action'] = 'pushMessageToSingleBatchAction'
        data['serialize'] = 'pb'
        data['async'] = GtConfig.isPushSingleBatchAsync()

        try:
            request = gt_req_pb2.SingleBatchRequest()
            request.batchId = self.batchId
            for msg in self.innerMsgList:
                tmp = request.batchItem.add()
                tmp.CopyFrom(msg)

            data["singleDatas"] = base64.encodestring(
                request.SerializeToString())
            self.lastPostData = data
            self.innerMsgList = []
            return self.push.httpPostJson(self.push.host, data, True)
        except:
            raise Exception("submit single batch request failed")
Esempio n. 8
0
 def cycleInspect(self):
     if len(IGeTui.serviceMap[self.appKey]) == 0:
         raise ValueError("can't get fastest host from empty list")
     else:
         t = threading.Timer(GtConfig.getHttpInspectInterval(), self.getFastUrl)
         t.setDaemon(True)
         t.start()
Esempio n. 9
0
    def httpPost(self, host, params, needGzip=False):
        if GtConfig.getHttpProxyIp() is not None:
            #如果通过代理访问我们接口,需要自行配置代理,示例如下:
            ipport = GtConfig.getHttpProxyIp() + ":" + GtConfig.getHttpProxyPort()
            opener = urllib2.build_opener(urllib2.ProxyHandler({ipport}), urllib2.HTTPHandler(debuglevel=1))
            urllib2.install_opener(opener)

        data_json = json.dumps(params)

        headers = dict()
        headers['Gt-Action'] = params.get("action")
        if needGzip:
            out = StringIO.StringIO()
            with gzip.GzipFile(fileobj=out, mode="w") as f:
                f.write(data_json)
            data_json = out.getvalue()
            headers['Content-Encoding'] = 'gzip'
            headers['Accept-Encoding'] = 'gzip'

        req = urllib2.Request(host, data_json, headers)
        retry_time_limit = GtConfig.getHttpTryCount()
        isFail = True
        tryTime = 0
        res_stream = None
        while isFail and tryTime < retry_time_limit:
            try:
                res_stream = urllib2.urlopen(req, timeout=GtConfig.getHttpConnectionTimeOut())
                isFail = False
            except Exception:
                isFail = True
                tryTime += 1
                #print("try " + str(tryTime) + " time failed, time out.")

        if res_stream is None:
            return None
        page_str = res_stream.read()
        if needGzip:
            compressedstream = StringIO.StringIO(page_str)
            with gzip.GzipFile(fileobj=compressedstream) as f:
                data = f.read()
                return eval(data)
        else:
            return eval(page_str)
Esempio n. 10
0
 def httpPostJson(self, host, params, needGzip=False):
     params['version'] = GtConfig.getSDKVersion()
     ret = self.httpPost(host, params, needGzip)
     if ret is None or ret == '':
         if params.get('requestId') is not None:
             raise RequestException(params['requestId'])
         return ret
     if 'sign_error' == ret['result']:
         if self.connect():
             ret = self.httpPostJson(host, params, needGzip)
     elif 'domain_error' == ret['result']:
         IGeTui.serviceMap[self.appKey] = ret['osList']
         self.getFastUrl(ret['osList'])
         ret = self.httpPostJson(self.host, params)
     return ret
Esempio n. 11
0
 def httpPostJson(self, host, params, needGzip=False):
     params['version'] = GtConfig.getSDKVersion()
     ret = self.httpPost(host, params, needGzip)
     if ret is None or ret == '':
         if params.get('requestId') is not None:
             raise RequestException(params['requestId'])
         return ret
     if 'sign_error' == ret['result']:
         if self.connect():
             ret = self.httpPostJson(host, params, needGzip)
     elif 'domain_error' == ret['result']:
         IGeTui.serviceMap[self.appKey] = ret['osList']
         self.getFastUrl(ret['osList'])
         ret = self.httpPostJson(self.host, params)
     return ret
Esempio n. 12
0
    def httpPost(self, host, params, needGzip=False):
        if GtConfig.getHttpProxyIp() is not None:
            #如果通过代理访问我们接口,需要自行配置代理,示例如下:
            ipport = GtConfig.getHttpProxyIp(
            ) + ":" + GtConfig.getHttpProxyPort()
            print ipport
            opener = urllib2.build_opener(urllib2.ProxyHandler({ipport}),
                                          urllib2.HTTPHandler(debuglevel=1))
            urllib2.install_opener(opener)

        data_json = json.dumps(params)

        headers = dict()
        headers['Gt-Action'] = params.get("action")
        if needGzip:
            out = StringIO.StringIO()
            with gzip.GzipFile(fileobj=out, mode="w") as f:
                f.write(data_json)
            data_json = out.getvalue()
            headers['Content-Encoding'] = 'gzip'
            headers['Accept-Encoding'] = 'gzip'

        req = urllib2.Request(host, data_json, headers)
        retry_time_limit = GtConfig.getHttpTryCount()
        isFail = True
        tryTime = 0
        res_stream = None
        while isFail and tryTime < retry_time_limit:
            try:
                if '_create_unverified_context' in dir(ssl):
                    ct = ssl._create_unverified_context()
                    res_stream = urllib2.urlopen(
                        req,
                        timeout=GtConfig.getHttpConnectionTimeOut(),
                        context=ct)
                else:
                    res_stream = urllib2.urlopen(
                        req, timeout=GtConfig.getHttpConnectionTimeOut())
                isFail = False
            except Exception as e:
                isFail = True
                tryTime += 1
                #print("try " + str(tryTime) + " time failed, time out.")

        if res_stream is None:
            return None
        page_str = res_stream.read()
        if needGzip:
            compressedstream = StringIO.StringIO(page_str)
            with gzip.GzipFile(fileobj=compressedstream) as f:
                data = f.read()
                return eval(data)
        else:
            return eval(page_str)
Esempio n. 13
0
    def __init__(self, host, appKey, masterSecret, ssl = None):
        self.appKey = appKey
        self.masterSecret = masterSecret
		
        if host is not None:
            host = host.strip()
			
        if ssl is None and host is not None and host != '' and host.lower().startswith('https:'):
            ssl = True
		
        self.useSSL = (ssl if ssl is not None else False);
		
        if host is None or len(host) <= 0:
            self.hosts = GtConfig.getDefaultDomainUrl(self.useSSL)
        else:
            self.hosts = list()
            self.hosts.append(host)
        self.initOSDomain()
Esempio n. 14
0
    def __init__(self, host, appKey, masterSecret, ssl = None):
        self.appKey = appKey
        self.masterSecret = masterSecret
		
        if host is not None:
            host = host.strip()
			
        if ssl is None and host is not None and host != '' and host.lower().startswith('https:'):
            ssl = True
		
        self.useSSL = (ssl if ssl is not None else False);
		
        if host is None or len(host) <= 0:
            self.hosts = GtConfig.getDefaultDomainUrl(self.useSSL)
        else:
            self.hosts = list()
            self.hosts.append(host)
        self.initOSDomain()
Esempio n. 15
0
    def submit(self):
        requestId = str(uuid.uuid1())
        self.seqId = 0

        data = dict()
        data['requestId'] = requestId
        data['appkey'] = self.APPKEY
        data['action'] = 'pushMessageToSingleBatchAction'
        data['serialize'] = 'pb'
        data['async'] = GtConfig.isPushSingleBatchAsync()

        try:
            request = gt_req_pb2.SingleBatchRequest()
            request.batchId = self.batchId
            for msg in self.innerMsgList:
                tmp = request.batchItem.add()
                tmp.CopyFrom(msg)

            data["singleDatas"] = base64.encodestring(request.SerializeToString())
            self.lastPostData = data
            self.innerMsgList = []
            return self.push.httpPostJson(self.push.host, data, True)
        except:
            raise Exception("submit single batch request failed")
Esempio n. 16
0
        params['contentId'] = contentId
        params['type'] = 2
        return self.httpPostJson(self.host, params)

    def pushMessageToList(self, contentId, targets):
        params = dict()
        params['action'] = 'pushMessageToListAction'
        params['appkey'] = self.appKey
        params['contentId'] = contentId
        needDetails = GtConfig.isPushListNeedDetails()
        params['needDetails'] = GtConfig.isPushListNeedDetails()
        async = GtConfig.isPushListAsync()
        params["async"] = async

        if async and not needDetails:
            limit = GtConfig.getAsyncListLimit()
        else:
            limit = GtConfig.getSyncListLimit()

        if len(targets) > limit:
            raise AssertionError("target size:" + str(len(targets)) + " beyond the limit:" + str(limit))

        clientIdList = []
        aliasList = []
        appId = ''
        for target in targets:
            clientId = target.clientId.strip()
            alias = target.alias.strip()
            if clientId != '':
                clientIdList.append(clientId)
            elif alias != '':
Esempio n. 17
0
        params['contentId'] = contentId
        params['type'] = 2
        return self.httpPostJson(self.host, params)

    def pushMessageToList(self, contentId, targets):
        params = dict()
        params['action'] = 'pushMessageToListAction'
        params['appkey'] = self.appKey
        params['contentId'] = contentId
        needDetails = GtConfig.isPushListNeedDetails()
        params['needDetails'] = GtConfig.isPushListNeedDetails()
        async = GtConfig.isPushListAsync()
        params["async"] = async

        if async and not needDetails:
            limit = GtConfig.getAsyncListLimit()
        else:
            limit = GtConfig.getSyncListLimit()

        if len(targets) > limit:
            raise AssertionError("target size:" + str(len(targets)) +
                                 " beyond the limit:" + str(limit))

        clientIdList = []
        aliasList = []
        appId = ''
        for target in targets:
            clientId = target.clientId.strip()
            alias = target.alias.strip()
            if clientId != '':
                clientIdList.append(clientId)