def assert_DCAE_app_consumed(self, app_url, expected_messages_amount):
        logger.info("GET at: " + app_url)
        resp = HttpRequests.session_without_env().get(app_url, timeout=10)
        HttpRequests.checkStatusCode(resp.status_code, DCAE_APP_NAME)

        assert resp.content == expected_messages_amount, \
            "Messages consumed by simulator: " + resp.content + " expecting: " + expected_messages_amount
 def configure_dcae_app_simulator_to_consume_messages_from_topics(
         self, app_url, topics):
     logger.info("PUT at: " + app_url)
     resp = HttpRequests.session_without_env().put(app_url,
                                                   data={'topics': topics},
                                                   timeout=10)
     HttpRequests.checkStatusCode(resp.status_code, DCAE_APP_NAME)
    def assert_DCAE_app_consumed_proper_messages(self, app_url,
                                                 message_filepath):
        logger.info("POST at: " + app_url)
        file = open(message_filepath, "rb")
        data = file.read()
        file.close()

        resp = HttpRequests.session_without_env().post(app_url,
                                                       data=data,
                                                       timeout=10)
        HttpRequests.checkStatusCode(resp.status_code, DCAE_APP_NAME)
Ejemplo n.º 4
0
def newGroupRequest(eventId, fromAccount, fromGroup, operate, message=""):
    url = "http://" + host + "resp/botInvitedJoinGroupRequestEvent"
    data = json.dumps({
        'sessionKey': getSession(),
        'eventId': eventId,
        'fromId': fromAccount,
        'groupId': fromGroup,
        'operate': operate,
        'message': message
    })
    HttpRequests.doPost(url, data, {'Content-Type': 'application/json'})
    def send_messages(self, simulator_url, message_filepath):
        logger.info("Reading message to simulator from: " + message_filepath)

        file = open(message_filepath, "rb")
        data = file.read()
        file.close()

        logger.info("POST at: " + simulator_url)
        resp = HttpRequests.session_without_env().post(simulator_url,
                                                       data=data,
                                                       timeout=5)
        HttpRequests.checkStatusCode(resp.status_code, XNF_SIMULATOR_NAME)
    def assert_DCAE_app_consumed_less_equal_than(self, app_url,
                                                 messages_threshold):
        logger.info("GET at: " + app_url)
        resp = HttpRequests.session_without_env().get(app_url, timeout=10)
        HttpRequests.checkStatusCode(resp.status_code, DCAE_APP_NAME)

        logger.debug("Messages consumed by simulator: " + resp.content +
                     " expecting more than 0 and less/equal than " +
                     messages_threshold)

        assert 0 < int(resp.content) <= int(messages_threshold), \
            "Messages consumed by simulator: " + resp.content + \
            " expecting more than 0 and less/equal than " + messages_threshold
Ejemplo n.º 7
0
    def publish_hv_ves_configuration_in_consul(self, consul_url,
                                               consul_configuration_filepath):
        logger.info("Reading consul configuration file from: " +
                    consul_configuration_filepath)
        file = open(consul_configuration_filepath, "rb")
        data = file.read()
        file.close()

        logger.info("PUT at: " + consul_url)
        resp = HttpRequests.session_without_env().put(consul_url,
                                                      data=data,
                                                      timeout=5)
        HttpRequests.checkStatusCode(resp.status_code, CONSUL_NAME)
Ejemplo n.º 8
0
def recall(fromId):
    url = "http://" + host + "recall"
    data = json.dumps({'sessionKey': getSession(), 'target': fromId})
    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})
    array = json.loads(response)
    return array['code']
 def __consultar_estado(self):
     #Definimos los headers para el request
     headers = {"PRIVATE-TOKEN": self.__configuracion_ci.get_token()}
     request_url = (self.__configuracion_ci.get_api_url() + "/projects/" +
                    self.__configuracion_ci.get_usuario() + "%2F" +
                    self.__configuracion_ci.get_repositorio() +
                    "/pipelines?per_page=1&page=1")
     response = HttpRequests.get(request_url, headers=headers)
     return response.text
