remove has_key()

fix base64 calls (requires and returns bytes, not str)
This commit is contained in:
Yann Leboulanger 2013-01-02 17:53:42 +01:00
parent 912f0e921d
commit 2c21353a8b
16 changed files with 47 additions and 48 deletions

View File

@ -428,7 +428,7 @@ if dbus_support.supported:
def account_info(self, account): def account_info(self, account):
'''show info on account: resource, jid, nick, prio, message''' '''show info on account: resource, jid, nick, prio, message'''
result = DBUS_DICT_SS() result = DBUS_DICT_SS()
if gajim.connections.has_key(account): if account in gajim.connections:
# account is valid # account is valid
con = gajim.connections[account] con = gajim.connections[account]
index = con.connected index = con.connected

View File

@ -163,7 +163,7 @@ def compute_caps_hash(identities, features, dataforms=[], hash_method='sha-1'):
hash_ = hashlib.md5(S.encode('utf-8')) hash_ = hashlib.md5(S.encode('utf-8'))
else: else:
return '' return ''
return base64.b64encode(hash_.digest()) return base64.b64encode(hash_.digest()).decode('utf-8')
################################################################################ ################################################################################

View File

@ -431,7 +431,8 @@ class ConnectionVcard:
if 'PHOTO' in vcard and isinstance(vcard['PHOTO'], dict) and \ if 'PHOTO' in vcard and isinstance(vcard['PHOTO'], dict) and \
'BINVAL' in vcard['PHOTO']: 'BINVAL' in vcard['PHOTO']:
photo = vcard['PHOTO']['BINVAL'] photo = vcard['PHOTO']['BINVAL']
photo_decoded = base64.decodestring(photo) photo_decoded = base64.b64decode(photo.encode('utf-8')).decode(
'utf-8')
gajim.interface.save_avatar_files(our_jid, photo_decoded) gajim.interface.save_avatar_files(our_jid, photo_decoded)
avatar_sha = hashlib.sha1(photo_decoded).hexdigest() avatar_sha = hashlib.sha1(photo_decoded).hexdigest()
iq2.getTag('PHOTO').setTagData('SHA', avatar_sha) iq2.getTag('PHOTO').setTagData('SHA', avatar_sha)
@ -684,7 +685,7 @@ class ConnectionVcard:
'BINVAL' in vcard['PHOTO']: 'BINVAL' in vcard['PHOTO']:
photo = vcard['PHOTO']['BINVAL'] photo = vcard['PHOTO']['BINVAL']
try: try:
photo_decoded = base64.decodestring(photo) photo_decoded = base64.b64decode(photo.encode('utf-8')).decode('utf-8')
avatar_sha = hashlib.sha1(photo_decoded).hexdigest() avatar_sha = hashlib.sha1(photo_decoded).hexdigest()
except Exception: except Exception:
avatar_sha = '' avatar_sha = ''
@ -970,7 +971,7 @@ class ConnectionHandlersBase:
decmsg = self.gpg.decrypt(encmsg, keyID) decmsg = self.gpg.decrypt(encmsg, keyID)
decmsg = self.connection.Dispatcher.replace_non_character(decmsg) decmsg = self.connection.Dispatcher.replace_non_character(decmsg)
# \x00 chars are not allowed in C (so in GTK) # \x00 chars are not allowed in C (so in GTK)
obj.msgtxt = helpers.decode_string(decmsg.replace('\x00', '')) obj.msgtxt = decmsg.replace('\x00', '')
obj.encrypted = 'xep27' obj.encrypted = 'xep27'
self.gpg_messages_to_decrypt.remove([encmsg, keyID, obj]) self.gpg_messages_to_decrypt.remove([encmsg, keyID, obj])
@ -1095,7 +1096,7 @@ class ConnectionHandlersBase:
jid = gajim.get_jid_without_resource(jid) jid = gajim.get_jid_without_resource(jid)
try: try:
return self.sessions[jid].values() return list(self.sessions[jid].values())
except KeyError: except KeyError:
return [] return []
@ -1157,7 +1158,7 @@ class ConnectionHandlersBase:
received a thread_id yet and returns the session that we last sent a received a thread_id yet and returns the session that we last sent a
message to message to
""" """
sessions = self.sessions[jid].values() sessions = list(self.sessions[jid].values())
# sessions that we haven't received a thread ID in # sessions that we haven't received a thread ID in
idless = [s for s in sessions if not s.received_thread_id] idless = [s for s in sessions if not s.received_thread_id]
@ -1178,7 +1179,7 @@ class ConnectionHandlersBase:
Find an active session that doesn't have a control attached Find an active session that doesn't have a control attached
""" """
try: try:
sessions = self.sessions[jid].values() sessions = list(self.sessions[jid].values())
# filter out everything except the default session type # filter out everything except the default session type
chat_sessions = [s for s in sessions if isinstance(s, chat_sessions = [s for s in sessions if isinstance(s,
@ -1549,9 +1550,8 @@ ConnectionJingle, ConnectionIBBytestream):
iq_obj = obj.stanza.buildReply('result') iq_obj = obj.stanza.buildReply('result')
qp = iq_obj.setQuery() qp = iq_obj.setQuery()
qp.setTagData('utc', strftime('%Y%m%dT%H:%M:%S', gmtime())) qp.setTagData('utc', strftime('%Y%m%dT%H:%M:%S', gmtime()))
qp.setTagData('tz', helpers.decode_string(tzname[daylight])) qp.setTagData('tz', tzname[daylight])
qp.setTagData('display', helpers.decode_string(strftime('%c', qp.setTagData('display', strftime('%c', localtime()))
localtime())))
else: else:
iq_obj = obj.stanza.buildReply('error') iq_obj = obj.stanza.buildReply('error')
err = nbxmpp.ErrorNode(name=nbxmpp.NS_STANZAS + \ err = nbxmpp.ErrorNode(name=nbxmpp.NS_STANZAS + \

View File

@ -64,7 +64,7 @@ class FilesProp:
@classmethod @classmethod
def getAllFileProp(cls): def getAllFileProp(cls):
return cls._files_props.values() return list(cls._files_props.values())
@classmethod @classmethod
def setFileProp(cls, fp, account, sid): def setFileProp(cls, fp, account, sid):

View File

@ -633,8 +633,6 @@ def datetime_tuple(timestamp):
from time import strptime from time import strptime
return strptime(timestamp, '%Y%m%dT%H:%M:%S') return strptime(timestamp, '%Y%m%dT%H:%M:%S')
# import gajim only when needed (after decode_string is defined) see #4764
from common import gajim from common import gajim
if gajim.HAVE_PYCURL: if gajim.HAVE_PYCURL:
import pycurl import pycurl
@ -904,7 +902,7 @@ def get_full_jid_from_iq(iq_obj):
""" """
Return the full jid (with resource) from an iq Return the full jid (with resource) from an iq
""" """
return parse_jid(iq_obj.getFrom()) return parse_jid(str(iq_obj.getFrom()))
def get_jid_from_iq(iq_obj): def get_jid_from_iq(iq_obj):
""" """

View File

@ -852,7 +852,8 @@ class ConnectionIBBytestream(ConnectionBytestream):
chunk = file_props.fp.read(file_props.block_size) chunk = file_props.fp.read(file_props.block_size)
if chunk: if chunk:
datanode = nbxmpp.Node(nbxmpp.NS_IBB + ' data', {'sid': sid, datanode = nbxmpp.Node(nbxmpp.NS_IBB + ' data', {'sid': sid,
'seq': file_props.seq}, base64.encodestring(chunk)) 'seq': file_props.seq}, base64.b64encode(chunk.encode(
'utf-8')).decode('utf-8'))
file_props.seq += 1 file_props.seq += 1
file_props.started = True file_props.started = True
if file_props.seq == 65536: if file_props.seq == 65536:
@ -887,7 +888,7 @@ class ConnectionIBBytestream(ConnectionBytestream):
log.debug('ReceiveHandler called sid->%s seq->%s' % (sid, seq)) log.debug('ReceiveHandler called sid->%s seq->%s' % (sid, seq))
try: try:
seq = int(seq) seq = int(seq)
data = base64.decodestring(data) data = base64.b64decode(data.encode('utf-8')).decode('utf-8')
except Exception: except Exception:
seq = '' seq = ''
data = '' data = ''

View File

@ -70,33 +70,33 @@ class CommonResolver():
# empty host, return empty list of srv records # empty host, return empty list of srv records
on_ready([]) on_ready([])
return return
if self.resolved_hosts.has_key(host+type): if host + type in self.resolved_hosts:
# host is already resolved, return cached values # host is already resolved, return cached values
log.debug('%s already resolved: %s' % (host, log.debug('%s already resolved: %s' % (host,
self.resolved_hosts[host+type])) self.resolved_hosts[host + type]))
on_ready(host, self.resolved_hosts[host+type]) on_ready(host, self.resolved_hosts[host + type])
return return
if self.handlers.has_key(host+type): if host + type in self.handlers:
# host is about to be resolved by another connection, # host is about to be resolved by another connection,
# attach our callback # attach our callback
log.debug('already resolving %s' % host) log.debug('already resolving %s' % host)
self.handlers[host+type].append(on_ready) self.handlers[host + type].append(on_ready)
else: else:
# host has never been resolved, start now # host has never been resolved, start now
log.debug('Starting to resolve %s using %s' % (host, self)) log.debug('Starting to resolve %s using %s' % (host, self))
self.handlers[host+type] = [on_ready] self.handlers[host + type] = [on_ready]
self.start_resolve(host, type) self.start_resolve(host, type)
def _on_ready(self, host, type, result_list): def _on_ready(self, host, type, result_list):
# practically it is impossible to be the opposite, but who knows :) # practically it is impossible to be the opposite, but who knows :)
host = host.lower() host = host.lower()
log.debug('Resolving result for %s: %s' % (host, result_list)) log.debug('Resolving result for %s: %s' % (host, result_list))
if not self.resolved_hosts.has_key(host+type): if host + type not in self.resolved_hosts:
self.resolved_hosts[host+type] = result_list self.resolved_hosts[host + type] = result_list
if self.handlers.has_key(host+type): if host + type in self.handlers:
for callback in self.handlers[host+type]: for callback in self.handlers[host + type]:
callback(host, result_list) callback(host, result_list)
del(self.handlers[host+type]) del(self.handlers[host + type])
def start_resolve(self, host, type): def start_resolve(self, host, type):
pass pass
@ -251,8 +251,7 @@ class NSLookupResolver(CommonResolver):
domain = None domain = None
if line.startswith(fqdn): if line.startswith(fqdn):
domain = fqdn # For nslookup 9.5 domain = fqdn # For nslookup 9.5
elif helpers.decode_string(line).startswith(ufqdn): elif line.startswith(ufqdn):
line = helpers.decode_string(line)
domain = ufqdn # For nslookup 9.6 domain = ufqdn # For nslookup 9.6
if domain: if domain:
rest = line[len(domain):].split('=') rest = line[len(domain):].split('=')

View File

@ -173,7 +173,7 @@ class P2PClient(IdleObject):
id_ = stanza.getID() id_ = stanza.getID()
if not id_: if not id_:
id_ = self.Dispatcher.getAnID() id_ = self.Dispatcher.getAnID()
if self.conn_holder.ids_of_awaiting_messages.has_key(self.fd): if self.fd in self.conn_holder.ids_of_awaiting_messages:
self.conn_holder.ids_of_awaiting_messages[self.fd].append(( self.conn_holder.ids_of_awaiting_messages[self.fd].append((
id_, thread_id)) id_, thread_id))
else: else:
@ -195,7 +195,7 @@ class P2PClient(IdleObject):
id_ = stanza.getID() id_ = stanza.getID()
if not id_: if not id_:
id_ = self.Dispatcher.getAnID() id_ = self.Dispatcher.getAnID()
if self.conn_holder.ids_of_awaiting_messages.has_key(self.fd): if self.fd in self.conn_holder.ids_of_awaiting_messages:
self.conn_holder.ids_of_awaiting_messages[self.fd].append((id_, self.conn_holder.ids_of_awaiting_messages[self.fd].append((id_,
thread_id)) thread_id))
else: else:
@ -253,10 +253,10 @@ class P2PClient(IdleObject):
'Incorrect answer from server.') 'Incorrect answer from server.')
return return
if self.sock_type == TYPE_SERVER: if self.sock_type == TYPE_SERVER:
if attrs.has_key('from'): if 'from' in attrs:
self.to = attrs['from'] self.to = attrs['from']
self.send_stream_header() self.send_stream_header()
if attrs.has_key('version') and attrs['version'] == '1.0': if 'version' in attrs and attrs['version'] == '1.0':
# other part supports stream features # other part supports stream features
features = Node('stream:features') features = Node('stream:features')
self.Dispatcher.send(features) self.Dispatcher.send(features)
@ -270,12 +270,12 @@ class P2PClient(IdleObject):
def on_disconnect(self): def on_disconnect(self):
if self.conn_holder: if self.conn_holder:
if self.conn_holder.ids_of_awaiting_messages.has_key(self.fd): if self.fd in self.conn_holder.ids_of_awaiting_messages:
del self.conn_holder.ids_of_awaiting_messages[self.fd] del self.conn_holder.ids_of_awaiting_messages[self.fd]
self.conn_holder.remove_connection(self.sock_hash) self.conn_holder.remove_connection(self.sock_hash)
if self.__dict__.has_key('Dispatcher'): if 'Dispatcher' in self.__dict__:
self.Dispatcher.PlugOut() self.Dispatcher.PlugOut()
if self.__dict__.has_key('P2PConnection'): if 'P2PConnection' in self.__dict__:
self.P2PConnection.PlugOut() self.P2PConnection.PlugOut()
self.Connection = None self.Connection = None
self._caller = None self._caller = None
@ -294,7 +294,7 @@ class P2PClient(IdleObject):
self.Dispatcher.Stream._document_attrs is None: self.Dispatcher.Stream._document_attrs is None:
return return
self.onreceive(None) self.onreceive(None)
if self.Dispatcher.Stream._document_attrs.has_key('version') and \ if 'version' in self.Dispatcher.Stream._document_attrs and \
self.Dispatcher.Stream._document_attrs['version'] == '1.0': self.Dispatcher.Stream._document_attrs['version'] == '1.0':
#~ self.onreceive(self._on_receive_stream_features) #~ self.onreceive(self._on_receive_stream_features)
#XXX continue with TLS #XXX continue with TLS
@ -710,7 +710,7 @@ class ClientZeroconf:
if self.ip_to_hash[i] == sock_hash: if self.ip_to_hash[i] == sock_hash:
del self.ip_to_hash[i] del self.ip_to_hash[i]
break break
if self.hash_to_port.has_key(sock_hash): if sock_hash in self.hash_to_port:
del self.hash_to_port[sock_hash] del self.hash_to_port[sock_hash]
def start_listener(self, port): def start_listener(self, port):

View File

@ -566,7 +566,8 @@ class SingleForm(Gtk.Table, object):
for uri in field.media.uris: for uri in field.media.uris:
if uri.type_.startswith('image/'): if uri.type_.startswith('image/'):
try: try:
img_data = base64.decodestring(uri.uri_data) img_data = base64.b64decode(uri.uri_data.encode(
'utf-8')).decode('utf-8')
pixbuf_l = GdkPixbuf.PixbufLoader() pixbuf_l = GdkPixbuf.PixbufLoader()
pixbuf_l.write(img_data) pixbuf_l.write(img_data)
pixbuf_l.close() pixbuf_l.close()

View File

@ -193,7 +193,6 @@ class CacheDictionary:
def __contains__(self, key): def __contains__(self, key):
return key in self.cache return key in self.cache
has_key = __contains__
_icon_cache = CacheDictionary(15) _icon_cache = CacheDictionary(15)

View File

@ -42,7 +42,7 @@ except Exception:
def send_error(error_message): def send_error(error_message):
'''Writes error message to stderr and exits''' '''Writes error message to stderr and exits'''
print(error_message.encode(PREFERRED_ENCODING), file=sys.stderr) print(error_message, file=sys.stderr)
sys.exit(1) sys.exit(1)
try: try:

View File

@ -122,7 +122,7 @@ def build_invite_submenu(invite_menuitem, list_, ignore_rooms=[]):
minimized_controls = [] minimized_controls = []
for account in connected_accounts: for account in connected_accounts:
minimized_controls += \ minimized_controls += \
gajim.interface.minimized_controls[account].values() list(gajim.interface.minimized_controls[account].values())
for gc_control in gajim.interface.msg_win_mgr.get_controls( for gc_control in gajim.interface.msg_win_mgr.get_controls(
message_control.TYPE_GC) + minimized_controls: message_control.TYPE_GC) + minimized_controls:
acct = gc_control.account acct = gc_control.account

View File

@ -171,7 +171,8 @@ class ProfileWindow:
button.show() button.show()
text_button = self.xml.get_object('NOPHOTO_button') text_button = self.xml.get_object('NOPHOTO_button')
text_button.hide() text_button.hide()
self.avatar_encoded = base64.encodestring(data) self.avatar_encoded = base64.b64encode(data.encode('utf-8')).decode(
'utf-8')
# returns None if unknown type # returns None if unknown type
self.avatar_mime_type = mimetypes.guess_type(path_to_file)[0] self.avatar_mime_type = mimetypes.guess_type(path_to_file)[0]
if must_delete: if must_delete:

View File

@ -907,7 +907,7 @@ class SignalObject(dbus.service.Object):
if not invalid_file and filesize < 16384: if not invalid_file and filesize < 16384:
fd = open(picture, 'rb') fd = open(picture, 'rb')
data = fd.read() data = fd.read()
avatar = base64.encodestring(data) avatar = base64.b64encode(data.encode('utf-8')).decode('utf-8')
avatar_mime_type = mimetypes.guess_type(picture)[0] avatar_mime_type = mimetypes.guess_type(picture)[0]
vcard={} vcard={}
vcard['PHOTO'] = {'BINVAL': avatar} vcard['PHOTO'] = {'BINVAL': avatar}

View File

@ -2186,7 +2186,7 @@ class RosterWindow:
gajim.interface.status_sent_to_groups[account] = {} gajim.interface.status_sent_to_groups[account] = {}
for gc_control in gajim.interface.msg_win_mgr.get_controls( for gc_control in gajim.interface.msg_win_mgr.get_controls(
message_control.TYPE_GC) + \ message_control.TYPE_GC) + \
gajim.interface.minimized_controls[account].values(): list(gajim.interface.minimized_controls[account].values()):
if gc_control.account == account: if gc_control.account == account:
if gajim.gc_connected[account][gc_control.room_jid]: if gajim.gc_connected[account][gc_control.room_jid]:
gajim.connections[account].send_gc_status( gajim.connections[account].send_gc_status(
@ -3923,7 +3923,7 @@ class RosterWindow:
) )
def on_plugins_menuitem_activate(self, widget): def on_plugins_menuitem_activate(self, widget):
if gajim.interface.instances.has_key('plugins'): if 'plugins' in gajim.interface.instances:
gajim.interface.instances['plugins'].window.present() gajim.interface.instances['plugins'].window.present()
else: else:
gajim.interface.instances['plugins'] = plugins.gui.PluginsWindow() gajim.interface.instances['plugins'] = plugins.gui.PluginsWindow()

View File

@ -61,7 +61,7 @@ def get_avatar_pixbuf_encoded_mime(photo):
img_encoded = photo['BINVAL'] img_encoded = photo['BINVAL']
avatar_encoded = img_encoded avatar_encoded = img_encoded
try: try:
img_decoded = base64.decodestring(img_encoded) img_decoded = base64.b64decode(img_encoded.encode('utf-8')).decode('utf-8')
except Exception: except Exception:
pass pass
if img_decoded: if img_decoded: