Example #1
0
def test_to_binary():
    assert to_binary(6) == six.binary_type(6)
    assert to_binary(b"aa") == b"aa"
    assert to_binary("cc") == b"cc"
    if six.PY2:
        assert to_binary(u"喵") == "喵"
        assert to_binary("喵") == "喵"
Example #2
0
def test_to_binary():
    assert to_binary(6) == six.binary_type(6)
    assert to_binary(b"aa") == b"aa"
    assert to_binary("cc") == b"cc"
    if six.PY2:
        assert to_binary(u"喵") == "喵"
        assert to_binary("喵") == "喵"
Example #3
0
def wish_read(message, session):
    token = get_token(message, session)
    if (None == token):
        return "输入'豆瓣'完成授权后回到微信"
    client_wechat.auth_with_token(token)
    if get_state(session) == 'booklist' or get_state(session) == 'wishread':
        bookid = session.get(message.content, 0)
        if 0 == bookid:
            return "输入有误,请重新输入"
        else:
            try:
                client_wechat.book.collection(bookid)
            except:
                return "你收藏过这本书啦!"
            else:
                return "设置想读成功!"
        set_state(session, 'wishread')
    elif get_state(session) == 'dnlist':
        dnstr = message.content
        tedstr = ted_kv.get(to_binary(TED_POPULAR))
        retstr = ''
        if None != tedstr:
            speaker_list = json.loads(tedstr)
        dnid = int(dnstr)
        if dnid >= len(speaker_list):
            return '输入有误,请重新输入'
        # change id to keyward
        message.content = speaker_list[dnid]
Example #4
0
    def get_reply(self, message):
        """
        根据 message 的内容获取 Reply 对象。

        :param message: 要处理的 message
        :return: 获取的 Reply 对象
        """
        session_storage = self.session_storage

        id = None
        session = None
        if session_storage and hasattr(message, "source"):
            id = to_binary(message.source)
            session = session_storage[id]

        handlers = self.get_handlers(message.type)
        try:
            for handler, args_count in handlers:
                args = [message, session][:args_count]
                reply = handler(*args)
                if session_storage and id:
                    session_storage[id] = session
                if reply:
                    return process_function_reply(reply, message=message)
        except:
            self.logger.exception("Catch an exception")
Example #5
0
    def get_reply(self, message):
        """
        根据 message 的内容获取 Reply 对象。

        :param message: 要处理的 message
        :return: 获取的 Reply 对象
        """
        session_storage = self.session_storage

        id = None
        session = None
        if session_storage and hasattr(message, "source"):
            id = to_binary(message.source)
            session = session_storage[id]

        handlers = self.get_handlers(message.type)
        try:
            for handler, args_count in handlers:
                args = [message, session][:args_count]
                reply = handler(*args)
                if session_storage and id:
                    session_storage[id] = session
                if reply:
                    return process_function_reply(reply, message=message)
        except:
            self.logger.exception("Catch an exception")
Example #6
0
def wish_read(message, session):
    token = get_token(message, session)
    if (None == token):
        return "输入'豆瓣'完成授权后回到微信"
    client_wechat.auth_with_token(token)
    if get_state(session) == 'booklist' or get_state(session) == 'wishread':
        bookid =  session.get(message.content, 0)
        if 0 == bookid:
            return "输入有误,请重新输入"
        else:
            try:
                client_wechat.book.collection(bookid)
            except:
                return "你收藏过这本书啦!"
            else:
                return "设置想读成功!"
        set_state(session, 'wishread')
    elif get_state(session) ==  'dnlist':
        dnstr =  message.content
        tedstr = ted_kv.get(to_binary(TED_POPULAR))
        retstr = ''
        if None != tedstr:
            speaker_list = json.loads(tedstr)
        dnid = int(dnstr)
        if dnid >= len(speaker_list):
           return '输入有误,请重新输入'
        # change id to keyward
        message.content = speaker_list[dnid]