Ejemplo n.º 10
0
def uploadImage(type, img):
    url = "http://" + host + "uploadImage"
    data = "sessionKey=" + getSession() + "&type=" + type + "&img=" + img
    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'multipart/form-data'})
    if '.mirai' in response:
        array = json.loads(response)
        return array['url']
    else:
        return response
Ejemplo n.º 11
0
 def __consultar_estado(self):
     #Definimos los headers para el request
     headers = {
         "Travis-API-Version": "3",
         "Authorization": "token " + self.__configuracion_ci.get_token()
     }
     request_url = (self.__configuracion_ci.get_api_url() + "/repo/" +
                    self.__configuracion_ci.get_usuario() + "%2F" +
                    self.__configuracion_ci.get_repositorio() +
                    "/builds?limit=1&sort_by=finished_at:desc")
     response = HttpRequests.get(request_url, headers=headers)
     return response.text
Ejemplo n.º 12
0
 def __init__(self):
     self.dataFileName="data.txt"
     self.req = HttpRequests();
     self.friend_list = {}
     self.data={}
     self.data['client_id']= int(random.uniform(111111, 888888))
     self.data['ptwebqq'] = ''
     self.data['psessionid'] = ''
     self.data['selfuin']=''
     self.appid = 0
     self.data['vfwebqq'] = ''
     self.qrcode_path = "./vcode.jpg"  # QRCode保存路径
     self.username = ''
     self.account = 0
Ejemplo n.º 13
0
def createSession():
    #创建新 Session
    url = "http://" + host + "auth"
    data = json.dumps({'authKey': authKey})
    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})
    array = json.loads(response)

    session = array['session']

    #绑定 Session 到 Bot
    url = "http://" + host + "verify"
    data = json.dumps({'sessionKey': session, 'qq': qq})
    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})

    #修改 Session 的权限
    url = "http://" + host + "config"
    data = json.dumps({'sessionKey': session, 'enableWebsocket': 'true'})
    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})

    return session
Ejemplo n.º 14
0
def sendGroupMessage(fromGroup, fromAccount, messages, fromId=-1):
    url = "http://" + host + "sendGroupMessage"
    data = json.dumps({
        'sessionKey': getSession(),
        'target': fromGroup,
        'quote': fromId,
        'messageChain': messages
    })

    if (fromId == -1):
        data = data.replace('"quote": -1, ', '')

    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})
    messageId = getMessageId(response)
    return messageId
Ejemplo n.º 15
0
def getHumanResourceInfo(type, hr):
    url = DOKTA_OFFICE_SERVER + "hr/"
    url = url + type

    if (type == 'tag'):
        data = "tags=" + hr.replace(' ', ',')
    else:
        data = hr

    url = url + "?fullMode=true"
    try:
        response = HttpRequests.doPost(url, data)
    except:
        response = TEXT_ERROR_MESSAGE

    return response
Ejemplo n.º 16
0
def sendFriendMessage(fromAccount, messages, fromId=-1):
    url = "http://" + host + "sendFriendMessage"
    data = json.dumps({
        'sessionKey': getSession(),
        'target': fromAccount,
        'messageChain': messages
    })

    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})
    print(response)
    if 'code' not in response:
        print(response)
        print(data)
        return 0

    messageId = getMessageId(response)
    return messageId
Ejemplo n.º 17
0
 def __init__(self,isLoadData=False):
     self.dataFileName="data.txt"
     self.req = HttpRequests(isLoadData);
     self.data={}
     self.data['client_id']= int(random.uniform(111111, 888888))
     self.data['ptwebqq'] = ''
     self.data['psessionid'] = ''
     self.data['selfuin']=''
     self.appid = 0
     self.data['vfwebqq'] = ''
     self.qrcode_path = "./vcode.jpg"  # QRCode保存路径
     self.username = ''
     self.account = 0
     self.friendList={}
     self.uinInfo={}
     self.redis=redis.StrictRedis(host='localhost', port=6379, db=0)
     if isLoadData:
         self.data=self.__loadData()
     pass
Ejemplo n.º 18
0
def ocrBaiduCloudAnalyze(url):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    imageId = str(random.randint(0, 9999999)) + ".jpg"
    r = requests.get(url)
    imageData = HttpRequests.doGet(url)

    with open(imageId, 'wb') as f:
        f.write(r.content)

    f = open(imageId, 'rb')
    img = base64.encodebytes(f.read())

    os.remove(imageId)

    params = {"image": img}
    access_token = ocrBaiduCloudToken()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return response.text
Ejemplo n.º 19
0
def getMaterialInfo(material, fullMode):
    url = DOKTA_OFFICE_SERVER + "material/" + material
    data = "msgMode=true&fullMode=" + fullMode
    response = HttpRequests.doPost(url, data)
    return response
Ejemplo n.º 20
0
def releaseSession(session):
    #绑定 Session 到 Bot
    url = "http://" + host + "release"
    data = json.dumps({'sessionKey': session, 'qq': qq})
    response = HttpRequests.doPost(url, data,
                                   {'Content-Type': 'application/json'})
Ejemplo n.º 21
0
__author__ = 'lvxinwei'
import cookielib, urllib, urllib2, socket,json
from HttpRequests import *
import pickle,time
with open("data.txt", 'r') as f:
    data=pickle.load(f)
f.close()
req=HttpRequests(True)
reply_content="12345"
tuin=str(2891802047)
psessionid=data['psessionid']
client_id=data['client_id']
fix_content = str(reply_content.replace("\\", "\\\\\\\\").replace("\n", "\\\\n").replace("\t", "\\\\t")).decode("utf-8")
rsp = ""

req_url = "http://d.web2.qq.com/channel/send_buddy_msg2"
data = (
    ('r', '{{"to":{0}, "face":594, "content":"[\\"{4}\\", [\\"font\\", {{\\"name\\":\\"Arial\\", \\"size\\":\\"10\\", \\"style\\":[0, 0, 0], \\"color\\":\\"000000\\"}}]]", "clientid":"{1}", "msg_id":{2}, "psessionid":"{3}"}}'.format(tuin, client_id, "78652",  psessionid, fix_content)),
    ('clientid', client_id),
    ('psessionid', psessionid)
)
while True:
    rsp =req.post(req_url, data)
    rsp_json = json.loads(rsp)
    print rsp_json
    time.sleep(60)
#



Ejemplo n.º 22
0
def getNewsInfo(type):
    url = DOKTA_OFFICE_SERVER + "news/" + type
    response = HttpRequests.doGet(url)
    return response
Ejemplo n.º 23
0
class QQ:
    def __init__(self):
        self.dataFileName="data.txt"
        self.req = HttpRequests();
        self.friend_list = {}
        self.data={}
        self.data['client_id']= int(random.uniform(111111, 888888))
        self.data['ptwebqq'] = ''
        self.data['psessionid'] = ''
        self.data['selfuin']=''
        self.appid = 0
        self.data['vfwebqq'] = ''
        self.qrcode_path = "./vcode.jpg"  # QRCode保存路径
        self.username = ''
        self.account = 0
    def __saveData(self):
        with open(self.dataFileName, 'w') as f:
             pickle.dump(self.data,f)
        f.close()
    def login_by_qrcode(self):
        logging.info("Requesting the login pages...")
        initurl_html = self.req.get('http://w.qq.com/login.html')
        print initurl_html
        initurl = get_revalue(initurl_html, r'\.src = "(.+?)"', "Get Login Url Error.", 1)
        html = self.req.get(initurl + '0')
        appid = get_revalue(html, r'var g_appid =encodeURIComponent\("(\d+)"\);', 'Get AppId Error', 1)
        sign = get_revalue(html, r'var g_login_sig=encodeURIComponent\("(.*?)"\);', 'Get Login Sign Error', 0)
        js_ver = get_revalue(html, r'var g_pt_version=encodeURIComponent\("(\d+)"\);', 'Get g_pt_version Error', 1)
        mibao_css = get_revalue(html, r'var g_mibao_css=encodeURIComponent\("(.+?)"\);', 'Get g_mibao_css Error', 1)
        star_time = date_to_millis(datetime.datetime.utcnow())
        error_times = 0
        ret = []
        while True:
            error_times += 1
            vcodeUrl='https://ssl.ptlogin2.qq.com/ptqrshow?appid={0}&e=0&l=L&s=8&d=72&v=4'.format(appid)
            self.req.downloadFile(vcodeUrl,self.qrcode_path)
            print "Please scan the downloaded QRCode"

            while True:
                checkLoginUrl='https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1&login2qq=1&aid={0}&u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-0-{1}&mibao_css={2}&t=undefined&g=1&js_type=0&js_ver={3}&login_sig={4}'.format(
                        appid, date_to_millis(datetime.datetime.utcnow()) - star_time, mibao_css, js_ver, sign);
                html = self.req.get(checkLoginUrl,{'Referer':initurl})
                ret = html.split("'")
                print ret
                time.sleep(2)
                if ret[1] in ('0', '65'):  # 65: QRCode 失效, 0: 验证成功, 66: 未失效, 67: 验证中
                    break
            if ret[1] == '0' or error_times > 10:
                break

        if ret[1] != '0':
            return
        print "QRCode scaned, now logging in."

        # 删除QRCode文件
        if os.path.exists(self.qrcode_path):
            os.remove(self.qrcode_path)

        # 记录登陆账号的昵称
        self.username = ret[11]
        url = get_revalue(self.req.get(ret[5]), r' src="(.+?)"', 'Get mibao_res Url Error.', 0)
        if url != '':
            html = self.req.get(url.replace('&amp;', '&'))
            url = get_revalue(html, r'location\.href="(.+?)"', 'Get Redirect Url Error', 1)
            self.req.get(url)
        self.data['ptwebqq'] = self.req.getCookies()['ptwebqq']
        print self.data
        login_error = 1
        ret = {}
        while login_error > 0:
            try:
                html = self.req.post('http://d.web2.qq.com/channel/login2', {
                    'r': '{{"ptwebqq":"{0}","clientid":{1},"psessionid":"{2}","status":"online"}}'.format(self.data['ptwebqq'] ,
                                                                                                          self.data['client_id'] ,
                                                                                                          self.data['psessionid'] )
                }, {'Referer':"http://d.web2.qq.com/proxy.html?v=20030916001&callback=1&id=2"} )
                ret = json.loads(html)
                login_error = 0
            except:
                login_error += 1
                print "login fail, retrying..."
                exit()

        if ret['retcode'] != 0:
            print ret
            return

        self.data['vfwebqq']  = ret['result']['vfwebqq']
        self.data['psessionid']  = ret['result']['psessionid']
        self.data['selfuin'] = ret['result']['uin']
        self.__saveData()

        #print "QQ:{0} login successfully, Username:{1}".format(self.account, self.username)
        print self.username

    def relogin(self, error_times=0):
        if error_times >= 10:
            return False
        try:
            html = self.req.post('http://d.web2.qq.com/channel/login2', {
                'r': '{{"ptwebqq":"{0}","clientid":{1},"psessionid":"{2}","key":"","status":"online"}}'.format(
                    self.data['ptwebqq'] ,
                    self.data['client_id'] ,
                    self.data['psessionid'] )
            } )
            ret = json.loads(html)
            self.data['vfwebqq']  = ret['result']['vfwebqq']
            self.data['psessionid']  = ret['result']['psessionid']
            return True
        except:
            logging.info("login fail, retryng..." + str(error_times))
            return self.relogin(error_times + 1)

    def check_msg(self, error_times=0):
        if error_times >= 5:
            if not self.relogin():
                raise IOError("Account offline.")
            else:
                error_times = 0

        # 调用后进入单次轮询,等待服务器发回状态。
        html = self.req.post('http://d.web2.qq.com/channel/poll2', {
            'r': '{{"ptwebqq":"{1}","clientid":{2},"psessionid":"{0}","key":""}}'.format(self.data['psessionid'] , self.data['ptwebqq'] ,
                                                                                         self.data['client_id'] )
        })

        try:
            if html == "":
                return self.check_msg()
            ret = json.loads(html)
            print ret

            ret_code = ret['retcode']

            if ret_code in (102,):
                logging.info("received retcode: " + str(ret_code) + ": No message.")
                time.sleep(1)
                return

            if ret_code in (103,):
                logging.warning("received retcode: " + str(ret_code) + ": Check error.retrying.." + str(error_times))
                time.sleep(1)
                return self.check_msg(error_times + 1)

            if ret_code in (121,):
                logging.warning("received retcode: " + str(ret_code))
                return self.check_msg(5)

            elif ret_code == 0:
                msg_list = []
                pm_list = []
                sess_list = []
                group_list = []
                notify_list = []
                for msg in ret['result']:
                    ret_type = msg['poll_type']
                    if ret_type == 'message':
                        pm_list.append(PmMsg(msg))
                    elif ret_type == 'group_message':
                        group_list.append(GroupMsg(msg))
                    elif ret_type == 'sess_message':
                        sess_list.append(SessMsg(msg))
                    elif ret_type == 'input_notify':
                        notify_list.append(InputNotify(msg))
                    elif ret_code == 'kick_message':
                        notify_list.append(KickMessage(msg))
                    else:
                        logging.warning("unknown message type: " + str(ret_type) + "details:    " + str(msg))

                group_list.sort(key=lambda x: x.seq)
                msg_list += pm_list + sess_list + group_list + notify_list
                if not msg_list:
                    return
                return msg_list
            elif ret_code == 100006:
                print "POST data error"
                return

            elif ret_code == 116:
                self.data['ptwebqq'] = ret['p']
                self.__saveData()
                return
            else:
                print "unknown retcode " + str(ret_code)
                return
        except ValueError, e:
            print "Check error occured: " + str(e)
            time.sleep(1)
            return self.check_msg(error_times + 1)
        except BaseException, e:
            time.sleep(1)
            return self.check_msg(error_times + 1)
