From a40ebae4da3cce0e05e77aedf86ca8b051e5b709 Mon Sep 17 00:00:00 2001 From: Valentin Lorentz Date: Sun, 5 Aug 2012 17:55:29 +0200 Subject: [PATCH] String: Apply/unapply base64 encoding when dealing with a binary encoding. --- plugins/String/plugin.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/plugins/String/plugin.py b/plugins/String/plugin.py index f065a5abe..1a53d2666 100644 --- a/plugins/String/plugin.py +++ b/plugins/String/plugin.py @@ -31,6 +31,7 @@ import sys import types import codecs +import base64 import binascii import supybot.utils as utils @@ -74,17 +75,30 @@ class String(callbacks.Plugin): available in the documentation of the Python codecs module: . """ + # Binary codecs are prefixed with _codec in Python 3 if encoding in 'base64 bz2 hex quopri uu zlib': encoding += '_codec' + if encoding.endswith('_codec'): + text = text.encode() + + # Do the encoding try: encoder = codecs.getencoder(encoding) except LookupError: irc.errorInvalid(_('encoding'), encoding) text = encoder(text)[0] + + # If this is a binary codec, re-encode it with base64 + if encoding.endswith('_codec') and encoding != 'base64_codec': + text = codecs.getencoder('base64_codec')(text)[0].decode() + + # Change result into a string if sys.version_info[0] < 3 and isinstance(text, unicode): text = text.encode('utf-8') elif sys.version_info[0] >= 3 and isinstance(text, bytes): text = text.decode() + + # Reply irc.reply(text.rstrip('\n')) encode = wrap(encode, ['something', 'text']) @@ -96,13 +110,20 @@ class String(callbacks.Plugin): available in the documentation of the Python codecs module: . """ + # Binary codecs are prefixed with _codec in Python 3 if encoding in 'base64 bz2 hex quopri uu zlib': encoding += '_codec' + + # If this is a binary codec, pre-decode it with base64 + if encoding.endswith('_codec') and encoding != 'base64_codec': + text = codecs.getdecoder('base64_codec')(text.encode())[0] + + # Do the decoding try: decoder = codecs.getdecoder(encoding) except LookupError: irc.errorInvalid(_('encoding'), encoding) - if sys.version_info[0] >= 3: + if sys.version_info[0] >= 3 and not isinstance(text, bytes): text = text.encode() try: text = decoder(text)[0] @@ -111,10 +132,14 @@ class String(callbacks.Plugin): s=_('Base64 strings must be a multiple of 4 in ' 'length, padded with \'=\' if necessary.')) return + + # Change result into a string if sys.version_info[0] < 3 and isinstance(text, unicode): text = text.encode('utf-8') elif sys.version_info[0] >= 3 and isinstance(text, bytes): text = text.decode() + + # Reply irc.reply(text) decode = wrap(decode, ['something', 'text'])