String: Apply/unapply base64 encoding when dealing with a binary encoding.

This commit is contained in:
Valentin Lorentz 2012-08-05 17:55:29 +02:00
parent 5ae3e3fdcf
commit a40ebae4da

View File

@ -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:
<http://docs.python.org/library/codecs.html#standard-encodings>.
"""
# 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:
<http://docs.python.org/library/codecs.html#standard-encodings>.
"""
# 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'])