Ejemplo n.º 24
0
def ocrBaiduCloudToken():
    url = DOKTA_OFFICE_SERVER + "hr/token"
    response = HttpRequests.doPost(url, "")
    return response
Ejemplo n.º 25
0
def getGroupList():
    url = "http://" + host + "groupList?sessionKey=" + getSession()
    response = HttpRequests.doGet(url, {'Content-Type': 'application/json'})
    response = json.loads(response)
    return response
 def reset_DCAE_app_simulator(self, app_url):
     logger.info("DELETE at: " + app_url)
     resp = HttpRequests.session_without_env().delete(app_url, timeout=10)
     HttpRequests.checkStatusCode(resp.status_code, DCAE_APP_NAME)
Ejemplo n.º 27
0
class QQCore:
    def __init__(self,isLoadData=False):
        self.dataFileName="data.txt"
        self.req = HttpRequests(isLoadData);
        self.data={}
        self.data['client_id']= int(random.uniform(111111, 888888))
        self.data['ptwebqq'] = ''
        self.data['psessionid'] = ''
        self.data['selfuin']=''
        self.appid = 0
        self.data['vfwebqq'] = ''
        self.qrcode_path = "./vcode.jpg"  # QRCode保存路径
        self.username = ''
        self.account = 0
        self.friendList={}
        self.uinInfo={}
        self.redis=redis.StrictRedis(host='localhost', port=6379, db=0)
        if isLoadData:
            self.data=self.__loadData()
        pass
    #获取相关信息
    def __loadData(self):
        with open(self.dataFileName, 'r') as f:
            data=pickle.load(f)
        f.close()
        return  data
    #保存data
    def __saveData(self):
        with open(self.dataFileName, 'w') as f:
             pickle.dump(self.data,f)
        f.close()
    #计算hash信息
    def __hash(self,selfuin,ptwebqq):
        selfuin=str(selfuin)
        selfuin += ""
        N=[0,0,0,0]
        for T in range(len(ptwebqq)):
            N[T%4]=N[T%4]^ord(ptwebqq[T])
        U=["EC","OK"]
        V=[0, 0, 0, 0]
        V[0]=int(selfuin) >> 24 & 255 ^ ord(U[0][0])
        V[1]=int(selfuin) >> 16 & 255 ^ ord(U[0][1])
        V[2]=int(selfuin) >>  8 & 255 ^ ord(U[1][0])
        V[3]=int(selfuin)       & 255 ^ ord(U[1][1])
        U=[0,0,0,0,0,0,0,0]
        U[0]=N[0]
        U[1]=V[0]
        U[2]=N[1]
        U[3]=V[1]
        U[4]=N[2]
        U[5]=V[2]
        U[6]=N[3]
        U[7]=V[3]
        N=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
        V=""
        for T in range(len(U)):
            V+= N[ U[T]>>4 & 15]
            V+= N[ U[T]    & 15]
        return V
    def login_by_qrcode(self):
        initurl_html = self.req.get('http://w.qq.com/login.html')
        initurl = get_revalue(initurl_html, r'\.src = "(.+?)"', "Get Login Url Error.", 1)
        html = self.req.get(initurl + '0')
        appid = get_revalue(html, r'var g_appid =encodeURIComponent\("(\d+)"\);', 'Get AppId Error', 1)
        sign = get_revalue(html, r'var g_login_sig=encodeURIComponent\("(.*?)"\);', 'Get Login Sign Error', 0)
        js_ver = get_revalue(html, r'var g_pt_version=encodeURIComponent\("(\d+)"\);', 'Get g_pt_version Error', 1)
        mibao_css = get_revalue(html, r'var g_mibao_css=encodeURIComponent\("(.+?)"\);', 'Get g_mibao_css Error', 1)
        star_time = date_to_millis(datetime.datetime.utcnow())
        error_times = 0
        ret = []
        while True:
            error_times += 1
            vcodeUrl='https://ssl.ptlogin2.qq.com/ptqrshow?appid={0}&e=0&l=L&s=8&d=72&v=4'.format(appid)
            self.req.downloadFile(vcodeUrl,self.qrcode_path)
            print "Please scan the downloaded QRCode"
            while True:
                checkLoginUrl='https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1&login2qq=1&aid={0}&u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-0-{1}&mibao_css={2}&t=undefined&g=1&js_type=0&js_ver={3}&login_sig={4}'.format(
                        appid, date_to_millis(datetime.datetime.utcnow()) - star_time, mibao_css, js_ver, sign);
                html = self.req.get(checkLoginUrl,{'Referer':initurl})
                ret = html.split("'")
                time.sleep(2)
                if ret[1] in ('0', '65'):  # 65: QRCode 失效, 0: 验证成功, 66: 未失效, 67: 验证中
                    break
            if ret[1] == '0' or error_times > 10:
                break
        if ret[1] != '0':
            return
        print "QRCode scaned, now logging in."
        # 删除QRCode文件
        if os.path.exists(self.qrcode_path):
            os.remove(self.qrcode_path)
        # 记录登陆账号的昵称
        self.username = ret[11]
        url = get_revalue(self.req.get(ret[5]), r' src="(.+?)"', 'Get mibao_res Url Error.', 0)
        if url != '':
            html = self.req.get(url.replace('&amp;', '&'))
            url = get_revalue(html, r'location\.href="(.+?)"', 'Get Redirect Url Error', 1)
            self.req.get(url)
        self.data['ptwebqq'] = self.req.getCookies()['ptwebqq']
        login_error = 1
        ret = {}
        while login_error > 0:
            try:
                html = self.req.post('http://d.web2.qq.com/channel/login2', {
                    'r': '{{"ptwebqq":"{0}","clientid":{1},"psessionid":"{2}","status":"online"}}'.format(self.data['ptwebqq'] ,
                                                                                                          self.data['client_id'] ,
                                                                                                          self.data['psessionid'] )
                }, {'Referer':"http://d.web2.qq.com/proxy.html?v=20030916001&callback=1&id=2"} )
                ret = json.loads(html)
                login_error = 0
            except:
                login_error += 1
                print "login fail, retrying..."
                exit()

        if ret['retcode'] != 0:
            print ret
            return
        self.data['vfwebqq']  = ret['result']['vfwebqq']
        self.data['psessionid']  = ret['result']['psessionid']
        self.data['selfuin'] = ret['result']['uin']
        self.__saveData()
    def relogin(self, error_times=0):
        if error_times >= 10:
            return False
        try:
            html = self.req.post('http://d.web2.qq.com/channel/login2', {
                'r': '{{"ptwebqq":"{0}","clientid":{1},"psessionid":"{2}","key":"","status":"online"}}'.format(
                    self.req.getCookies()['ptwebqq'],
                    self.data['client_id'] ,
                    self.data['psessionid'] )
            } )
            ret = json.loads(html)
            self.data['vfwebqq']  = ret['result']['vfwebqq']
            self.data['psessionid']  = ret['result']['psessionid']
            return True
        except:
            return self.relogin(error_times + 1)
    #处理消息
    def __handleMsg(self,msgs):
        print msgs
        for msg in msgs:
            temp=json.dumps(msg)
            self.redis.rpush("message_box_in",temp)


    def getAccountByUin(self,uin):
        if uin in self.uinInfo:
            return self.uinInfo[uin]
        else:
            ret=self.uin_to_account(uin)
            if ret:
                return ret
        return False

    #获取好友详细信息
    def getFriendInfo(self):
        ret=self.getFriendList()
        if not ret:
            return False
        friendlist={}
        uinInfo={}
        for user in ret['marknames']:
            if user['uin'] not in friendlist:
                friendlist[user['uin']]={}
            friendlist[user['uin']]['markname']=user['markname']
        for user in ret['info']:
             if user['uin'] not in friendlist:
                friendlist[user['uin']]={}
             friendlist[user['uin']]['nick']=user['nick']
             friendlist[user['uin']]['uin']=user['uin']
             account=self.uin_to_account(user['uin'])
             friendlist[user['uin']]['account']=account
             friendlist[account]=friendlist[user['uin']]
             del friendlist[user['uin']]
             uinInfo[user['uin']]=account
        self.friendList=friendlist
        self.uinInfo=uinInfo
        return friendlist

    #获取所有用户列表,但是不含QQ号
    def getFriendList(self):
        try :
            requestUrl="http://s.web2.qq.com/api/get_user_friends2"
            hash=self.__hash(self.data['selfuin'],self.req.getCookies()['ptwebqq'])
            ret=self.req.post(requestUrl,{'vfwebqq':self.data['vfwebqq'],'hash':hash})
            ret=json.loads(ret)
            if ret['retcode'] ==0:
                return ret['result']
            else :
                return False
        except Exception,e:
            print e
Ejemplo n.º 28
0
 def __init__(self, Dialog):
     super().setupUi(Dialog)  # 调用父类的setupUI函数
     self.toolButton.clicked.connect(lambda: self.openFile())
     self.pushButton.clicked.connect(lambda: self.land())
     httpRequests = HttpRequests.HttpRequests()
Ejemplo n.º 29
0
def getAboutDoInfo(type):
    url = DOKTA_OFFICE_SERVER + "about/" + type
    response = HttpRequests.doGet(url)
    response = json.loads(response)
    return response['msg']
Ejemplo n.º 30
0
def messageFromId(id):
    url = "http://" + host + "messageFromId?sessionKey=" + getSession(
    ) + "&id=" + id
    response = HttpRequests.doGet(url, {'Content-Type': 'application/json'})
    response = json.loads(response)
    return response