Example #7
0
 def __init__(self, key):
     key = to_binary(key)
     self.cipher = Cipher(
         algorithms.AES(key),
         modes.CBC(key[:16]),
         backend=default_backend()
     )
Example #8
0
 def __init__(self, key):
     key = to_binary(key)
     self.cipher = Cipher(
         algorithms.AES(key),
         modes.CBC(key[:16]),
         backend=default_backend()
     )
Example #9
0
    def get_reply(self, message):
        """
        Return the raw xml reply for the given message.
        """

        # 读取session
        session_storage = self.config["SESSION_STORAGE"]

        id = None
        session = None
        if session_storage and hasattr(message, "source"):
            id = to_binary(message.source)
            session = session_storage[id]

        # 获取处理该信息的所有handler
        handlers = self.get_handlers(message.type)
        try:
            for handler, args_count in handlers:
                # 从list[...]中取args_count个构成新list
                args = [message, session][:args_count]
                reply = handler(*args)
                if session_storage and id:
                    session_storage[id] = session
                if reply:
                    return reply
        except:
            self.logger.warning("Catch an exception", exc_info=True)
Example #10
0
 def encrypt(self, text, app_id):
     """
     对明文进行加密
     :param text: 需要加密的明文
     :param app_id: 微信公众平台的 AppID
     :return: 加密后的字符串
     """
     text = b"".join([
         to_binary(self.get_random_string()),
         struct.pack(b"I", socket.htonl(len(to_binary(text)))),
         to_binary(text),
         to_binary(app_id)
     ])
     text = pkcs7.encode(text)
     encryptor = self.cipher.encryptor()
     ciphertext = to_binary(encryptor.update(text) + encryptor.finalize())
     return base64.b64encode(ciphertext)
Example #11
0
    def __init__(self, token, encoding_aes_key, app_id):
        key = base64.b64decode(to_binary(encoding_aes_key + '='))
        if len(key) != 32:
            raise UnvalidEncodingAESKey(encoding_aes_key)
        self.prp_crypto = PrpCrypto(key)

        self.token = token
        self.app_id = app_id
Example #12
0
 def encrypt(self, text, app_id):
     """
     对明文进行加密
     :param text: 需要加密的明文
     :param app_id: 微信公众平台的 AppID
     :return: 加密后的字符串
     """
     text = b"".join([
         to_binary(self.get_random_string()),
         struct.pack(b"I", socket.htonl(len(to_binary(text)))),
         to_binary(text),
         to_binary(app_id)
     ])
     text = pkcs7.encode(text)
     encryptor = self.cipher.encryptor()
     ciphertext = to_binary(encryptor.update(text) + encryptor.finalize())
     return base64.b64encode(ciphertext)
Example #13
0
    def __init__(self, token, encoding_aes_key, app_id):
        key = base64.b64decode(to_binary(encoding_aes_key + '='))
        if len(key) != 32:
            raise UnvalidEncodingAESKey(encoding_aes_key)
        self.prp_crypto = PrpCrypto(key)

        self.token = token
        self.app_id = app_id
Example #14
0
def encode(text):
    # 计算需要填充的位数
    amount_to_pad = _BLOCK_SIZE - (len(text) % _BLOCK_SIZE)
    if not amount_to_pad:
        amount_to_pad = _BLOCK_SIZE
    # 获得补位所用的字符
    pad = chr(amount_to_pad)
    return text + to_binary(pad * amount_to_pad)
Example #15
0
def get_token(message, session):
    guid = message.source
    userstr = wechat_kv.get(to_binary(guid))
    if None != userstr:
       user = json.loads(userstr)
       uid = user['uid']
       token = user['token']
       return token
    return None
Example #16
0
def test_prpcrypto():
    key = "ReUrr0NKeHkppBQq"

    assert len(key) == 16

    crypto = PrpCrypto(key)
    text = generate_token(32)
    app_id = generate_token(32)
    assert crypto.decrypt(crypto.encrypt(text, app_id),
                          app_id) == to_binary(text)
