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("喵") == "喵"
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]
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")
def __init__(self, key): key = to_binary(key) self.cipher = Cipher( algorithms.AES(key), modes.CBC(key[:16]), backend=default_backend() )
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)
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)
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
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)
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
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)
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 "大牛列表暂时还拉不到哦"
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
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()
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()
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)
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')
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')
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))
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 ))
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
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
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)
def remove_session(session): del session[to_binary("fromUser")]
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 ''
def remove_session(session): try: del session[to_binary("fromUser")] except: pass
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
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 ''
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")
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")
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"