Example #17
0
def test_prpcrypto():
    key = "ReUrr0NKeHkppBQq"

    assert len(key) == 16

    crypto = PrpCrypto(key)
    text = generate_token(32)
    app_id = generate_token(32)
    assert crypto.decrypt(crypto.encrypt(text, app_id),
                          app_id) == to_binary(text)
Example #18
0
def speaker(message, session):
    tedstr = ted_kv.get(to_binary(TED_POPULAR))
    retstr = ''
    if None != tedstr:
        speaker_list = json.loads(tedstr)
        if 0 == len(speaker_list):
            return '大牛列表暂时为空'
        for index in range(len(speaker_list)):
            retstr += '[' + str(index) + ']. ' + speaker_list[index] + '\n'
        retstr += u'\n输入序号可以查询大牛著作'
        set_state(session, 'dnlist')
        return retstr
    return "大牛列表暂时还拉不到哦"
Example #19
0
def get_ted_page_name():
    print ted_popular_url
    response = requests.get(ted_popular_url)
    print response
    soup = bs4.BeautifulSoup(response.text)
    ted_name_list = []
    for tag in soup.find_all("h4"):
        if None != tag.string:
            ted_name_list.append(tag.string) 
    ted_name_str = json.dumps(ted_name_list)
    if 0 != len(ted_name_list):
        ted_kv.set(to_binary(TED_POPULAR), ted_name_str)
    return ted_name_str
Example #20
0
def speaker(message, session):
    tedstr = ted_kv.get(to_binary(TED_POPULAR))
    retstr = ''
    if None != tedstr:
       speaker_list = json.loads(tedstr)
       if 0 == len(speaker_list):
           return '大牛列表暂时为空'
       for index in range(len(speaker_list)):
           retstr += '[' + str(index) + ']. ' + speaker_list[index] + '\n'
       retstr += u'\n输入序号可以查询大牛著作'
       set_state(session, 'dnlist')
       return retstr
    return "大牛列表暂时还拉不到哦"
Example #21
0
def test_article():
    article = Article(title="tt",
                      description=to_binary("附近的萨卡里发生"),
                      img="http",
                      url="uuu")
    assert article.render().strip() == to_text("""
    <item>
    <Title><![CDATA[tt]]></Title>
    <Description><![CDATA[附近的萨卡里发生]]></Description>
    <PicUrl><![CDATA[http]]></PicUrl>
    <Url><![CDATA[uuu]]></Url>
    </item>
    """).strip()
Example #22
0
def test_article():
    article = Article(
        title="tt", description=to_binary("附近的萨卡里发生"), img="http", url="uuu"
    )
    assert article.render().strip() == to_text(
        """
    <item>
    <Title><![CDATA[tt]]></Title>
    <Description><![CDATA[附近的萨卡里发生]]></Description>
    <PicUrl><![CDATA[http]]></PicUrl>
    <Url><![CDATA[uuu]]></Url>
    </item>
    """
    ).strip()
Example #23
0
def test_wechat_reply():
    message = parse_user_msg("""
        <xml>
        <ToUserName><![CDATA[toUser]]></ToUserName>
        <FromUserName><![CDATA[fromUser]]></FromUserName>
        <CreateTime>1348831860</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        <PicUrl><![CDATA[this is a url]]></PicUrl>
        <MediaId><![CDATA[media_id]]></MediaId>
        <MsgId>1234567890123456</MsgId>
        </xml>
    """)
    s = to_binary("喵fdsjaklfsk")
    reply = WeChatReply(message=message, s=s)
    assert reply._args['source'] == 'toUser'
    assert reply._args['target'] == 'fromUser'
    assert reply._args['s'] == to_text(s)
    assert isinstance(reply._args['time'], int)
Example #24
0
def test_message_crypt():
    encoding_aes_key = generate_token(32) + generate_token(11)
    token = generate_token()
    timestamp = to_text(int(time.time()))
    nonce = generate_token(5)
    app_id = generate_token(18)
    crypt = MessageCrypt(token=token,
                         encoding_aes_key=encoding_aes_key,
                         app_id=app_id)

    message = crypt.encrypt_message('hello', timestamp, nonce)
    assert message is not None
    message = parse_xml(message)
    assert message is not None
    message = crypt.decrypt_message(message['TimeStamp'], message['Nonce'],
                                    message['MsgSignature'],
                                    message['Encrypt'])
    assert message == to_binary('hello')
Example #25
0
def test_message_crypt():
    encoding_aes_key = generate_token(32) + generate_token(11)
    token = generate_token()
    timestamp = to_text(int(time.time()))
    nonce = generate_token(5)
    app_id = generate_token(18)
    crypt = MessageCrypt(
        token=token, encoding_aes_key=encoding_aes_key, app_id=app_id
    )

    message = crypt.encrypt_message('hello', timestamp, nonce)
    assert message is not None
    message = parse_xml(message)
    assert message is not None
    message = crypt.decrypt_message(
        message['TimeStamp'], message['Nonce'], message['MsgSignature'],
        message['Encrypt']
    )
    assert message == to_binary('hello')
Example #26
0
    def encrypt_message(self, reply, timestamp=None, nonce=None):
        """
        加密微信回复
        :param reply: 加密前的回复
        :type reply: WeChatReply 或 XML 文本
        :return: 加密后的回复文本
        """
        if hasattr(reply, "render"):
            reply = reply.render()

        timestamp = timestamp or to_binary(int(time.time()))
        nonce = nonce or generate_token(5)
        encrypt = to_text(self.prp_crypto.encrypt(reply, self.app_id))
        signature = get_signature(self.token, timestamp, nonce, encrypt)
        return to_text(
            self.ENCRYPTED_MESSAGE_XML.format(encrypt=encrypt,
                                              signature=signature,
                                              timestamp=timestamp,
                                              nonce=nonce))
Example #27
0
    def encrypt_message(self, reply, timestamp=None, nonce=None):
        """
        加密微信回复
        :param reply: 加密前的回复
        :type reply: WeChatReply 或 XML 文本
        :return: 加密后的回复文本
        """
        if hasattr(reply, "render"):
            reply = reply.render()

        timestamp = timestamp or to_binary(int(time.time()))
        nonce = nonce or generate_token(5)
        encrypt = to_text(self.prp_crypto.encrypt(reply, self.app_id))
        signature = get_signature(self.token, timestamp, nonce, encrypt)
        return to_text(self.ENCRYPTED_MESSAGE_XML.format(
            encrypt=encrypt,
            signature=signature,
            timestamp=timestamp,
            nonce=nonce
        ))
Example #28
0
    def decrypt(self, text, app_id):
        """
        对密文进行解密
        :param text: 需要解密的密文
        :param app_id: 微信公众平台的 AppID
        :return: 解密后的字符串
        """
        text = to_binary(text)
        plain_text = self.cipher.decrypt(base64.b64decode(text))

        padding = byte2int(plain_text, -1)
        content = plain_text[16:-padding]

        xml_len = socket.ntohl(struct.unpack("I", content[:4])[0])
        xml_content = content[4:xml_len + 4]
        from_appid = content[xml_len + 4:]

        if to_text(from_appid) != app_id:
            raise AppIdValidationError(text, app_id)

        return xml_content
Example #29
0
    def decrypt(self, text, app_id):
        """
        对密文进行解密
        :param text: 需要解密的密文
        :param app_id: 微信公众平台的 AppID
        :return: 解密后的字符串
        """
        text = to_binary(text)
        plain_text = self.cipher.decrypt(base64.b64decode(text))

        padding = byte2int(plain_text, -1)
        content = plain_text[16:-padding]

        xml_len = socket.ntohl(struct.unpack("I", content[:4])[0])
        xml_content = content[4:xml_len+4]
        from_appid = content[xml_len+4:]

        if to_text(from_appid) != app_id:
            raise AppIdValidationError(text, app_id)

        return xml_content
Example #30
0
    def get_reply(self, message):
        """
        Return the Reply Object for the given message.
        """
        session_storage = self.config["SESSION_STORAGE"]

        id = None
        session = None
        if session_storage and hasattr(message, "source"):
            id = to_binary(message.source)
            session = session_storage[id]

        handlers = self.get_handlers(message.type)
        try:
            for handler, args_count in handlers:
                args = [message, session][:args_count]
                reply = handler(*args)
                if session_storage and id:
                    session_storage[id] = session
                if reply:
                    return process_function_reply(reply, message=message)
        except:
            self.logger.warning("Catch an exception", exc_info=True)
Example #31
0
    def get_reply(self, message):
        """
        Return the Reply Object for the given message.
        """
        session_storage = self.config["SESSION_STORAGE"]

        id = None
        session = None
        if session_storage and hasattr(message, "source"):
            id = to_binary(message.source)
            session = session_storage[id]

        handlers = self.get_handlers(message.type)
        try:
            for handler, args_count in handlers:
                args = [message, session][:args_count]
                reply = handler(*args)
                if session_storage and id:
                    session_storage[id] = session
                if reply:
                    return process_function_reply(reply, message=message)
        except:
            self.logger.warning("Catch an exception", exc_info=True)
Example #32
0
def remove_session(session):
    del session[to_binary("fromUser")]
Example #33
0
def unsubscribe(message):
    logging.info('user %s unsubscribe.' % (message.source,))
    id = to_binary(message.source)
    session_storage = robot.config["SESSION_STORAGE"]
    session_storage.delete(id)
    return ''
Example #34
0
def remove_session(session):
    try:
        del session[to_binary("fromUser")]
    except:
        pass
Example #35
0
File: robot.py Project: A-you/odoo
 def check_signature(self, timestamp, nonce, signature):
     sign = [self.config["TOKEN"], timestamp, nonce]
     sign.sort()
     sign = to_binary(''.join(sign))
     sign = hashlib.sha1(sign).hexdigest()
     return sign == signature
Example #36
0
def unsubscribe(message):
    logging.info('user %s unsubscribe.' % (message.source, ))
    id = to_binary(message.source)
    session_storage = robot.config["SESSION_STORAGE"]
    session_storage.delete(id)
    return ''
Example #37
0
 def check_signature(self, timestamp, nonce, signature):
     sign = [self.config["TOKEN"], timestamp, nonce]
     sign.sort()
     sign = to_binary(''.join(sign))
     sign = hashlib.sha1(sign).hexdigest()
     return sign == signature
Example #38
0
def remove_session(session):
    try:
        del session[to_binary("fromUser")]
    except:
        pass
Example #39
0
 def __init__(self, filename='werobot_session'):
     try:
         self.db = dbm.open(filename, "c")
     except TypeError:  # pragma: no cover
         # dbm in PyPy requires filename to be binary
         self.db = dbm.open(to_binary(filename), "c")
Example #40
0
 def __init__(self, filename: str = 'werobot_session'):
     try:
         self.db = dbm.open(filename, "c")
     except TypeError:  # pragma: no cover
         # dbm in PyPy requires filename to be binary
         self.db = dbm.open(to_binary(filename), "c")
Example #41
0
def test_to_binary():
    assert to_binary(6) == bytes(6)
    assert to_binary(b"aa") == b"aa"
    assert to_binary("cc") == b"cc"
    assert to_binary(u"喵") == b"\xe5\x96\xb5"
    assert to_binary("喵") == b"\xe5\x96\xb5"