diff --git a/src/apps/admin/bongo-admin.py b/src/apps/admin/bongo-admin.py index 0dc7b4c..ebde4b1 100755 --- a/src/apps/admin/bongo-admin.py +++ b/src/apps/admin/bongo-admin.py @@ -58,7 +58,7 @@ if __name__ == '__main__': try: options.authpass = getpass.getpass(_("Enter password for %s: ") % options.authuser) except KeyboardInterrupt: - print + print() sys.exit(1) log.debug("running command: %s", str(command)) @@ -75,14 +75,14 @@ if __name__ == '__main__': try: ret = command.run(options, args) except KeyboardInterrupt: - print + print() sys.exit(1) except SystemExit: raise - except Exception, e: + except Exception as e: log.debug("Error at bongo-admintool main()", exc_info=1) ret = 1 - print _("ERROR: %s") % str(e) + print(_("ERROR: %s") % str(e)) if ret is None: sys.exit(0) diff --git a/src/apps/admin/bongo/admintool/AgentCommands.py b/src/apps/admin/bongo/admintool/AgentCommands.py index 5ee865b..d87301a 100644 --- a/src/apps/admin/bongo/admintool/AgentCommands.py +++ b/src/apps/admin/bongo/admintool/AgentCommands.py @@ -15,8 +15,8 @@ from libbongo.bootstrap import msgapi from bongo.Console import wrap from bongo.MDB import MDB, MDBError -import CmdUtil -import MdbUtil +from . import CmdUtil +from . import MdbUtil class AgentDelete(Command): log = logging.getLogger("bongo.admintool") @@ -36,10 +36,10 @@ class AgentDelete(Command): for agent in args: try: Util.RemoveBongoAgent(mdb, options.server, agent) - print _("Removed agent: %s") % agent - except MDBError, e: + print(_("Removed agent: %s") % agent) + except MDBError as e: self.log.debug("Error removing agent %s", agent, exc_info=1) - print _("Error removing %s: %s") % (agent, str(e)) + print(_("Error removing %s: %s") % (agent, str(e))) class AgentInfo(Command): log = logging.getLogger("bongo.admintool") @@ -56,20 +56,20 @@ class AgentInfo(Command): mdb = MdbUtil.GetMdb(options) - print "[%s]" % options.server + print("[%s]" % options.server) for agent in args: dn = options.server + "\\" + agent attrs = Util.GetAgentAttributes(mdb, dn) - keys = attrs.keys() + keys = list(attrs.keys()) keys.sort(lambda x,y: cmp(Util.PropertiesPrintable.get(x), Util.PropertiesPrintable.get(y))) for k in keys: - print " |->(%s)" % Util.PropertiesPrintable[k] + print(" |->(%s)" % Util.PropertiesPrintable[k]) for val in attrs[k]: - print " | |->\"%s\"" % val + print(" | |->\"%s\"" % val) class AgentList(Command): log = logging.getLogger("bongo.admintool") @@ -84,10 +84,10 @@ class AgentList(Command): for server in Util.ListBongoMessagingServers(mdb): agents = Util.ListBongoAgents(mdb, server) - print 'Installed agents:' - print '[%s]' % server + print('Installed agents:') + print('[%s]' % server) for agent in agents: - print ' |->[%s]' % agent + print(' |->[%s]' % agent) class AgentModify(Command): log = logging.getLogger("bongo.admintool") @@ -107,11 +107,11 @@ class AgentModify(Command): agentArgs = CmdUtil.GetAgentArgs() seenArgs = {} - for agent, args in agentArgs.items(): + for agent, args in list(agentArgs.items()): group = optparse.OptionGroup(self, self.get_pretty_agent(agent)) for arg, desc in args: - if seenArgs.has_key(arg): + if arg in seenArgs: # you can only add_option a long opt once continue @@ -140,8 +140,8 @@ class AgentModify(Command): mdb = MdbUtil.GetMdb(options) props = {} - for key, value in options.attributes.items(): + for key, value in list(options.attributes.items()): props[Util.Properties[key]] = value Util.ModifyBongoAgent(mdb, options.server, agent, props) - print "%s modified" % agent + print("%s modified" % agent) diff --git a/src/apps/admin/bongo/admintool/CmdUtil.py b/src/apps/admin/bongo/admintool/CmdUtil.py index 36fc242..cbe23f9 100644 --- a/src/apps/admin/bongo/admintool/CmdUtil.py +++ b/src/apps/admin/bongo/admintool/CmdUtil.py @@ -39,7 +39,7 @@ def GetAgentArgs(): agentAttrs = GetAttributeArgs(agent) for arg in agentAttrs: - if not commonCache.has_key(arg[0]): + if arg[0] not in commonCache: attrs.setdefault(agent, []).append(arg) return attrs diff --git a/src/apps/admin/bongo/admintool/DemoCommands.py b/src/apps/admin/bongo/admintool/DemoCommands.py index 5cfa5e8..e80bac2 100644 --- a/src/apps/admin/bongo/admintool/DemoCommands.py +++ b/src/apps/admin/bongo/admintool/DemoCommands.py @@ -5,8 +5,8 @@ import os import re import time import random -import md5 -import urllib +import hashlib +import urllib.request, urllib.parse, urllib.error import email from email.MIMEText import MIMEText @@ -25,7 +25,7 @@ from bongo import MDB, Xpl from bongo.admin import Util -import MdbUtil +from . import MdbUtil if os.path.isfile("demo/contacts/list.vcf") : demopath = "demo" @@ -63,7 +63,7 @@ class DemoCommand(Command): help="demo user to create [default %default]") def AddUser(self, mdb, context, user, address) : - print "adding user %s to %s with password 'bongo'" % (user, context) + print("adding user %s to %s with password 'bongo'" % (user, context)) attributes = {} attributes[mdb.A_GIVEN_NAME] = ["Rupert"] attributes[mdb.A_SURNAME] = ["Monkey"] @@ -77,8 +77,8 @@ class DemoCommand(Command): for filename in dir : if filename[0] == '.' : continue - print "importing %s" % (filename) - f = file ("%s/mail/%s" % (demopath, filename)) + print("importing %s" % (filename)) + f = open("%s/mail/%s" % (demopath, filename)) data = f.read() f.close() data = data.replace("@ADDRESS@", address) @@ -87,7 +87,7 @@ class DemoCommand(Command): uid = store.Write("/mail/INBOX", DocTypes.Mail, email.Utils.fix_eols(data)) if filename in demo["starMail"] : conversation = store.PropGet(uid, "nmap.mail.conversation") - print "starring conversation %s" % (conversation) + print("starring conversation %s" % (conversation)) store.Flag(uid, DocFlags.Starred, FlagMode.Add) store.Flag(conversation, DocFlags.Starred, FlagMode.Add) @@ -108,7 +108,7 @@ class DemoCommand(Command): if filename[0] == '.' : continue - print "importing %s" % (filename) + print("importing %s" % (filename)) f = open("%s/contacts/%s" % (demopath, filename), 'r') for v in vobject.readComponents(f): c = Contact(v) @@ -129,13 +129,13 @@ class DemoCommand(Command): if filename[0] == '.' : continue - path = urllib.quote(os.path.abspath(dirname + "/" + filename)) + path = urllib.parse.quote(os.path.abspath(dirname + "/" + filename)) - print "importing %s" % (filename) + print("importing %s" % (filename)) calname = os.path.basename(filename) calname = os.path.splitext(filename)[0] - calname = urllib.unquote(calname) + calname = urllib.parse.unquote(calname) msgapi.IcsImport(storename, calname, None, "file://" + path, None, None) @@ -156,14 +156,14 @@ class DemoCommand(Command): try: Util.GetUserAttributes(mdb, context, user) - print "using existing user %s" % (user) + print("using existing user %s" % (user)) except : - print "adding user %s" % (user) + print("adding user %s" % (user)) self.AddUser(mdb, context, user, address) dragonfly = { "calendar": defaultData["calendarPreferences"] } dragonfly["mail"] = { "from": address } - print "dragonfly config is: %s" % simplejson.dumps(dragonfly) + print("dragonfly config is: %s" % simplejson.dumps(dragonfly)) try : store = StoreClient(user, user) diff --git a/src/apps/admin/bongo/admintool/ServerCommands.py b/src/apps/admin/bongo/admintool/ServerCommands.py index d81448e..1308976 100644 --- a/src/apps/admin/bongo/admintool/ServerCommands.py +++ b/src/apps/admin/bongo/admintool/ServerCommands.py @@ -14,7 +14,7 @@ from bongo.admin import Schema, Util from libbongo.bootstrap import msgapi from bongo.Console import wrap -import MdbUtil +from . import MdbUtil class ServerInfo(Command): log = logging.getLogger("bongo.admintool") @@ -32,19 +32,19 @@ class ServerInfo(Command): else: servers = args - print 'Installed servers:' + print('Installed servers:') for server in servers: - print '[%s]' % server + print('[%s]' % server) attrs = Util.GetServerAttributes(mdb, server) - keys = attrs.keys() + keys = list(attrs.keys()) keys.sort(lambda x,y: cmp(Util.PropertiesPrintable.get(x), Util.PropertiesPrintable.get(y))) for key in keys: - print " |->(%s)" % Util.PropertiesPrintable[key] + print(" |->(%s)" % Util.PropertiesPrintable[key]) for val in attrs[key]: - print " | |->\"%s\"" % val + print(" | |->\"%s\"" % val) class ServerList(Command): log = logging.getLogger("bongo.admintool") @@ -59,6 +59,6 @@ class ServerList(Command): servers = Util.ListBongoMessagingServers(mdb) - print 'Installed servers:' + print('Installed servers:') for server in servers: - print '[%s]' % server + print('[%s]' % server) diff --git a/src/apps/admin/bongo/admintool/SetupCommands.py b/src/apps/admin/bongo/admintool/SetupCommands.py index 08e9c56..7a41383 100644 --- a/src/apps/admin/bongo/admintool/SetupCommands.py +++ b/src/apps/admin/bongo/admintool/SetupCommands.py @@ -14,7 +14,7 @@ from libbongo.bootstrap import msgapi from bongo.Console import wrap from bongo.MDB import MDB -import MdbUtil +from . import MdbUtil class ImportCommand(Command): log = logging.getLogger("bongo.admintool") @@ -68,7 +68,7 @@ class SetupGenSchemaCommand(Command): "edir" : Schema.GenerateEdir, "openldap" : Schema.GenerateSlapd} - if dirs.has_key(target): + if target in dirs: self.log.info("generating schema") if options.output_file is not None: @@ -117,7 +117,7 @@ class SetupCredentialCommand(Command): passwd = Util.GeneratePassword(32) credential = Util.GeneratePassword(4096) - omask = os.umask(0077) + omask = os.umask(0o077) eclients = os.path.join(Xpl.DEFAULT_DBF_DIR, "eclients.dat") credfile = os.path.join(Xpl.DEFAULT_DBF_DIR, "credential.dat") diff --git a/src/apps/admin/bongo/admintool/UserCommands.py b/src/apps/admin/bongo/admintool/UserCommands.py index 3d73e90..5365d06 100644 --- a/src/apps/admin/bongo/admintool/UserCommands.py +++ b/src/apps/admin/bongo/admintool/UserCommands.py @@ -15,8 +15,8 @@ from libbongo.bootstrap import msgapi from bongo.Console import wrap from bongo.MDB import MDB, MDBError -import CmdUtil -import MdbUtil +from . import CmdUtil +from . import MdbUtil class UserAdd(Command): log = logging.getLogger("bongo.admintool") @@ -58,14 +58,14 @@ class UserAdd(Command): # set attributes from cmdline options props = {} - for key, value in options.attributes.items(): + for key, value in list(options.attributes.items()): props[Util.Properties[key]] = value try: Util.AddBongoUser(mdb, context, username, props, options.userpass) - print _("Added user: %s") % user - except MDBError, e: - print _("Error adding %s: %s") % (user, str(e)) + print(_("Added user: %s") % user) + except MDBError as e: + print(_("Error adding %s: %s") % (user, str(e))) class UserDelete(Command): log = logging.getLogger("bongo.admintool") @@ -85,9 +85,9 @@ class UserDelete(Command): context, username = MdbUtil.GetContext(user) try: Util.RemoveBongoUser(mdb, context, username) - print _("Removed user: %s") % user - except MDBError, e: - print _("Error removing %s: %s") % (user, str(e)) + print(_("Removed user: %s") % user) + except MDBError as e: + print(_("Error removing %s: %s") % (user, str(e))) class UserInfo(Command): log = logging.getLogger("bongo.admintool") @@ -106,18 +106,18 @@ class UserInfo(Command): for user in args: context, username = MdbUtil.GetContext(user) - print "[%s]" % username + print("[%s]" % username) attrs = Util.GetUserAttributes(mdb, context, username) - keys = attrs.keys() + keys = list(attrs.keys()) keys.sort(lambda x,y: cmp(Util.PropertiesPrintable.get(x), Util.PropertiesPrintable.get(y))) for k in keys: - print " |->(%s)" % Util.PropertiesPrintable[k] + print(" |->(%s)" % Util.PropertiesPrintable[k]) for val in attrs[k]: - print " |->\"%s\"" % val + print(" |->\"%s\"" % val) class UserList(Command): log = logging.getLogger("bongo.admintool") @@ -131,9 +131,9 @@ class UserList(Command): mdb = MdbUtil.GetMdb(options) context = msgapi.GetConfigProperty(msgapi.DEFAULT_CONTEXT) - print '[%s]' % context + print('[%s]' % context) for user in Util.ListBongoUsers(mdb, context): - print ' |->[%s]' % user + print(' |->[%s]' % user) class UserModify(Command): log = logging.getLogger("bongo.admintool") @@ -170,11 +170,11 @@ class UserModify(Command): mdb.GetObjectDetails(context + "\\" + username) props = {} - for key, value in options.attributes.items(): + for key, value in list(options.attributes.items()): props[Util.Properties[key]] = value Util.ModifyBongoUser(mdb, context, username, props) - print "%s modified" % username + print("%s modified" % username) class UserPasswd(Command): log = logging.getLogger("bongo.admintool") @@ -193,7 +193,7 @@ class UserPasswd(Command): if len(args) == 1: user = args[0] - print _("Changing password for %s.") % user + print(_("Changing password for %s.") % user) passwd1 = getpass.getpass(_("New Password: ")) passwd2 = getpass.getpass(_("Reenter New Password: ")) @@ -207,4 +207,4 @@ class UserPasswd(Command): mdb = MdbUtil.GetMdb(options) context, username = MdbUtil.GetContext(user) mdb.SetPassword("\\".join((context, username)), passwd) - print _("Password changed.") + print(_("Password changed.")) diff --git a/src/apps/storetool/bongo/storetool/BackupCommands.py b/src/apps/storetool/bongo/storetool/BackupCommands.py index d70869b..8bf38ff 100644 --- a/src/apps/storetool/bongo/storetool/BackupCommands.py +++ b/src/apps/storetool/bongo/storetool/BackupCommands.py @@ -29,7 +29,7 @@ class PAXHeader: header.type = "x" content = "" - for key in self.keywords.keys(): + for key in list(self.keywords.keys()): if self.keywords[key] != None: content += "%d %s=%s\n" % (len(key) + len(self.keywords[key]) + 5, key, self.keywords[key]) header.size = len(content) @@ -70,8 +70,8 @@ class StoreBackupCommand(Command): try: backup_file = open("%s.backup" % self.store, "wb") - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) return collection_list = ['/'] @@ -82,14 +82,14 @@ class StoreBackupCommand(Command): tar_head.SetKey("BONGO.type", "%d" % collection.type) tar_head.SetKey("BONGO.flags", "%d" % collection.flags) props = docstore.PropGet(collection.uid) - for key in props.keys(): + for key in list(props.keys()): tar_head.SetKey("BONGO.%s" % key, props[key]) backup_file.write(tar_head.ToString()) tar_dir = tarfile.TarInfo(collection.name) tar_dir.size = 0 tar_dir.type = tarfile.DIRTYPE - tar_dir.mode = 0755 + tar_dir.mode = 0o755 backup_file.write(tar_dir.tobuf()) collection_list.append(collection.name) @@ -109,8 +109,8 @@ class StoreBackupCommand(Command): try: content = docstore.Read(document.filename) - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) continue # write out meta data associated with document in a PAX extended header @@ -120,7 +120,7 @@ class StoreBackupCommand(Command): headerx.SetKey("BONGO.type", "%d" % document.type) headerx.SetKey("BONGO.flags", "%d" % document.flags) props = docstore.PropGet(document.uid) - for key in props.keys(): + for key in list(props.keys()): value = props[key] if value != None: headerx.SetKey("BONGO.%s" % key, value.encode("utf-8")) @@ -132,7 +132,7 @@ class StoreBackupCommand(Command): # content is padded to a multiple of 512 bytes tar_info = tarfile.TarInfo(document.filename) tar_info.size = len(content) - tar_info.mode = 0644 + tar_info.mode = 0o644 tar_info.mtime = int(document.created) backup_file.write(tar_info.tobuf()) backup_file.write(content) @@ -182,7 +182,7 @@ class StoreRestoreCommand(Command): return if extheader.type != "x": - print "No metadata header found (%s)" % extheader.name + print("No metadata header found (%s)" % extheader.name) continue metadata = PAXHeader(None) @@ -228,13 +228,13 @@ class StoreRestoreCommand(Command): del metadata["BONGO.flags"] if "BONGO.imapuid" in metadata: del metadata["BONGO.imapuid"] - for key, value in metadata.items(): + for key, value in list(metadata.items()): if key[0:6] == "BONGO.": prop = key[6:] try: store.PropSet(guid, prop, value) except: - print "Failed to set property %s to %s on %s" % (prop, value, guid) + print("Failed to set property %s to %s on %s" % (prop, value, guid)) def RestoreFile(self, store, name, content, metadata): dir_sep = name.rfind("/") @@ -256,14 +256,14 @@ class StoreRestoreCommand(Command): try: new_guid = store.Write(collection, file_type, content, filename=filename, guid=file_guid, noProcess=True) except: - print "Failed to restore %s/%s" % (collection, filename) + print("Failed to restore %s/%s" % (collection, filename)) return if "BONGO.flags" in metadata: try: store.Flag(new_guid, flags=int(metadata["BONGO.flags"])) del metadata["BONGO.flags"] except: - print "Couldn't restore mail flag on %s/%s" % (collection, filename) + print("Couldn't restore mail flag on %s/%s" % (collection, filename)) self.RestoreProps(store, new_guid, metadata) def RestoreCollection(self, store, name, metadata): @@ -275,7 +275,7 @@ class StoreRestoreCommand(Command): else: store.Create(collection) except: - print "Failed to create collection %s" % collection + print("Failed to create collection %s" % collection) self.RestoreProps(store, collection, metadata) def ClearStore(self, store): @@ -302,8 +302,8 @@ class StoreRestoreCommand(Command): store.Store(options.store) self.ClearStore(store) self.RestoreStore(store, f) - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) if f: f.close() store.Quit() diff --git a/src/apps/storetool/bongo/storetool/CalendarCommands.py b/src/apps/storetool/bongo/storetool/CalendarCommands.py index 90f0223..871c240 100644 --- a/src/apps/storetool/bongo/storetool/CalendarCommands.py +++ b/src/apps/storetool/bongo/storetool/CalendarCommands.py @@ -5,7 +5,7 @@ import os import re import time import random -import md5 +import hashlib import email from email.MIMEText import MIMEText @@ -38,13 +38,13 @@ class CalendarsCommand(Command): try: cals = list(store.List("/calendars", props=["bongo.calendar.url"])) for cal in cals: - subd = cal.props.has_key("bongo.calendar.url") and "Yes" or None + subd = "bongo.calendar.url" in cal.props and "Yes" or None rows.append([subd, cal.filename, cal.props.get("bongo.calendar.url")]) finally: store.Quit() - print table.format_table(cols, rows) + print(table.format_table(cols, rows)) class CalendarEventsCommand(Command): log = logging.getLogger("Bongo.StoreTool") @@ -69,7 +69,7 @@ class CalendarEventsCommand(Command): try: cal = self._FindCalendar(store, args[0]) if cal is None: - print "Could not find calendar named '%s'" % args[0] + print("Could not find calendar named '%s'" % args[0]) return events = list(store.Events(cal.uid, ["nmap.document", @@ -96,7 +96,7 @@ class CalendarEventsCommand(Command): store.Quit() rows.sort() - print table.format_table(cols, rows) + print(table.format_table(cols, rows)) class EventsDeleteCommand(Command): log = logging.getLogger("Bongo.StoreTool") @@ -117,7 +117,7 @@ class EventsDeleteCommand(Command): for cal in cals: if cal == "": continue - print "unlinking event", event.uid + print("unlinking event", event.uid) store.Unlink(cal, event.uid) store.Delete(event.uid) finally: @@ -139,7 +139,7 @@ class EventsCleanupCommand(Command): for event in events: cals = store.PropGet(event.uid, "nmap.event.calendars") if cals is None or cals == "": - print "deleting event", event.uid + print("deleting event", event.uid) store.Delete(event.uid) finally: store.Quit() @@ -170,14 +170,14 @@ class CalendarDeleteCommand(Command): for calname in args: cal = self._FindCalendar(store, calname) if cal is None: - print "Could not find calendar named '%s'" % calname + print("Could not find calendar named '%s'" % calname) continue if calname.lower() != "personal": - print "deleting calendar", cal.uid + print("deleting calendar", cal.uid) store.Delete(cal.uid) else: - print "events deleted. not deleting calendar", calname + print("events deleted. not deleting calendar", calname) finally: store.Quit() @@ -196,7 +196,7 @@ class CalendarSubscribeCommand(Command): (name, url) = args uid = msgapi.IcsSubscribe(options.store, name, None, url, None, None) - print "Subscribed: uid is", hex(uid) + print("Subscribed: uid is", hex(uid)) class CalendarImportCommand(Command): log = logging.getLogger("Bongo.StoreTool") @@ -224,7 +224,7 @@ class CalendarImportCommand(Command): url = "file://" + file uid = msgapi.IcsImport(options.store, name, None, url, None, None) - print "Imported: uid is", hex(uid) + print("Imported: uid is", hex(uid)) class CalendarPublishCommand(Command): log = logging.getLogger("Bongo.StoreTool") @@ -272,7 +272,7 @@ class CalendarUnpublishCommand(Command): acl = CalendarACL(store.GetACL(doc)) acl.SetPublic(0) store.SetACL(doc, acl.GetACL()) - print "current acl: %s" % (str(acl)) + print("current acl: %s" % (str(acl))) finally: store.Quit() @@ -316,8 +316,8 @@ class CalendarShareCommand(Command): msg.attach(MIMEText(simplejson.dumps(invitation), "x-bongo-invitation")) - print "sending:" - print msg.as_string() + print("sending:") + print(msg.as_string()) self._SendMessage(options, address, msg) def Run(self, options, args): @@ -338,7 +338,7 @@ class CalendarShareCommand(Command): self._SendInvitation(options, address, info.uid, args[0], token, "read,write") - print "Shared with %s, token is %s" % (address, token) + print("Shared with %s, token is %s" % (address, token)) store.SetACL(doc, acl.GetACL()) finally: store.Quit() @@ -373,12 +373,12 @@ class CalendarAcceptShareCommand(Command): store.PropSet(docpath, "bongo.calendar.uid", cal["bongo.calendar.invitation-uid"]) store.PropSet(docpath, "bongo.calendar.token", cal["bongo.calendar.invitation-token"]) store.PropSet(docpath, "bongo.calendar.invitation", "0") - print "Accepted %s" % (calname) + print("Accepted %s" % (calname)) else : - print "%s is not a calendar invitation" % (calname) + print("%s is not a calendar invitation" % (calname)) store.Quit() - except BongoError, e: + except BongoError as e: store.Quit() self.exit("%s: %s" % (docpath, str(e))) except: @@ -410,7 +410,7 @@ class CalendarUnshareCommand(Command): acl.UnshareAll() store.SetACL(doc, acl.GetACL()) - print "current acl: %s" % (str(acl)) + print("current acl: %s" % (str(acl))) finally: store.Quit() @@ -435,16 +435,15 @@ class CalendarListSharesCommand(Command): acl = CalendarACL(store.GetACL(doc)) summary = acl.Summarize() - print "Public: %s" % (acl.RightsToString(summary["public"])) + print("Public: %s" % (acl.RightsToString(summary["public"]))) - print "\nAddresses: " - print "========== " + print("\nAddresses: ") + print("========== ") for address in summary["addresses"] : info = summary["addresses"][address] - print address - print "\tpassword %s" % info["password"] - print "\taccess: %s" % (acl.RightsToString(info["rights"])) + print(address) + print("\tpassword %s" % info["password"]) + print("\taccess: %s" % (acl.RightsToString(info["rights"]))) finally: store.Quit() - diff --git a/src/apps/storetool/bongo/storetool/ContactCommands.py b/src/apps/storetool/bongo/storetool/ContactCommands.py index 902ecd6..ef838d3 100644 --- a/src/apps/storetool/bongo/storetool/ContactCommands.py +++ b/src/apps/storetool/bongo/storetool/ContactCommands.py @@ -28,7 +28,7 @@ class AddressbooksCommand(Command): finally: store.Quit() - print table.format_table(cols, rows) + print(table.format_table(cols, rows)) class AddressbookContactsCommand(Command): log = logging.getLogger("Bongo.StoreTool") @@ -57,7 +57,7 @@ class AddressbookContactsCommand(Command): try: ab = self._FindAddressbook(store, args[0]) if ab is None: - print "Could not find addressbook named '%s'" % args[0] + print("Could not find addressbook named '%s'" % args[0]) return contacts = list(store.List(ab.uid, ["nmap.document"])) @@ -72,7 +72,7 @@ class AddressbookContactsCommand(Command): store.Quit() rows.sort() - print table.format_table(cols, rows) + print(table.format_table(cols, rows)) class ImportVcfCommand(Command): log = logging.getLogger("Bongo.StoreTool") diff --git a/src/apps/storetool/bongo/storetool/ExportMailbox.py b/src/apps/storetool/bongo/storetool/ExportMailbox.py index 522d158..e5ece62 100644 --- a/src/apps/storetool/bongo/storetool/ExportMailbox.py +++ b/src/apps/storetool/bongo/storetool/ExportMailbox.py @@ -2,7 +2,7 @@ import os import re import socket import errno -import cStringIO +import io import mailbox import email, email.Generator import sys @@ -17,14 +17,14 @@ class MboxMailbox(mailbox.PortableUnixMailbox): self.content = "" def add(self, msg): - fp = cStringIO.StringIO() + fp = io.StringIO() g = email.Generator.Generator(fp, mangle_from_=False) envelope = email.message_from_string(msg) g.flatten(envelope, unixfrom=True) self.content += "%s" % fp.getvalue() def write(self): - outfile=file(self.boxname, "wb") + outfile=open(self.boxname, "wb") outfile.write("%s\n" % self.content) outfile.close() @@ -40,7 +40,7 @@ class MaildirMailbox(mailbox.Maildir): os.makedirs(self.boxname + "cur") os.makedirs(self.boxname + "new") os.makedirs(self.boxname + "tmp") - except OSError, err: + except OSError as err: if err.errno == errno.EEXIST: break mailbox.Maildir.__init__(self, file, email.message_from_file) @@ -52,11 +52,11 @@ class MaildirMailbox(mailbox.Maildir): name = "tmp/%.6f%05d.%s" % (time(), pid, hostname) try: os.stat(name) - except OSError, err: + except OSError as err: if err.errno == errno.ENOENT: break - fd = os.open(name, os.O_WRONLY|os.O_EXCL|os.O_CREAT, 0600) + fd = os.open(name, os.O_WRONLY|os.O_EXCL|os.O_CREAT, 0o600) return (name, fd) @@ -76,7 +76,7 @@ class MaildirMailbox(mailbox.Maildir): def get_delivery_time(self, message): dtime = None - if message.has_key("Date"): + if "Date" in message: dtime = mktime_tz(parsedate_tz(message["Date"])) return dtime @@ -86,7 +86,7 @@ class MaildirMailbox(mailbox.Maildir): os.write(fd, raw_msg) os.fsync(fd) os.close(fd) - except OSError, err: + except OSError as err: os.unlink(tmp) raise Error("unable to fsync() or close() temp file: %s" % err) @@ -108,7 +108,7 @@ class MaildirMailbox(mailbox.Maildir): (tmp, fd) = self.tmp_open() try: - fp = cStringIO.StringIO(raw_msg) + fp = io.StringIO(raw_msg) message = Message(fp) (dir, info) = self.status(message) dtime = self.get_delivery_time(message) diff --git a/src/apps/storetool/bongo/storetool/InteractiveCommands.py b/src/apps/storetool/bongo/storetool/InteractiveCommands.py index 90e65c2..27ebbe6 100644 --- a/src/apps/storetool/bongo/storetool/InteractiveCommands.py +++ b/src/apps/storetool/bongo/storetool/InteractiveCommands.py @@ -20,11 +20,11 @@ class BongoTelnet(telnetlib.Telnet): """A Telnet class made for talking to Bongo Stores. Uses readline.""" def mt_interact(self): """Multithreaded version of interact().""" - import thread - thread.start_new_thread(self.listener, ()) + import _thread + _thread.start_new_thread(self.listener, ()) while 1: try: - line = raw_input() + line = input() except EOFError: return if not line: @@ -40,13 +40,13 @@ class BongoTelnet(telnetlib.Telnet): try: text = self.read_eager() except EOFError: - print '*** Connection closed by remote host ***' + print('*** Connection closed by remote host ***') break if text: sys.stdout.write(text) sys.stdout.flush() except EOFError: - print '*** Connection closed by remote host ***' + print('*** Connection closed by remote host ***') return except: return @@ -60,22 +60,22 @@ class TelnetCommand(Command): def Run(self, options, args): try: - print "Trying %s..." % socket.gethostbyname(options.host) + print("Trying %s..." % socket.gethostbyname(options.host)) tn = BongoTelnet(options.host, options.port) - print "Connected to %s." % options.host + print("Connected to %s." % options.host) self.stream = CommandStream(tn.get_socket()) Auth(self.stream) - print "USER %s" % options.user + print("USER %s" % options.user) self.stream.Write("USER %s" % options.user) r = self.stream.GetResponse() - print "%d %s" % (r.code, r.message) + print("%d %s" % (r.code, r.message)) - print "STORE %s" % options.store + print("STORE %s" % options.store) self.stream.Write("STORE %s" % options.store) r = self.stream.GetResponse() - print "%d %s" % (r.code, r.message) + print("%d %s" % (r.code, r.message)) tn.mt_interact() except KeyboardInterrupt: diff --git a/src/apps/storetool/bongo/storetool/MailCommands.py b/src/apps/storetool/bongo/storetool/MailCommands.py index 89a8e13..c759815 100644 --- a/src/apps/storetool/bongo/storetool/MailCommands.py +++ b/src/apps/storetool/bongo/storetool/MailCommands.py @@ -58,8 +58,8 @@ class MailImportCommand(Command): for file in args: try: self.ImportFile(store, file, options.type, options.folder) - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) finally: store.Quit() @@ -107,8 +107,8 @@ class MailExportCommand(Command): for file in args: try: self.ExportFile(store, file, options.type, options.folder) - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) finally: store.Quit() diff --git a/src/apps/storetool/bongo/storetool/StoreCommands.py b/src/apps/storetool/bongo/storetool/StoreCommands.py index 7affe4b..669ffe0 100644 --- a/src/apps/storetool/bongo/storetool/StoreCommands.py +++ b/src/apps/storetool/bongo/storetool/StoreCommands.py @@ -28,9 +28,9 @@ class DocumentListCommand(Command): store.Store(options.store) list = store.List(collection) for document in list: - print "%s %s %s %s" % (document.uid, document.type, document.filename, document.bodylen) - except IOError, e: - print str(e) + print("%s %s %s %s" % (document.uid, document.type, document.filename, document.bodylen)) + except IOError as e: + print(str(e)) store.Quit() @@ -60,8 +60,8 @@ class DocumentGetCommand(Command): content = store.Read(document) f.write(content) f.close() - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) store.Quit() @@ -89,7 +89,7 @@ class DocumentPutCommand(Command): docbits = document.split('/') if len(docbits) < 2: - print "ERROR: Document must be a full path, e.g. /collection/documentname" + print("ERROR: Document must be a full path, e.g. /collection/documentname") doc_name = docbits.pop() doc_collection = '/'.join(docbits) if doc_collection == '': @@ -108,7 +108,7 @@ class DocumentPutCommand(Command): store.Write(doc_collection, doc_type, content, filename=doc_name) f.close() - except IOError, e: - print str(e) + except IOError as e: + print(str(e)) store.Quit() diff --git a/src/apps/storetool/bongo/storetool/TestCommands.py b/src/apps/storetool/bongo/storetool/TestCommands.py index d0fadb6..9637719 100644 --- a/src/apps/storetool/bongo/storetool/TestCommands.py +++ b/src/apps/storetool/bongo/storetool/TestCommands.py @@ -13,7 +13,7 @@ class TestRun(Command): usage="%prog %cmd") def Err(self, message): - print "[ERR] %s" % message + print("[ERR] %s" % message) def Run(self, options, args): try: @@ -23,7 +23,7 @@ class TestRun(Command): return # collection testing first - print "Looking for collections..." + print("Looking for collections...") try: colls = store.Collections() for coll in colls: @@ -31,13 +31,13 @@ class TestRun(Command): except: self.Err("Can't list collections (COLLECTIONS)") - print "Adding collection" + print("Adding collection") try: coll = store.Create("/testcoll", existingOk = True) except: self.Err("Can't add collection (CREATE)") - print "Listing collection contents" + print("Listing collection contents") try: contents = store.List("/testcoll") for doc in contents: @@ -45,7 +45,7 @@ class TestRun(Command): except: self.Err("Can't list collection contents (LIST)") - print "Renaming collection" + print("Renaming collection") try: store.Rename("/testcoll", "/renamed-testcoll") except: @@ -55,23 +55,23 @@ class TestRun(Command): mail1 = "%s/%s" % (mailpath, "bongo-general-000") mail2 = "%s/%s" % (mailpath, "bongo-general-002") - print "Writing mail to collection..." + print("Writing mail to collection...") guid = None try: - f = file(mail1) + f = open(mail1) guid = store.Write("/renamed-testcoll", DocTypes.Mail, f.read()) f.close() except: self.Err("Can't write new doc to renamed-testcoll") if guid != None: - print "Removing mail from collection..." + print("Removing mail from collection...") try: store.Delete(guid) except: self.Err("Can't remove document from renamed-testcoll") - print "Removing collection" + print("Removing collection") try: store.Remove("/renamed-testcoll") except: @@ -79,4 +79,4 @@ class TestRun(Command): - print "Test suite ran successfully." + print("Test suite ran successfully.") diff --git a/src/libs/python/bongo/Agent.py b/src/libs/python/bongo/Agent.py index 49e2794..680a546 100644 --- a/src/libs/python/bongo/Agent.py +++ b/src/libs/python/bongo/Agent.py @@ -33,8 +33,8 @@ class Agent: def daemonize(self): try: pid = os.fork() - except OSError, e: - raise Exception, e.strerror + except OSError as e: + raise Exception(e.strerror) if (pid != 0): os._exit(0) @@ -42,8 +42,8 @@ class Agent: try: pid = os.fork() - except OSError, e: - raise Exception, e.strerror + except OSError as e: + raise Exception(e.strerror) if (pid != 0): os._exit(0) diff --git a/src/libs/python/bongo/Console.py b/src/libs/python/bongo/Console.py index be261d9..5739eb9 100644 --- a/src/libs/python/bongo/Console.py +++ b/src/libs/python/bongo/Console.py @@ -1,5 +1,5 @@ import re -rx=re.compile(u"([\u2e80-\uffff])", re.UNICODE) +rx=re.compile("([\u2e80-\uffff])", re.UNICODE) # find out the terminal width try: @@ -28,5 +28,5 @@ def wrap(text, width=termwidth, encoding="utf8"): + len(word.split('\n',1)[0] ) >= width) or line[-1:] == '\0' and 2], word), - rx.sub(r'\1\0 ', unicode(text,encoding)).split(' ') + rx.sub(r'\1\0 ', str(text,encoding)).split(' ') ).replace('\0', '').encode(encoding) diff --git a/src/libs/python/bongo/Contact.py b/src/libs/python/bongo/Contact.py index 39c4c77..9abb594 100644 --- a/src/libs/python/bongo/Contact.py +++ b/src/libs/python/bongo/Contact.py @@ -27,7 +27,7 @@ class Contact: obj["value"] = str(content.value) - for key,value in content.params.items(): + for key,value in list(content.params.items()): obj[key.lower()] = value data.setdefault(field, []).append(obj) diff --git a/src/libs/python/bongo/MDB.py b/src/libs/python/bongo/MDB.py index 93ae172..b150302 100644 --- a/src/libs/python/bongo/MDB.py +++ b/src/libs/python/bongo/MDB.py @@ -99,7 +99,7 @@ class MDB(mdb): def AddObject(self, obj, classname, attrdict): vsattr = self.mdb_CreateValueStruct(self.handle) vsdata = self.mdb_CreateValueStruct(self.handle) - for key, vals in attrdict.iteritems(): + for key, vals in attrdict.items(): if '\\' in vals[0]: key = ('%c' % self.MDB_ATTR_SYN_DIST_NAME) + key else: @@ -165,7 +165,7 @@ class MDB(mdb): single = False sync = False public = False - for key, val in optdict.iteritems(): + for key, val in optdict.items(): if key.lower() == 'type': if val.lower() == 'dn': attrtype = self.MDB_ATTR_SYN_DIST_NAME @@ -192,7 +192,7 @@ class MDB(mdb): vsmand = self.mdb_CreateValueStruct(self.handle) vsopt = self.mdb_CreateValueStruct(self.handle) #fixme: partial success cases - for key, vals in optdict.iteritems(): + for key, vals in optdict.items(): if key.lower() == 'container': if vals[0] == True: container = True @@ -253,7 +253,7 @@ class MDB(mdb): delete = False rename = False admin = False - for key, val in optdict.iteritems(): + for key, val in optdict.items(): if key.lower() == 'read': if val == True: read = True @@ -279,7 +279,7 @@ class MDB(mdb): read = False write = False admin = False - for key, val in optdict.iteritems(): + for key, val in optdict.items(): if key.lower() == 'read': if val == True: read = True @@ -304,4 +304,4 @@ class MDB(mdb): return details if __name__ == '__main__': - print 'This file should not be executed directly; it is a library.' + print('This file should not be executed directly; it is a library.') diff --git a/src/libs/python/bongo/Privs.py b/src/libs/python/bongo/Privs.py index 6729d43..21304f0 100644 --- a/src/libs/python/bongo/Privs.py +++ b/src/libs/python/bongo/Privs.py @@ -74,4 +74,4 @@ def GainPrivs(): os.seteuid(uid) if __name__ == '__main__': - print 'This file should not be executed directly; it is a library.' + print('This file should not be executed directly; it is a library.') diff --git a/src/libs/python/bongo/StreamIO.py b/src/libs/python/bongo/StreamIO.py index 03c4257..0bf97bb 100644 --- a/src/libs/python/bongo/StreamIO.py +++ b/src/libs/python/bongo/StreamIO.py @@ -1,5 +1,5 @@ from libbongo.libs import streamio -import cStringIO as StringIO +import io as StringIO class Stream: def __init__(self, stream): diff --git a/src/libs/python/bongo/Template.py b/src/libs/python/bongo/Template.py index bd0e118..088036e 100644 --- a/src/libs/python/bongo/Template.py +++ b/src/libs/python/bongo/Template.py @@ -74,7 +74,7 @@ class TemplatePreprocessor: content = f.read() f.close() except: - print "Couldn't open file %s" % filename + print("Couldn't open file %s" % filename) return content def setTemplatePath(self, path): diff --git a/src/libs/python/bongo/__init__.py b/src/libs/python/bongo/__init__.py index f65cf39..9ec0b2a 100644 --- a/src/libs/python/bongo/__init__.py +++ b/src/libs/python/bongo/__init__.py @@ -1,4 +1,4 @@ -from BongoError import BongoError +from .BongoError import BongoError # I'm having very strange issues trying to import bongo.dragonfly from # our web service. When running under Apache, bongo.dragonfly can't be diff --git a/src/libs/python/bongo/admin/Addressbook.py b/src/libs/python/bongo/admin/Addressbook.py index f0da96f..defa0aa 100644 --- a/src/libs/python/bongo/admin/Addressbook.py +++ b/src/libs/python/bongo/admin/Addressbook.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowAddressbook(req): diff --git a/src/libs/python/bongo/admin/Alias.py b/src/libs/python/bongo/admin/Alias.py index e0ee34f..389b3a0 100644 --- a/src/libs/python/bongo/admin/Alias.py +++ b/src/libs/python/bongo/admin/Alias.py @@ -1,10 +1,10 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def CreateAlias(req): - if not req.fields.has_key('newaliasname'): + if 'newaliasname' not in req.fields: return Handler.SendMessage(req, 'Alias CN is required') - if not req.fields.has_key('newaliasref'): + if 'newaliasref' not in req.fields: return Handler.SendMessage(req, 'Aliased object is required') aliasname = req.fields.getfirst('newaliasname').value aliasref = req.fields.getfirst('newaliasref').value diff --git a/src/libs/python/bongo/admin/Antispam.py b/src/libs/python/bongo/admin/Antispam.py index 7fd5d54..7e11a0c 100644 --- a/src/libs/python/bongo/admin/Antispam.py +++ b/src/libs/python/bongo/admin/Antispam.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowAntispam(req): diff --git a/src/libs/python/bongo/admin/Calcmd.py b/src/libs/python/bongo/admin/Calcmd.py index 0d66990..9bf79b5 100644 --- a/src/libs/python/bongo/admin/Calcmd.py +++ b/src/libs/python/bongo/admin/Calcmd.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowCalcmd(req): diff --git a/src/libs/python/bongo/admin/Collector.py b/src/libs/python/bongo/admin/Collector.py index 9ac1bab..a566e0e 100644 --- a/src/libs/python/bongo/admin/Collector.py +++ b/src/libs/python/bongo/admin/Collector.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowCollector(req): diff --git a/src/libs/python/bongo/admin/Handler.py b/src/libs/python/bongo/admin/Handler.py index 5dfbe84..05149c1 100644 --- a/src/libs/python/bongo/admin/Handler.py +++ b/src/libs/python/bongo/admin/Handler.py @@ -2,9 +2,9 @@ import inspect from libbongo.libs import msgapi from bongo import MDB import bongo.commonweb.BongoSession as Session -import bongoutil as util -import Alias, Mdb, Security, Template, User, JsonUtil -import Imap, Pop3, Calcmd, Webservices, Itip, Webadmin, Proxy, Store, Smtp, Queue, Addressbook, Collector, Antispam, Msgserver +from . import bongoutil as util +from . import Alias, Mdb, Security, Template, User, JsonUtil +from . import Imap, Pop3, Calcmd, Webservices, Itip, Webadmin, Proxy, Store, Smtp, Queue, Addressbook, Collector, Antispam, Msgserver class Config: def __init__(self): @@ -22,7 +22,7 @@ class Config: self.modules['getobjattr'] = Mdb.GetObjectAttribute self.modules['setobjattr'] = Mdb.SetObjectAttribute self.modules['getattrprop'] = Mdb.GetAttributeProperty - self.modules['setattrprop'] = Mdb.SetAttributeProperty + self.modules['setattrprop'] = Mdb.SetAttributeProperty self.modules['deleteobj'] = Mdb.DeleteObject self.modules['searchtree'] = Mdb.SearchTree self.modules['loadobjchildren'] = Mdb.LoadObjectChildren @@ -62,13 +62,13 @@ class Config: self.ajaxmods.append('getobjattr') self.ajaxmods.append('setobjattr') self.ajaxmods.append('getattrprop') - self.ajaxmods.append('setattrprop') + self.ajaxmods.append('setattrprop') self.ajaxmods.append('deleteobj') self.ajaxmods.append('searchtree') self.ajaxmods.append('loadtreeobjs') self.ajaxmods.append('loadtreeattrs') self.ajaxmods.append('imap') - self.ajaxmods.append('pop3') + self.ajaxmods.append('pop3') self.ajaxmods.append('calcmd') self.ajaxmods.append('webservices') self.ajaxmods.append('itip') @@ -97,7 +97,7 @@ def handler(req): if resource_dir not in req.config.hiddendirs: try: return SendFile(req) - except Exception, e: + except Exception as e: return SendError(req, 'Unknown resource: ' + req.uri) else: return SendError(req, 'Unknown resource: ' + req.uri) @@ -108,7 +108,7 @@ def handler(req): if req.resource_name == 'login': return Security.Login(req) if req.resource_name not in req.config.publicmods and \ - not req.session.has_key('username'): + 'username' not in req.session: if req.resource_name != 'logout': req.session['request_uri'] = req.uri req.session.save() @@ -120,7 +120,7 @@ def handler(req): # Standard policies if req.resource_name.strip().strip('/') == '': return SendRedirect(req, req.application_path + '/main') - if not req.config.modules.has_key(req.resource_name): + if req.resource_name not in req.config.modules: return SendError(req, 'Unknown resource: ' + req.uri) # Initialize MDB and execute the module @@ -129,7 +129,7 @@ def handler(req): password = req.session['password'] req.mdb = MDB.MDB(username, password) return req.config.modules[req.resource_name](req) - except Exception, e: + except Exception as e: return SendError(req, str(e)) def ShowMain(req): diff --git a/src/libs/python/bongo/admin/Imap.py b/src/libs/python/bongo/admin/Imap.py index d7f4dc6..d820e67 100644 --- a/src/libs/python/bongo/admin/Imap.py +++ b/src/libs/python/bongo/admin/Imap.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowImap(req): diff --git a/src/libs/python/bongo/admin/Itip.py b/src/libs/python/bongo/admin/Itip.py index f0e1b2f..e440d65 100644 --- a/src/libs/python/bongo/admin/Itip.py +++ b/src/libs/python/bongo/admin/Itip.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowItip(req): diff --git a/src/libs/python/bongo/admin/JsonUtil.py b/src/libs/python/bongo/admin/JsonUtil.py index dd64941..b919376 100644 --- a/src/libs/python/bongo/admin/JsonUtil.py +++ b/src/libs/python/bongo/admin/JsonUtil.py @@ -4,23 +4,23 @@ import types def jsonstr(item): """Turn an object into a JSON string""" item_type = type(item) - if item_type == types.BooleanType: + if item_type == bool: return boolean2json(item) - elif item_type == types.DictType: + elif item_type == dict: return dict2json(item) - elif item_type == types.FloatType: + elif item_type == float: return float2json(item) elif item_type == types.InstanceType: return instance2json(item) - elif item_type == types.IntType: + elif item_type == int: return int2json(item) - elif item_type == types.ListType: + elif item_type == list: return list2json(item) - elif item_type == types.NoneType: + elif item_type == type(None): return none2json(item) - elif item_type == types.StringType: + elif item_type == bytes: return string2json(item) - elif item_type == types.TupleType: + elif item_type == tuple: return tuple2json(item) return 'null' @@ -29,7 +29,7 @@ def boolean2json(item): def dict2json(item): json = '' - for key, value in item.items(): + for key, value in list(item.items()): json += key + ':' + jsonstr(value) + ',' return '{' + json[:-1] + '}' diff --git a/src/libs/python/bongo/admin/ManagedSlapd.py b/src/libs/python/bongo/admin/ManagedSlapd.py index b5446a6..be121c8 100644 --- a/src/libs/python/bongo/admin/ManagedSlapd.py +++ b/src/libs/python/bongo/admin/ManagedSlapd.py @@ -7,7 +7,7 @@ import logging import os import pwd import random -import sha +import hashlib import signal import socket import string @@ -51,7 +51,7 @@ class ConfigSlapd: s.close() if not os.path.exists(self.slapdPidFile): - print wrap("Slapd is running, but its pid file doesn't exist. You may need to kill slapd manually.") + print(wrap("Slapd is running, but its pid file doesn't exist. You may need to kill slapd manually.")) return None return True @@ -83,7 +83,7 @@ class ConfigSlapd: for i in range(1, 10): salt = salt + random.choice(string.ascii_letters + string.digits) - ctx = sha.new(password) + ctx = hashlib.sha1(password.encode("utf-8")) ctx.update(salt) enc = base64.encodestring(ctx.digest() + salt) @@ -91,7 +91,7 @@ class ConfigSlapd: def startSlapd(self, confFile): if not os.path.exists(self.binary): - print "Slapd path doesn't exist: %s" % self.binary + print("Slapd path doesn't exist: %s" % self.binary) return None tmp = self.slapdRunning(self.port) @@ -99,10 +99,10 @@ class ConfigSlapd: return None if tmp: - print "Found an existing slapd on port %d, using that" % self.port + print("Found an existing slapd on port %d, using that" % self.port) return 0 - print "Starting temporary slapd process" + print("Starting temporary slapd process") pid = os.fork() @@ -140,7 +140,7 @@ class ConfigSlapd: def killSlapd(self): if self.slapdPid: - print "Shutting down temporary slapd process" + print("Shutting down temporary slapd process") os.kill(self.slapdPid, signal.SIGTERM) # wait until it has exited before continuing diff --git a/src/libs/python/bongo/admin/Mdb.py b/src/libs/python/bongo/admin/Mdb.py index e1fdafd..3ed2b5d 100644 --- a/src/libs/python/bongo/admin/Mdb.py +++ b/src/libs/python/bongo/admin/Mdb.py @@ -75,7 +75,7 @@ def _search_tree(req, context, classname): def LoadObjectChildren(req): results = [] context = '' - if req.fields.has_key('context'): + if 'context' in req.fields: context = req.fields.getfirst('context').value if context == '': context = '#'.join(req.session['username'].split('\\')[0:-1]) @@ -99,7 +99,7 @@ def LoadObjectChildren(req): if currobj == '': currobj = html % (c_back, c_back, node) else: - currobj = html % (c_back, c_back, node) +'\\'+ currobj + currobj = html % (c_back, c_back, node) +'\\'+ currobj context = '#'.join(context.split('#')[0:-1]) response += '\\'+currobj response += '

' @@ -118,7 +118,7 @@ def LoadObjectChildren(req): # version 1 - returns attribute list, includes html formating def xLoadObjectAttributes(req): results = [] - if not req.fields.has_key('objdn'): + if 'objdn' not in req.fields: objdn = '\\'.join(req.session['username'].split('\\')[0:-1]) #return Handler.SendMessage(req, 'No object specified') else: @@ -141,7 +141,7 @@ def xLoadObjectAttributes(req): # version 2 - returns a dict, enabled for inline editor def LoadObjectAttributes(req): - if not req.fields.has_key('objdn'): + if 'objdn' not in req.fields: objdn = '\\'.join(req.session['username'].split('\\')[0:-1]) #return Handler.SendMessage(req, 'No object specified') else: @@ -161,7 +161,7 @@ def LoadObjectAttributes(req): # version3 - returns a dict, includes all schema defined attributes def zLoadObjectAttributes(req): """Return a dict of (set and unset) attributes on a BongoUser.""" - if not req.fields.has_key('objdn'): + if 'objdn' not in req.fields: objdn = '\\'.join(req.session['username'].split('\\')[0:-1]) #return Handler.SendMessage(req, 'No object specified') else: @@ -170,7 +170,7 @@ def zLoadObjectAttributes(req): fields = {} details = req.mdb.GetObjectDetails(objdn) - if 'Type' not in details.keys(): + if 'Type' not in list(details.keys()): raise bongo.BongoError('Could not determine type for ' + objdn) #fields['len'] = len( Util.GetClassAttributes(details['Type'])) try: @@ -180,7 +180,7 @@ def zLoadObjectAttributes(req): fields[str(attribute.replace(' ','_'))] = '' else: fields[str(attribute.replace(' ','_'))] = attrs - except Exception, e: + except Exception as e: str(e) if len(fields) <= 0: attributes = req.mdb.EnumerateAttributes(objdn) @@ -195,4 +195,3 @@ def zLoadObjectAttributes(req): else: fields['Object_Class'] = req.mdb.GetAttributes(objdn,'Object Class') return Handler.SendDict(req,fields) - diff --git a/src/libs/python/bongo/admin/Msgserver.py b/src/libs/python/bongo/admin/Msgserver.py index 971b5a1..0d098dd 100644 --- a/src/libs/python/bongo/admin/Msgserver.py +++ b/src/libs/python/bongo/admin/Msgserver.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowMsgserver(req): diff --git a/src/libs/python/bongo/admin/Pop3.py b/src/libs/python/bongo/admin/Pop3.py index 7cf1202..7dc71e0 100644 --- a/src/libs/python/bongo/admin/Pop3.py +++ b/src/libs/python/bongo/admin/Pop3.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowPop3(req): diff --git a/src/libs/python/bongo/admin/Proxy.py b/src/libs/python/bongo/admin/Proxy.py index b86227c..d936f30 100644 --- a/src/libs/python/bongo/admin/Proxy.py +++ b/src/libs/python/bongo/admin/Proxy.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowProxy(req): diff --git a/src/libs/python/bongo/admin/Queue.py b/src/libs/python/bongo/admin/Queue.py index 6e51a42..f29a36e 100644 --- a/src/libs/python/bongo/admin/Queue.py +++ b/src/libs/python/bongo/admin/Queue.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowQueue(req): diff --git a/src/libs/python/bongo/admin/Schema.py b/src/libs/python/bongo/admin/Schema.py index f6590d4..e41c4d3 100644 --- a/src/libs/python/bongo/admin/Schema.py +++ b/src/libs/python/bongo/admin/Schema.py @@ -68,7 +68,7 @@ class Schema: self.read(filename) def addClass(self, schemaClass): - if self.classes.has_key(schemaClass.name): + if schemaClass.name in self.classes: self.removeClass(schemaClass.name) self.schemaClasses.append(schemaClass) self.classes[schemaClass.name] = schemaClass @@ -81,7 +81,7 @@ class Schema: return self.attributes.get(attrName) def addAttribute(self, schemaAttribute): - if self.attributes.has_key(schemaAttribute.name): + if schemaAttribute.name in self.attributes: self.removeAttribute(schemaAttribute.name) self.schemaAttributes.append(schemaAttribute) self.attributes[schemaAttribute.name] = schemaAttribute @@ -149,7 +149,7 @@ class SchemaClass: self.loginClass = False attrs = parent.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) if attrName == 'name': self.name = attrNode.nodeValue @@ -168,7 +168,7 @@ class SchemaClass: if classNode.nodeType == Node.ELEMENT_NODE and \ classNode.nodeName == 'option': attrs = classNode.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) attrValue = attrNode.nodeValue if attrName == 'type': @@ -183,7 +183,7 @@ class SchemaClass: if classNode.nodeType == Node.ELEMENT_NODE and \ classNode.nodeName == 'class': attrs = classNode.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) attrValue = attrNode.nodeValue if attrName == 'name': @@ -193,7 +193,7 @@ class SchemaClass: if classNode.nodeType == Node.ELEMENT_NODE and \ classNode.nodeName == 'attribute': attrs = classNode.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) attrValue = attrNode.nodeValue if attrName == 'name': @@ -203,7 +203,7 @@ class SchemaClass: if classNode.nodeType == Node.ELEMENT_NODE and \ classNode.nodeName == 'attribute': attrs = classNode.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) attrValue = attrNode.nodeValue if attrName == 'name': @@ -214,7 +214,7 @@ class SchemaAttribute: def __init__(self, parent): self.name = None self.oid = None - self.guid = None + self.guid = None self.syntax = None self.syncImmediate = False self.singleValue = False @@ -223,7 +223,7 @@ class SchemaAttribute: return attrs = parent.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) if attrName == 'name': self.name = attrNode.nodeValue @@ -240,7 +240,7 @@ class SchemaAttribute: if option.nodeType == Node.ELEMENT_NODE and \ option.nodeName == 'option': attrs = option.attributes - for attrName in attrs.keys(): + for attrName in list(attrs.keys()): attrNode = attrs.get(attrName) attrValue = attrNode.nodeValue if attrName == 'type': diff --git a/src/libs/python/bongo/admin/Security.py b/src/libs/python/bongo/admin/Security.py index 83110a4..a806ae4 100644 --- a/src/libs/python/bongo/admin/Security.py +++ b/src/libs/python/bongo/admin/Security.py @@ -1,9 +1,9 @@ -import Handler, Template +from . import Handler, Template from bongo import MDB def ShowLogin(req, message=''): username = '' - if req.fields.has_key('username'): + if 'username' in req.fields: username = req.fields.getfirst('username').value tmpl = Template.Template('tmpl/login.tmpl') tmpl.SetPageVariable('message', message) @@ -14,9 +14,9 @@ def ShowLogin(req, message=''): def Login(req): redirect_uri = req.application_path - if not req.fields.has_key('username'): + if 'username' not in req.fields: return ShowLogin(req, 'Username is required') - if not req.fields.has_key('password'): + if 'password' not in req.fields: return ShowLogin(req, 'Password is required') username = req.fields.getfirst('username').value @@ -26,16 +26,16 @@ def Login(req): username = req.default_context + '\\' + username try: mdb = MDB.MDB(username, password) - except MDB.MDBError, e: + except MDB.MDBError as e: try: username = req.fields.getfirst('username').value mdb = MDB.MDB(username,password) - except MDB.MDBError, e: + except MDB.MDBError as e: return ShowLogin(req, 'Login failed') req.session['username'] = username req.session['password'] = password - if req.session.has_key('request_uri'): + if 'request_uri' in req.session: redirect_uri = req.session['request_uri'] del req.session['request_uri'] req.session.save() diff --git a/src/libs/python/bongo/admin/Smtp.py b/src/libs/python/bongo/admin/Smtp.py index 7ed17c5..983fc51 100644 --- a/src/libs/python/bongo/admin/Smtp.py +++ b/src/libs/python/bongo/admin/Smtp.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowSmtp(req): diff --git a/src/libs/python/bongo/admin/Store.py b/src/libs/python/bongo/admin/Store.py index 5060c73..30b4f6a 100644 --- a/src/libs/python/bongo/admin/Store.py +++ b/src/libs/python/bongo/admin/Store.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowStore(req): diff --git a/src/libs/python/bongo/admin/User.py b/src/libs/python/bongo/admin/User.py index e8609a9..015a117 100644 --- a/src/libs/python/bongo/admin/User.py +++ b/src/libs/python/bongo/admin/User.py @@ -1,19 +1,19 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB from libbongo.libs import msgapi def CreateUser(req): - if not req.fields.has_key('newusername'): + if 'newusername' not in req.fields: return Handler.SendMessage(req, 'Username is required') - if not req.fields.has_key('newfirstname'): + if 'newfirstname' not in req.fields: return Handler.SendMessage(req, 'First name is required') - if not req.fields.has_key('newlastname'): + if 'newlastname' not in req.fields: return Handler.SendMessage(req, 'Last name is required') - if not req.fields.has_key('newemail'): + if 'newemail' not in req.fields: return Handler.SendMessage(req, 'Email address is required') - if not req.fields.has_key('newpassword'): + if 'newpassword' not in req.fields: return Handler.SendMessage(req, 'Password is requried') - if not req.fields.has_key('newpassword2'): + if 'newpassword2' not in req.fields: return Handler.SendMessage(req, 'Please confirm your password') username = req.fields.getfirst('newusername').value @@ -38,7 +38,7 @@ def CreateUser(req): def SearchUsers(req): response = '' - if req.fields.has_key('pattern'): + if 'pattern' in req.fields: pattern = req.fields.getfirst('pattern').value response += '' context = req.default_context diff --git a/src/libs/python/bongo/admin/Util.py b/src/libs/python/bongo/admin/Util.py index 85107ec..6973f84 100644 --- a/src/libs/python/bongo/admin/Util.py +++ b/src/libs/python/bongo/admin/Util.py @@ -41,12 +41,12 @@ def AddBongoUser(mdb, context, username, attributes, password = None): if '\\' not in username: raise BongoError('No context for user ' + username) for attr in [mdb.A_SURNAME]: - if attr not in attributes.keys(): - opt = Properties.keys()[Properties.values().index(attr)] + if attr not in list(attributes.keys()): + opt = list(Properties.keys())[list(Properties.values()).index(attr)] raise BongoError('Required option --%s not specified.' % opt) required[attr] = attributes.pop(attr) mdb.AddObject(userobject, mdb.C_USER, required) - for key, vals in attributes.iteritems(): + for key, vals in attributes.items(): MsgApi.SetUserSetting(userobject, key, vals) if password: mdb.SetPassword(userobject, password) @@ -61,7 +61,7 @@ def ModifyBongoUser(mdb, context, username, attributes, password = None): else: if '\\' not in username: raise BongoError('No context for user ' + username) - for key, vals in attributes.iteritems(): + for key, vals in attributes.items(): if MsgApi.SetUserSetting(userobject, key, vals) is False: raise BongoError('Error setting %s on %s' % (key, userobject)) if password: @@ -78,7 +78,7 @@ def RemoveBongoUser(mdb, context, username): if '\\' not in username: raise BongoError('No context for user ' + username) details = mdb.GetObjectDetails(userobject) - if 'Type' not in details.keys(): + if 'Type' not in list(details.keys()): raise BongoError('Could not determine type for ' + userobject) if not details['Type'] == mdb.C_USER: raise BongoError(userobject + ' is not a ' + mdb.C_USER) @@ -99,7 +99,7 @@ def DelegateBongoUser(mdb, context, username, community): if '\\' not in username: raise BongoError('No context for user ' + username) details = mdb.GetObjectDetails(userobject) - if 'Type' not in details.keys(): + if 'Type' not in list(details.keys()): raise BongoError('Could not determine type for ' + userobject) if not details['Type'] == mdb.C_USER: raise BongoError(userobject + ' is not a ' + mdb.C_USER) @@ -129,7 +129,7 @@ def UndelegateBongoUser(mdb, context, username, community): if '\\' not in username: raise BongoError('No context for user ' + username) details = mdb.GetObjectDetails(userobject) - if 'Type' not in details.keys(): + if 'Type' not in list(details.keys()): raise BongoError('Could not determine type for ' + userobject) if not details['Type'] == mdb.C_USER: raise BongoError(userobject + ' is not a ' + mdb.C_USER) @@ -162,18 +162,18 @@ def AddBongoAgent(mdb, server, name, type, attributes = {}): raise BongoError('Server \"%s\" not found' % str(server)) for attr in [msgapi.A_MODULE_NAME, msgapi.A_MODULE_VERSION]: - if attr not in attributes.keys(): - opt = Properties.keys()[Properties.values().index(attr)] + if attr not in list(attributes.keys()): + opt = list(Properties.keys())[list(Properties.values()).index(attr)] raise BongoError('Required option --%s not specified' % opt) if type == msgapi.C_STORE: for attr in [msgapi.A_MESSAGE_STORE]: - opt = Properties.keys()[Properties.values().index(attr)] - if attr not in attributes.keys(): + opt = list(Properties.keys())[list(Properties.values()).index(attr)] + if attr not in list(attributes.keys()): raise BongoError('Required option --%s not specified'% opt) elif type == msgapi.C_SMTP: for attr in [msgapi.A_DOMAIN]: - opt = Properties.keys()[Properties.values().index(attr)] - if attr not in attributes.keys(): + opt = list(Properties.keys())[list(Properties.values()).index(attr)] + if attr not in list(attributes.keys()): raise BongoError('Required option --%s not specified'% opt) mdb.AddObject(agentobj, Entities[type], attributes) return @@ -185,7 +185,7 @@ def ModifyBongoAgent(mdb, server, name, attributes = {}): if not server or not mdb.IsObject(agentobj): raise BongoError('Server \"%s\" not found' % str(server)) if attributes: - for key, vals in attributes.iteritems(): + for key, vals in attributes.items(): mdb.SetAttribute(agentobj, key, vals) return @@ -204,8 +204,8 @@ def AddBongoServer(mdb, name, attributes = {}): msgapi.A_POSTMASTER, msgapi.A_CONTEXT, msgapi.A_OFFICIAL_NAME]: - if attr not in attributes.keys(): - opt = Properties.keys()[Properties.values().index(attr)] + if attr not in list(attributes.keys()): + opt = list(Properties.keys())[list(Properties.values()).index(attr)] raise BongoError('Required option --%s not specified' % opt) mdb.AddObject(serverobj, msgapi.C_SERVER, attributes) # Always create a user settings container for bongo services @@ -219,7 +219,7 @@ def ModifyBongoServer(mdb, name, attributes = {}): (msgapi.GetConfigProperty(msgapi.BONGO_SERVICES), name) if not mdb.IsObject(serverobj): raise BongoError('Server \"%s\" not found' % str(serverobj)) - for key, vals in attributes.iteritems(): + for key, vals in attributes.items(): mdb.SetAttribute(serverobj, key, vals) return @@ -271,7 +271,7 @@ def GetClassAttributes(classname): schema = GetSchema() - tempattrs = FindInheritedAttrs(unicode(classname), schema, []) + tempattrs = FindInheritedAttrs(str(classname), schema, []) for attr in tempattrs: attrs.append(str(attr)) @@ -280,7 +280,7 @@ def GetClassAttributes(classname): def GetClassAttributeObjects(classname): """Return a list of possible attributes for a given classname.""" schema = GetSchema() - attrs = FindInheritedAttrObjects(unicode(classname), schema) + attrs = FindInheritedAttrObjects(str(classname), schema) # add the naming attribute for this class (typically CN), which # isn't found in the schema @@ -309,7 +309,7 @@ def FindInheritedAttrObjects(classname, schema): attrs[attr] = schema.getAttribute(attr) for superclass in cls.superClasses: - if schema.classes.has_key(superclass): + if superclass in schema.classes: attrs.update(FindInheritedAttrObjects(superclass, schema)) return attrs @@ -319,7 +319,7 @@ def FindInheritedAttrs(classname, schema, attrs): attrs.extend(schema.classes[classname].allowedAttributes) attrs.extend(schema.classes[classname].requiredAttributes) for superclass in schema.classes[classname].superClasses: - if superclass in schema.classes.keys(): + if superclass in list(schema.classes.keys()): FindInheritedAttrs(superclass, schema, attrs) return attrs @@ -335,7 +335,7 @@ def GetUserAttributes(mdb, context, username): if '\\' not in username: raise BongoError('No context for user ' + username) details = mdb.GetObjectDetails(userobject) - if 'Type' not in details.keys(): + if 'Type' not in list(details.keys()): raise BongoError('Could not determine type for ' + userobject) if not details['Type'] == mdb.C_USER: raise BongoError(userobject + ' is not a ' + mdb.C_USER) @@ -395,10 +395,10 @@ def SetupFromXML(mdb, base, xmlfile): requiredattrs = {} allowedattrs = {} #speaking of DNs, we need to resolve them now - for key, attrib in attrs.iteritems(): + for key, attrib in attrs.items(): requiredattrs[key] = {} allowedattrs[key] = {} - for attr, vals in attrib.iteritems(): + for attr, vals in attrib.items(): newvals = [] for val in vals: newval = None @@ -407,7 +407,7 @@ def SetupFromXML(mdb, base, xmlfile): newval = '%s\\' % base elif val.startswith('\\'): #fill in DNs - for obj in objs.keys(): + for obj in list(objs.keys()): if obj.endswith(val): newval = obj if not newval: @@ -416,36 +416,36 @@ def SetupFromXML(mdb, base, xmlfile): else: newval = val newvals.append(newval) - type = unicode(objs[key]) + type = str(objs[key]) #required = schema.classes[type].requiredAttributes required = SetupFindInheritedRequiredAttrs(type, schema) - if unicode(Properties[attr]) in required: + if str(Properties[attr]) in required: requiredattrs[key][Properties[attr]] = newvals else: allowedattrs[key][Properties[attr]] = newvals - objects = objs.items() + objects = list(objs.items()) objects.sort() #very handy sort, \a now preceeds \a\b, which preceeds \a\b\c... #create objects with just the required attributes first for objname, classname in objects: attributes = {} - if objname in requiredattrs.keys(): + if objname in list(requiredattrs.keys()): attributes = requiredattrs[objname] if(mdb.IsObject(objname)): #print 'modifying existing %s' % objname #only set attributes if object already exists #TODO: overridable behaviour for ignoring/clearing existing objs? - for key, vals in attributes.iteritems(): + for key, vals in attributes.items(): mdb.SetAttribute(objname, key, vals) else: #print 'adding %s (%s)' % (objname, classname) #print attributes log.debug("adding %s (%s): %s", objname, classname, str(attributes)) mdb.AddObject(objname, classname, attributes) - if objname in passwds.keys(): + if objname in list(passwds.keys()): mdb.SetPassword(objname, passwds[objname]) #now slap on all the optional attributes (in which DNs will now be valid) - for obj, attrib in allowedattrs.iteritems(): + for obj, attrib in allowedattrs.items(): if objs[obj] == mdb.C_USER: try: from libbongo.libs import msgapi as MsgApi @@ -454,17 +454,17 @@ def SetupFromXML(mdb, base, xmlfile): # save it in /tmp somewhere, do the rest of the # bootstrapping, and import the users later raise BongoError('Cannot import users during setup; import from a separate file afterwards.') - for key, vals in attrib.iteritems(): + for key, vals in attrib.items(): MsgApi.SetUserSetting(obj, key, vals) else: - for key, vals in attrib.iteritems(): + for key, vals in attrib.items(): mdb.SetAttribute(obj, key, vals) def SetupFindInheritedRequiredAttrs(classname, schema, attrs = []): """Recursively find required attributes for a class""" attrs.extend(schema.classes[classname].requiredAttributes) for superclass in schema.classes[classname].superClasses: - if superclass in schema.classes.keys(): + if superclass in list(schema.classes.keys()): SetupFindInheritedRequiredAttrs(superclass, schema, attrs) return attrs @@ -477,7 +477,7 @@ def SetupFromNode(mdb, node, objs, attrs, passwds, schema, base): if str(parnode.parentNode.nodeName) == 'user': ##context = msgapi.GetConfigProperty(msgapi.DEFAULT_CONTEXT) #we might not be able to ask for that yet, we'll have to build it - if 'context' in node.attributes.keys(): + if 'context' in list(node.attributes.keys()): context = str(node.attributes['context']) else: context = mdb.baseDn @@ -486,7 +486,7 @@ def SetupFromNode(mdb, node, objs, attrs, passwds, schema, base): else: while parnode.parentNode: if parnode.parentNode.attributes: - if 'name' in parnode.parentNode.attributes.keys(): + if 'name' in list(parnode.parentNode.attributes.keys()): parname = \ str(parnode.parentNode.attributes['name'].value) parent = '%s\\%s' % (parname, parent) @@ -495,30 +495,30 @@ def SetupFromNode(mdb, node, objs, attrs, passwds, schema, base): parent = '\\%s' % parent.strip('\\') #parent now has \\com\\novell\\Bongo Services\\... (or the user DN) if str(node.nodeName) in ['module', 'agent', 'container'] and \ - 'type' in node.attributes.keys(): + 'type' in list(node.attributes.keys()): objname = str(node.attributes['name'].value) - if objname in objs.keys(): + if objname in list(objs.keys()): raise BongoError('Duplicate setup item \"%s\" found' % objname) itemname = Entities[str(node.attributes['type'].value)] objs['%s\\%s' % (parent, objname)] = itemname #import users - elif str(node.nodeName) == 'user' and 'name' in node.attributes.keys(): + elif str(node.nodeName) == 'user' and 'name' in list(node.attributes.keys()): passwd = None - if 'context' in node.attributes.keys(): + if 'context' in list(node.attributes.keys()): context = str(node.attributes['context']) else: ##context = msgapi.GetConfigProperty(msgapi.DEFAULT_CONTEXT) #we might not be able to ask for that yet, we'll have to build it context = mdb.baseDn - if 'password' in node.attributes.keys(): + if 'password' in list(node.attributes.keys()): password = str(node.attributes['password'].value) passwds['%s\\%s' % (context, node.attributes['name'].value)] = \ password objs['%s\\%s' % (context, str(node.attributes['name'].value))] = \ mdb.C_USER - elif str(node.nodeName) in Entities.keys(): - objname = str(node.attributes[u'name'].value) - if objname in objs.keys(): + elif str(node.nodeName) in list(Entities.keys()): + objname = str(node.attributes['name'].value) + if objname in list(objs.keys()): raise BongoError('Duplicate setup item \"%s\" found' % objname) itemname = Entities[str(node.nodeName)] ##objs['%s\\%s%s' % (base, parent, objname)] = itemname @@ -540,9 +540,9 @@ def SetupFromNode(mdb, node, objs, attrs, passwds, schema, base): ##parent = '%s\\%s' % (base, parent.strip('\\')) key = str(node.attributes['name'].value) values = [] - if parent not in attrs.keys(): + if parent not in list(attrs.keys()): attrs[parent] = {} - if key not in Properties.keys(): + if key not in list(Properties.keys()): raise BongoError('Unrecognized property: %s' % key) #grab value style vals # + value style vals @@ -551,8 +551,8 @@ def SetupFromNode(mdb, node, objs, attrs, passwds, schema, base): if child.nodeValue: if child.nodeValue.strip(): val = str(child.nodeValue.strip()) - if unicode(Properties[key]) in schema.attributes.keys(): - syn = schema.attributes[unicode(Properties[key])].syntax + if str(Properties[key]) in list(schema.attributes.keys()): + syn = schema.attributes[str(Properties[key])].syntax if syn == 'DistinguishedName': values.append('\\%s' % val) else: @@ -614,7 +614,7 @@ def WriteConfProperties(props): filename = os.path.join(Xpl.DEFAULT_CONF_DIR, msgapi.CONFIG_FILENAME) fd = open(filename, "w") - keys = props.keys() + keys = list(props.keys()) keys.sort() for key in keys: @@ -1077,7 +1077,7 @@ Properties = { \ # reverse the Properties hash PropertyArguments = {} -for key, value in Properties.items(): +for key, value in list(Properties.items()): PropertyArguments[value] = key #TODO: translations diff --git a/src/libs/python/bongo/admin/Webadmin.py b/src/libs/python/bongo/admin/Webadmin.py index a6eebd8..1ee0c7e 100644 --- a/src/libs/python/bongo/admin/Webadmin.py +++ b/src/libs/python/bongo/admin/Webadmin.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowWebadmin(req): diff --git a/src/libs/python/bongo/admin/Webservices.py b/src/libs/python/bongo/admin/Webservices.py index bc6068b..ccda579 100644 --- a/src/libs/python/bongo/admin/Webservices.py +++ b/src/libs/python/bongo/admin/Webservices.py @@ -1,4 +1,4 @@ -import Handler, Mdb, Security, Template, Util +from . import Handler, Mdb, Security, Template, Util from bongo import MDB def ShowWebservices(req): diff --git a/src/libs/python/bongo/admin/bongoutil.py b/src/libs/python/bongo/admin/bongoutil.py index f7aabce..7817a43 100644 --- a/src/libs/python/bongo/admin/bongoutil.py +++ b/src/libs/python/bongo/admin/bongoutil.py @@ -1,4 +1,4 @@ -import urllib +import urllib.request, urllib.parse, urllib.error from bongo import BongoError class BongoFieldStorage(dict): @@ -18,8 +18,8 @@ class BongoFieldStorage(dict): if args != None: for arg in args.split('&'): (key, val) = arg.split('=') - field = BongoField(key, urllib.unquote_plus(val)) - if self.has_key(key): + field = BongoField(key, urllib.parse.unquote_plus(val)) + if key in self: try: self[key].append(field) except: @@ -32,7 +32,7 @@ class BongoFieldStorage(dict): return self.fields def getfirst(self, name, default=None): - if self.has_key(name): + if name in self: try: return self[name][0] except: diff --git a/src/libs/python/bongo/cmdparse.py b/src/libs/python/bongo/cmdparse.py index 21f0139..1f9c636 100644 --- a/src/libs/python/bongo/cmdparse.py +++ b/src/libs/python/bongo/cmdparse.py @@ -12,7 +12,7 @@ class Command(OptionParser): self.summary = kwargs.get("summary", None) for key in ("aliases", "summary"): - if kwargs.has_key(key): + if key in kwargs: del kwargs[key] OptionParser.__init__(self, *args, **kwargs) @@ -81,7 +81,7 @@ class Command(OptionParser): class CommandParser(OptionParser): """Parse command-line options CVS style.""" def __init__(self, *args, **kwargs): - if not kwargs.has_key("usage"): + if "usage" not in kwargs: kwargs["usage"] = "%prog [options] [command options]" OptionParser.__init__(self, *args, **kwargs) @@ -104,7 +104,7 @@ class CommandParser(OptionParser): for attr in dir(module): cls = getattr(module, attr) - if not type(cls) is types.ClassType: + if not type(cls) is type: continue if (not cls is Command) \ @@ -137,7 +137,7 @@ class CommandParser(OptionParser): (cmdoptions, args) = cmd.parse_args(args[1:]) # update cmdoptions with the values from options - for (attr, val) in options.__dict__.items(): + for (attr, val) in list(options.__dict__.items()): setattr(cmdoptions, attr, val) return (cmd, cmdoptions, args) @@ -152,7 +152,7 @@ class CommandParser(OptionParser): result = [] - groups = self.groups.keys() + groups = list(self.groups.keys()) groups.sort() max_cmd_length = 0 diff --git a/src/libs/python/bongo/external/dateutil/easter.py b/src/libs/python/bongo/external/dateutil/easter.py index e55afdb..6a573e1 100644 --- a/src/libs/python/bongo/external/dateutil/easter.py +++ b/src/libs/python/bongo/external/dateutil/easter.py @@ -52,7 +52,7 @@ def easter(year, method=EASTER_WESTERN): """ if not (1 <= method <= 3): - raise ValueError, "invalid method" + raise ValueError("invalid method") # g - Golden year - 1 # c - Century diff --git a/src/libs/python/bongo/external/dateutil/parser.py b/src/libs/python/bongo/external/dateutil/parser.py index 5f25a4d..d5eda44 100644 --- a/src/libs/python/bongo/external/dateutil/parser.py +++ b/src/libs/python/bongo/external/dateutil/parser.py @@ -14,8 +14,8 @@ import sys import time import datetime -import relativedelta -import tz +from . import relativedelta +from . import tz __all__ = ["parse", "parserinfo"] @@ -29,13 +29,13 @@ __all__ = ["parse", "parserinfo"] # http://stein.cshl.org/jade/distrib/docs/java.text.SimpleDateFormat.html try: - from cStringIO import StringIO + from io import StringIO except ImportError: - from StringIO import StringIO + from io import StringIO class _timelex: def __init__(self, instream): - if isinstance(instream, basestring): + if isinstance(instream, str): instream = StringIO(instream) self.instream = instream self.wordchars = ('abcdfeghijklmnopqrstuvwxyz' @@ -129,7 +129,7 @@ class _timelex: def __iter__(self): return self - def next(self): + def __next__(self): token = self.get_token() if token is None: raise StopIteration @@ -150,7 +150,7 @@ class _resultbase(object): for attr in self.__slots__: value = getattr(self, attr) if value is not None: - l.append("%s=%s" % (attr, `value`)) + l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (classname, ", ".join(l)) def __repr__(self): @@ -289,7 +289,7 @@ class parser: elif isinstance(info, parserinfo): self.info = info else: - raise TypeError, "Unsupported parserinfo type" + raise TypeError("Unsupported parserinfo type") def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, @@ -299,7 +299,7 @@ class parser: second=0, microsecond=0) res = self._parse(timestr, **kwargs) if res is None: - raise ValueError, "unknown string format" + raise ValueError("unknown string format") repl = {} for attr in ["year", "month", "day", "hour", "minute", "second", "microsecond"]: @@ -317,13 +317,13 @@ class parser: tzdata = tzinfos.get(res.tzname) if isinstance(tzdata, datetime.tzinfo): tzinfo = tzdata - elif isinstance(tzdata, basestring): + elif isinstance(tzdata, str): tzinfo = tz.tzstr(tzdata) elif isinstance(tzdata, int): tzinfo = tz.tzoffset(res.tzname, tzdata) else: - raise ValueError, "offset must be tzinfo subclass, " \ - "tz string, or int offset" + raise ValueError("offset must be tzinfo subclass, " \ + "tz string, or int offset") ret = ret.replace(tzinfo=tzinfo) elif res.tzname and res.tzname in time.tzname: ret = ret.replace(tzinfo=tz.tzlocal()) diff --git a/src/libs/python/bongo/external/dateutil/relativedelta.py b/src/libs/python/bongo/external/dateutil/relativedelta.py index cdb63b3..dc6c76e 100644 --- a/src/libs/python/bongo/external/dateutil/relativedelta.py +++ b/src/libs/python/bongo/external/dateutil/relativedelta.py @@ -115,7 +115,7 @@ Here is the behavior of operations with relativedelta: if dt1 and dt2: if not isinstance(dt1, datetime.date) or \ not isinstance(dt2, datetime.date): - raise TypeError, "relativedelta only diffs datetime/date" + raise TypeError("relativedelta only diffs datetime/date") if type(dt1) is not type(dt2): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) @@ -195,7 +195,7 @@ Here is the behavior of operations with relativedelta: self.day = yday-ydayidx[idx-1] break else: - raise ValueError, "invalid year day (%d)" % yday + raise ValueError("invalid year day (%d)" % yday) self._fix() @@ -244,7 +244,7 @@ Here is the behavior of operations with relativedelta: def __radd__(self, other): if not isinstance(other, datetime.date): - raise TypeError, "unsupported type for add operation" + raise TypeError("unsupported type for add operation") elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years @@ -290,7 +290,7 @@ Here is the behavior of operations with relativedelta: def __add__(self, other): if not isinstance(other, relativedelta): - raise TypeError, "unsupported type for add operation" + raise TypeError("unsupported type for add operation") return relativedelta(years=other.years+self.years, months=other.months+self.months, days=other.days+self.days, @@ -310,7 +310,7 @@ Here is the behavior of operations with relativedelta: def __sub__(self, other): if not isinstance(other, relativedelta): - raise TypeError, "unsupported type for sub operation" + raise TypeError("unsupported type for sub operation") return relativedelta(years=other.years-self.years, months=other.months-self.months, days=other.days-self.days, @@ -346,7 +346,7 @@ Here is the behavior of operations with relativedelta: second=self.second, microsecond=self.microsecond) - def __nonzero__(self): + def __bool__(self): return not (not self.years and not self.months and not self.days and @@ -426,7 +426,7 @@ Here is the behavior of operations with relativedelta: "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: - l.append("%s=%s" % (attr, `value`)) + l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) # vim:ts=4:sw=4:et diff --git a/src/libs/python/bongo/external/dateutil/rrule.py b/src/libs/python/bongo/external/dateutil/rrule.py index 108b536..ec80b81 100644 --- a/src/libs/python/bongo/external/dateutil/rrule.py +++ b/src/libs/python/bongo/external/dateutil/rrule.py @@ -10,7 +10,7 @@ __license__ = "PSF License" import itertools import datetime import calendar -import thread +import _thread import sys __all__ = ["rrule", "rruleset", "rrulestr", @@ -22,10 +22,10 @@ __all__ = ["rrule", "rruleset", "rrulestr", M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30+ [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) M365MASK = list(M366MASK) -M29, M30, M31 = range(1,30), range(1,31), range(1,32) +M29, M30, M31 = list(range(1,30)), list(range(1,31)), list(range(1,32)) MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) MDAY365MASK = list(MDAY366MASK) -M29, M30, M31 = range(-29,0), range(-30,0), range(-31,0) +M29, M30, M31 = list(range(-29,0)), list(range(-30,0)), list(range(-31,0)) NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) NMDAY365MASK = list(NMDAY366MASK) M366RANGE = (0,31,60,91,121,152,182,213,244,274,305,335,366) @@ -41,7 +41,7 @@ M365MASK = tuple(M365MASK) DAILY, HOURLY, MINUTELY, - SECONDLY) = range(7) + SECONDLY) = list(range(7)) # Imported on demand. easter = None @@ -52,7 +52,7 @@ class weekday(object): def __init__(self, weekday, n=None): if n == 0: - raise ValueError, "Can't create weekday with n == 0" + raise ValueError("Can't create weekday with n == 0") self.weekday = weekday self.n = n @@ -83,7 +83,7 @@ class rrulebase: def __init__(self, cache=False): if cache: self._cache = [] - self._cache_lock = thread.allocate_lock() + self._cache_lock = _thread.allocate_lock() self._cache_gen = self._iter() self._cache_complete = False else: @@ -112,7 +112,7 @@ class rrulebase: break try: for j in range(10): - cache.append(gen.next()) + cache.append(next(gen)) except StopIteration: self._cache_gen = gen = None self._cache_complete = True @@ -133,13 +133,13 @@ class rrulebase: else: return list(itertools.islice(self, item.start or 0, - item.stop or sys.maxint, + item.stop or sys.maxsize, item.step or 1)) elif item >= 0: gen = iter(self) try: for i in range(item+1): - res = gen.next() + res = next(gen) except StopIteration: raise IndexError return res @@ -761,7 +761,7 @@ class _iterinfo(object): self.lastmonth = month def ydayset(self, year, month, day): - return range(self.yearlen), 0, self.yearlen + return list(range(self.yearlen)), 0, self.yearlen def mdayset(self, year, month, day): set = [None]*self.yearlen @@ -826,7 +826,7 @@ class rruleset(rrulebase): self.genlist = genlist self.gen = gen - def next(self): + def __next__(self): try: self.dt = self.gen() except StopIteration: @@ -857,14 +857,14 @@ class rruleset(rrulebase): def _iter(self): rlist = [] self._rdate.sort() - self._genitem(rlist, iter(self._rdate).next) - for gen in [iter(x).next for x in self._rrule]: + self._genitem(rlist, iter(self._rdate).__next__) + for gen in [iter(x).__next__ for x in self._rrule]: self._genitem(rlist, gen) rlist.sort() exlist = [] self._exdate.sort() - self._genitem(exlist, iter(self._exdate).next) - for gen in [iter(x).next for x in self._exrule]: + self._genitem(exlist, iter(self._exdate).__next__) + for gen in [iter(x).__next__ for x in self._exrule]: self._genitem(exlist, gen) exlist.sort() lastdt = None @@ -873,13 +873,13 @@ class rruleset(rrulebase): ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: - exlist[0].next() + next(exlist[0]) exlist.sort() if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt - ritem.next() + next(ritem) rlist.sort() self._len = total @@ -925,7 +925,7 @@ class _rrulestr: ignoretz=kwargs.get("ignoretz"), tzinfos=kwargs.get("tzinfos")) except ValueError: - raise ValueError, "invalid until date" + raise ValueError("invalid until date") def _handle_WKST(self, rrkwargs, name, value, **kwargs): rrkwargs["wkst"] = self._weekday_map[value] @@ -952,7 +952,7 @@ class _rrulestr: if line.find(':') != -1: name, value = line.split(':') if name != "RRULE": - raise ValueError, "unknown parameter name" + raise ValueError("unknown parameter name") else: value = line rrkwargs = {} @@ -984,7 +984,7 @@ class _rrulestr: unfold = True s = s.upper() if not s.strip(): - raise ValueError, "empty string" + raise ValueError("empty string") if unfold: lines = s.splitlines() i = 0 @@ -1019,36 +1019,36 @@ class _rrulestr: name, value = line.split(':', 1) parms = name.split(';') if not parms: - raise ValueError, "empty property name" + raise ValueError("empty property name") name = parms[0] parms = parms[1:] if name == "RRULE": for parm in parms: - raise ValueError, "unsupported RRULE parm: "+parm + raise ValueError("unsupported RRULE parm: "+parm) rrulevals.append(value) elif name == "RDATE": for parm in parms: if parm != "VALUE=DATE-TIME": - raise ValueError, "unsupported RDATE parm: "+parm + raise ValueError("unsupported RDATE parm: "+parm) rdatevals.append(value) elif name == "EXRULE": for parm in parms: - raise ValueError, "unsupported EXRULE parm: "+parm + raise ValueError("unsupported EXRULE parm: "+parm) exrulevals.append(value) elif name == "EXDATE": for parm in parms: if parm != "VALUE=DATE-TIME": - raise ValueError, "unsupported RDATE parm: "+parm + raise ValueError("unsupported RDATE parm: "+parm) exdatevals.append(value) elif name == "DTSTART": for parm in parms: - raise ValueError, "unsupported DTSTART parm: "+parm + raise ValueError("unsupported DTSTART parm: "+parm) if not parser: from dateutil import parser dtstart = parser.parse(value, ignoretz=ignoretz, tzinfos=tzinfos) else: - raise ValueError, "unsupported property: "+name + raise ValueError("unsupported property: "+name) if (forceset or len(rrulevals) > 1 or rdatevals or exrulevals or exdatevals): if not parser and (rdatevals or exdatevals): diff --git a/src/libs/python/bongo/external/dateutil/tz.py b/src/libs/python/bongo/external/dateutil/tz.py index a1d6c97..39839e3 100644 --- a/src/libs/python/bongo/external/dateutil/tz.py +++ b/src/libs/python/bongo/external/dateutil/tz.py @@ -75,7 +75,7 @@ class tzoffset(datetime.tzinfo): def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, - `self._name`, + repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ @@ -161,7 +161,7 @@ class _ttinfo(object): for attr in self.__slots__: value = getattr(self, attr) if value is not None: - l.append("%s=%s" % (attr, `value`)) + l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) def __eq__(self, other): @@ -194,13 +194,13 @@ class tzfile(datetime.tzinfo): # ftp://elsie.nci.nih.gov/pub/tz*.tar.gz def __init__(self, fileobj): - if isinstance(fileobj, basestring): + if isinstance(fileobj, str): self._filename = fileobj fileobj = open(fileobj) elif hasattr(fileobj, "name"): self._filename = fileobj.name else: - self._filename = `fileobj` + self._filename = repr(fileobj) # From tzfile(5): # @@ -213,7 +213,7 @@ class tzfile(datetime.tzinfo): # of the value is written first). if fileobj.read(4) != "TZif": - raise ValueError, "magic not found" + raise ValueError("magic not found") fileobj.read(16) @@ -460,11 +460,11 @@ class tzfile(datetime.tzinfo): def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, `self._filename`) + return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename): - raise ValueError, "Unpickable %s class" % self.__class__.__name__ + raise ValueError("Unpickable %s class" % self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): @@ -556,7 +556,7 @@ class tzstr(tzrange): res = parser._parsetz(s) if res is None: - raise ValueError, "unknown string format" + raise ValueError("unknown string format") # We must initialize it first, since _delta() needs # _std_offset and _dst_offset set. Use False in start/end @@ -610,7 +610,7 @@ class tzstr(tzrange): return relativedelta.relativedelta(**kwargs) def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, `self._s`) + return "%s(%s)" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp: def __init__(self, tzoffsetfrom, tzoffsetto, isdst, @@ -680,7 +680,7 @@ class _tzicalvtz(datetime.tzinfo): return self._find_comp(dt).tzname def __repr__(self): - return "" % `self._tzid` + return "" % repr(self._tzid) __reduce__ = object.__reduce__ @@ -690,24 +690,24 @@ class tzical: if not rrule: from dateutil import rrule - if isinstance(fileobj, basestring): + if isinstance(fileobj, str): self._s = fileobj fileobj = open(fileobj) elif hasattr(fileobj, "name"): self._s = fileobj.name else: - self._s = `fileobj` + self._s = repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): - return self._vtz.keys() + return list(self._vtz.keys()) def get(self, tzid=None): if tzid is None: - keys = self._vtz.keys() + keys = list(self._vtz.keys()) if len(keys) == 0: raise "no timezones defined" elif len(keys) > 1: @@ -718,7 +718,7 @@ class tzical: def _parse_offset(self, s): s = s.strip() if not s: - raise ValueError, "empty offset" + raise ValueError("empty offset") if s[0] in ('+', '-'): signal = (-1,+1)[s[0]=='+'] s = s[1:] @@ -729,12 +729,12 @@ class tzical: elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: - raise ValueError, "invalid offset: "+s + raise ValueError("invalid offset: "+s) def _parse_rfc(self, s): lines = s.splitlines() if not lines: - raise ValueError, "empty string" + raise ValueError("empty string") # Unfold i = 0 @@ -756,7 +756,7 @@ class tzical: name, value = line.split(':', 1) parms = name.split(';') if not parms: - raise ValueError, "empty property name" + raise ValueError("empty property name") name = parms[0].upper() parms = parms[1:] if invtz: @@ -765,7 +765,7 @@ class tzical: # Process component pass else: - raise ValueError, "unknown component: "+value + raise ValueError("unknown component: "+value) comptype = value founddtstart = False tzoffsetfrom = None @@ -775,27 +775,21 @@ class tzical: elif name == "END": if value == "VTIMEZONE": if comptype: - raise ValueError, \ - "component not closed: "+comptype + raise ValueError("component not closed: "+comptype) if not tzid: - raise ValueError, \ - "mandatory TZID not found" + raise ValueError("mandatory TZID not found") if not comps: - raise ValueError, \ - "at least one component is needed" + raise ValueError("at least one component is needed") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value == comptype: if not founddtstart: - raise ValueError, \ - "mandatory DTSTART not found" + raise ValueError("mandatory DTSTART not found") if tzoffsetfrom is None: - raise ValueError, \ - "mandatory TZOFFSETFROM not found" + raise ValueError("mandatory TZOFFSETFROM not found") if tzoffsetto is None: - raise ValueError, \ - "mandatory TZOFFSETFROM not found" + raise ValueError("mandatory TZOFFSETFROM not found") # Process component rr = None if rrulelines: @@ -809,8 +803,7 @@ class tzical: comps.append(comp) comptype = None else: - raise ValueError, \ - "invalid component end: "+value + raise ValueError("invalid component end: "+value) elif comptype: if name == "DTSTART": rrulelines.append(line) @@ -819,40 +812,36 @@ class tzical: rrulelines.append(line) elif name == "TZOFFSETFROM": if parms: - raise ValueError, \ - "unsupported %s parm: %s "%(name, parms[0]) + raise ValueError("unsupported %s parm: %s "%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == "TZOFFSETTO": if parms: - raise ValueError, \ - "unsupported TZOFFSETTO parm: "+parms[0] + raise ValueError("unsupported TZOFFSETTO parm: "+parms[0]) tzoffsetto = self._parse_offset(value) elif name == "TZNAME": if parms: - raise ValueError, \ - "unsupported TZNAME parm: "+parms[0] + raise ValueError("unsupported TZNAME parm: "+parms[0]) tzname = value elif name == "COMMENT": pass else: - raise ValueError, "unsupported property: "+name + raise ValueError("unsupported property: "+name) else: if name == "TZID": if parms: - raise ValueError, \ - "unsupported TZID parm: "+parms[0] + raise ValueError("unsupported TZID parm: "+parms[0]) tzid = value elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): pass else: - raise ValueError, "unsupported property: "+name + raise ValueError("unsupported property: "+name) elif name == "BEGIN" and value == "VTIMEZONE": tzid = None comps = [] invtz = True def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, `self._s`) + return "%s(%s)" % (self.__class__.__name__, repr(self._s)) if sys.platform != "win32": TZFILES = ["/etc/localtime", "localtime"] diff --git a/src/libs/python/bongo/external/dateutil/tzwin.py b/src/libs/python/bongo/external/dateutil/tzwin.py index 073e0ff..b378f59 100644 --- a/src/libs/python/bongo/external/dateutil/tzwin.py +++ b/src/libs/python/bongo/external/dateutil/tzwin.py @@ -1,7 +1,7 @@ # This code was originally contributed by Jeffrey Harris. import datetime import struct -import _winreg +import winreg __author__ = "Jeffrey Harris & Gustavo Niemeyer " @@ -15,9 +15,9 @@ TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" def _settzkeyname(): global TZKEYNAME - handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: - _winreg.OpenKey(handle, TZKEYNAMENT).Close() + winreg.OpenKey(handle, TZKEYNAMENT).Close() TZKEYNAME = TZKEYNAMENT except WindowsError: TZKEYNAME = TZKEYNAME9X @@ -49,10 +49,10 @@ class tzwinbase(datetime.tzinfo): def list(): """Return a list of all time zones known to the system.""" - handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) - tzkey = _winreg.OpenKey(handle, TZKEYNAME) - result = [_winreg.EnumKey(tzkey, i) - for i in range(_winreg.QueryInfoKey(tzkey)[0])] + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) + tzkey = winreg.OpenKey(handle, TZKEYNAME) + result = [winreg.EnumKey(tzkey, i) + for i in range(winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result @@ -79,8 +79,8 @@ class tzwin(tzwinbase): def __init__(self, name): self._name = name - handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) - tzkey = _winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name)) + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) + tzkey = winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name)) keydict = valuestodict(tzkey) tzkey.Close() handle.Close() @@ -118,9 +118,9 @@ class tzwinlocal(tzwinbase): def __init__(self): - handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) - tzlocalkey = _winreg.OpenKey(handle, TZLOCALKEYNAME) + tzlocalkey = winreg.OpenKey(handle, TZLOCALKEYNAME) keydict = valuestodict(tzlocalkey) tzlocalkey.Close() @@ -128,7 +128,7 @@ class tzwinlocal(tzwinbase): self._dstname = keydict["DaylightName"].encode("iso-8859-1") try: - tzkey = _winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname)) + tzkey = winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname)) _keydict = valuestodict(tzkey) self._display = _keydict["Display"] tzkey.Close() @@ -165,7 +165,7 @@ def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek 5 means last instance""" first = datetime.datetime(year, month, 1, hour, minute) weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1)) - for n in xrange(whichweek): + for n in range(whichweek): dt = weekdayone+(whichweek-n)*ONEWEEK if dt.month == month: return dt @@ -173,8 +173,8 @@ def picknthweekday(year, month, dayofweek, hour, minute, whichweek): def valuestodict(key): """Convert a registry key's values to a dictionary.""" dict = {} - size = _winreg.QueryInfoKey(key)[1] + size = winreg.QueryInfoKey(key)[1] for i in range(size): - data = _winreg.EnumValue(key, i) + data = winreg.EnumValue(key, i) dict[data[0]] = data[1] return dict diff --git a/src/libs/python/bongo/external/email/_parseaddr.py b/src/libs/python/bongo/external/email/_parseaddr.py index a08c43e..8047df2 100644 --- a/src/libs/python/bongo/external/email/_parseaddr.py +++ b/src/libs/python/bongo/external/email/_parseaddr.py @@ -109,7 +109,7 @@ def parsedate_tz(data): return None tzoffset = None tz = tz.upper() - if _timezones.has_key(tz): + if tz in _timezones: tzoffset = _timezones[tz] else: try: diff --git a/src/libs/python/bongo/external/email/base64mime.py b/src/libs/python/bongo/external/email/base64mime.py index 11d0af6..4fa8563 100644 --- a/src/libs/python/bongo/external/email/base64mime.py +++ b/src/libs/python/bongo/external/email/base64mime.py @@ -146,7 +146,7 @@ def encode(s, binary=True, maxlinelen=76, eol=NL): # BAW: should encode() inherit b2a_base64()'s dubious behavior in # adding a newline to the encoded string? enc = b2a_base64(s[i:i + max_unencoded]) - if enc.endswith(NL) and eol <> NL: + if enc.endswith(NL) and eol != NL: enc = enc[:-1] + eol encvec.append(enc) return EMPTYSTRING.join(encvec) diff --git a/src/libs/python/bongo/external/email/charset.py b/src/libs/python/bongo/external/email/charset.py index d91f5d7..3205b50 100644 --- a/src/libs/python/bongo/external/email/charset.py +++ b/src/libs/python/bongo/external/email/charset.py @@ -199,10 +199,10 @@ class Charset: # is already a unicode, we leave it at that, but ensure that the # charset is ASCII, as the standard (RFC XXX) requires. try: - if isinstance(input_charset, unicode): + if isinstance(input_charset, str): input_charset.encode('ascii') else: - input_charset = unicode(input_charset, 'ascii') + input_charset = str(input_charset, 'ascii') except UnicodeError: raise errors.CharsetError(input_charset) input_charset = input_charset.lower() @@ -260,7 +260,7 @@ class Charset: Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise. """ - assert self.body_encoding <> SHORTEST + assert self.body_encoding != SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: @@ -270,8 +270,8 @@ class Charset: def convert(self, s): """Convert a string from the input_codec to the output_codec.""" - if self.input_codec <> self.output_codec: - return unicode(s, self.input_codec).encode(self.output_codec) + if self.input_codec != self.output_codec: + return str(s, self.input_codec).encode(self.output_codec) else: return s @@ -288,10 +288,10 @@ class Charset: Characters that could not be converted to Unicode will be replaced with the Unicode replacement character U+FFFD. """ - if isinstance(s, unicode) or self.input_codec is None: + if isinstance(s, str) or self.input_codec is None: return s try: - return unicode(s, self.input_codec, 'replace') + return str(s, self.input_codec, 'replace') except LookupError: # Input codec not installed on system, so return the original # string unchanged. @@ -314,7 +314,7 @@ class Charset: codec = self.output_codec else: codec = self.input_codec - if not isinstance(ustr, unicode) or codec is None: + if not isinstance(ustr, str) or codec is None: return ustr try: return ustr.encode(codec, 'replace') diff --git a/src/libs/python/bongo/external/email/feedparser.py b/src/libs/python/bongo/external/email/feedparser.py index 4284833..22e8211 100644 --- a/src/libs/python/bongo/external/email/feedparser.py +++ b/src/libs/python/bongo/external/email/feedparser.py @@ -123,7 +123,7 @@ class BufferedSubFile(object): def __iter__(self): return self - def next(self): + def __next__(self): line = self.readline() if line == '': raise StopIteration @@ -140,7 +140,7 @@ class FeedParser: self._payloadfactory = _payloadfactory self._input = BufferedSubFile() self._msgstack = [] - self._parse = self._parsegen().next + self._parse = self._parsegen().__next__ self._cur = None self._last = None self._headersonly = False diff --git a/src/libs/python/bongo/external/email/filegenerator.py b/src/libs/python/bongo/external/email/filegenerator.py index c1cee65..1e5a43e 100644 --- a/src/libs/python/bongo/external/email/filegenerator.py +++ b/src/libs/python/bongo/external/email/filegenerator.py @@ -10,7 +10,7 @@ from bongo.external.email.header import Header from bongo.external.email.payloads import Payload import bongo.external.email.generator -from cStringIO import StringIO +from io import StringIO UNDERSCORE = '_' NL = '\n' @@ -19,7 +19,7 @@ fcre = re.compile(r'^From ', re.MULTILINE) def _is8bitstring(s): if isinstance(s, str): try: - unicode(s, 'us-ascii') + str(s, 'us-ascii') except UnicodeError: return True return False @@ -39,7 +39,7 @@ class FileGenerator : ufrom = msg.get_unixfrom() if not ufrom : ufrom = 'From nobody ' + time.ctime(time.time()) - print >> self._fp, ufrom + print(ufrom, file=self._fp) self._write(msg) def write(self, buf, manglefrom=True) : @@ -95,14 +95,14 @@ class FileGenerator : if not boundary : msg.set_boundary(bongo.external.email.generator._make_boundary()) - for h, v in msg.items(): - print >> self._fp, '%s:' % h, + for h, v in list(msg.items()): + print('%s:' % h, end=' ', file=self._fp) if self._maxheaderlen == 0: # Explicit no-wrapping - print >> self._fp, v + print(v, file=self._fp) elif isinstance(v, Header): # Header instances know what to do - print >> self._fp, v.encode() + print(v.encode(), file=self._fp) elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this @@ -110,15 +110,15 @@ class FileGenerator : # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. - print >> self._fp, v + print(v, file=self._fp) else: # Header's got lots of smarts, so use it. - print >> self._fp, Header( + print(Header( v, maxlinelen=self._maxheaderlen, - header_name=h, continuation_ws='\t').encode() + header_name=h, continuation_ws='\t').encode(), file=self._fp) # A blank line always separates headers from body if trailing_newline : - print >> self._fp + print(file=self._fp) # # Handlers for writing types and subtypes @@ -147,16 +147,16 @@ class FileGenerator : self.flush() if msg.preamble is not None : - print >> self._fp, msg.preamble + print(msg.preamble, file=self._fp) - print >> self._fp, '--' + boundary + print('--' + boundary, file=self._fp) if isinstance(subparts, list) : first = True for part in subparts : if not first: self.flush() - print >> self._fp, NL + '--' + boundary + print(NL + '--' + boundary, file=self._fp) first = False g = self.clone(self._fp) @@ -165,7 +165,7 @@ class FileGenerator : if msg.epilogue is not None : self.flush() - print >> self._fp + print(file=self._fp) self.write(msg.epilogue, True) def _strip_newline(self) : diff --git a/src/libs/python/bongo/external/email/generator.py b/src/libs/python/bongo/external/email/generator.py index dd14b0e..a3a0505 100644 --- a/src/libs/python/bongo/external/email/generator.py +++ b/src/libs/python/bongo/external/email/generator.py @@ -12,7 +12,7 @@ import time import random import warnings -from cStringIO import StringIO +from io import StringIO from bongo.external.email.header import Header from bongo.external.email.filegenerator import FileGenerator @@ -24,7 +24,7 @@ fcre = re.compile(r'^From ', re.MULTILINE) def _is8bitstring(s): if isinstance(s, str): try: - unicode(s, 'us-ascii') + str(s, 'us-ascii') except UnicodeError: return True return False @@ -83,7 +83,7 @@ class OldGenerator: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) - print >> self._fp, ufrom + print(ufrom, file=self._fp) self._write(msg) def clone(self, fp): @@ -142,14 +142,14 @@ class OldGenerator: # def _write_headers(self, msg): - for h, v in msg.items(): - print >> self._fp, '%s:' % h, + for h, v in list(msg.items()): + print('%s:' % h, end=' ', file=self._fp) if self._maxheaderlen == 0: # Explicit no-wrapping - print >> self._fp, v + print(v, file=self._fp) elif isinstance(v, Header): # Header instances know what to do - print >> self._fp, v.encode() + print(v.encode(), file=self._fp) elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this @@ -157,14 +157,14 @@ class OldGenerator: # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. - print >> self._fp, v + print(v, file=self._fp) else: # Header's got lots of smarts, so use it. - print >> self._fp, Header( + print(Header( v, maxlinelen=self._maxheaderlen, - header_name=h, continuation_ws='\t').encode() + header_name=h, continuation_ws='\t').encode(), file=self._fp) # A blank line always separates headers from body - print >> self._fp + print(file=self._fp) # # Handlers for writing types and subtypes @@ -174,7 +174,7 @@ class OldGenerator: payload = msg.get_payload() if payload is None: return - if not isinstance(payload, basestring): + if not isinstance(payload, str): raise TypeError('string payload expected: %s' % type(payload)) if self._mangle_from_: payload = fcre.sub('>From ', payload) @@ -191,7 +191,7 @@ class OldGenerator: subparts = msg.get_payload() if subparts is None: subparts = [] - elif isinstance(subparts, basestring): + elif isinstance(subparts, str): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return @@ -214,13 +214,13 @@ class OldGenerator: # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. - if msg.get_boundary() <> boundary: + if msg.get_boundary() != boundary: msg.set_boundary(boundary) # If there's a preamble, write it out, with a trailing CRLF if msg.preamble is not None: - print >> self._fp, msg.preamble + print(msg.preamble, file=self._fp) # dash-boundary transport-padding CRLF - print >> self._fp, '--' + boundary + print('--' + boundary, file=self._fp) # body-part if msgtexts: self._fp.write(msgtexts.pop(0)) @@ -229,13 +229,13 @@ class OldGenerator: # --> CRLF body-part for body_part in msgtexts: # delimiter transport-padding CRLF - print >> self._fp, NL + '--' + boundary + print(NL + '--' + boundary, file=self._fp) # body-part self._fp.write(body_part) # close-delimiter transport-padding self._fp.write(NL + '--' + boundary + '--') if msg.epilogue is not None: - print >> self._fp + print(file=self._fp) self._fp.write(msg.epilogue) def _handle_message_delivery_status(self, msg): @@ -312,12 +312,12 @@ class DecodedGenerator(Generator): for part in msg.walk(): maintype = part.get_content_maintype() if maintype == 'text': - print >> self, part.get_payload(decode=True) + print(part.get_payload(decode=True), file=self) elif maintype == 'multipart': # Just skip this pass else: - print >> self, self._fmt % { + print(self._fmt % { 'type' : part.get_content_type(), 'maintype' : part.get_content_maintype(), 'subtype' : part.get_content_subtype(), @@ -326,18 +326,18 @@ class DecodedGenerator(Generator): '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), - } + }, file=self) self.flush() # Helper -_width = len(repr(sys.maxint-1)) +_width = len(repr(sys.maxsize-1)) _fmt = '%%0%dd' % _width def _make_boundary(text=None): # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. - token = random.randrange(sys.maxint) + token = random.randrange(sys.maxsize) boundary = ('=' * 15) + (_fmt % token) + '==' if text is None: return boundary diff --git a/src/libs/python/bongo/external/email/header.py b/src/libs/python/bongo/external/email/header.py index 0e3d18d..ce34a31 100644 --- a/src/libs/python/bongo/external/email/header.py +++ b/src/libs/python/bongo/external/email/header.py @@ -21,9 +21,9 @@ from bongo.external.email.charset import Charset NL = '\n' SPACE = ' ' -USPACE = u' ' +USPACE = ' ' SPACE8 = ' ' * 8 -UEMPTYSTRING = u'' +UEMPTYSTRING = '' MAXLINELEN = 76 @@ -209,7 +209,7 @@ class Header: elif nextcs not in (None, 'us-ascii'): uchunks.append(USPACE) lastcs = nextcs - uchunks.append(unicode(s, str(charset))) + uchunks.append(str(s, str(charset))) return UEMPTYSTRING.join(uchunks) # Rich comparison operators for equality only. BAW: does it make sense to @@ -248,7 +248,7 @@ class Header: elif not isinstance(charset, Charset): charset = Charset(charset) # If the charset is our faux 8bit charset, leave the string unchanged - if charset <> '8bit': + if charset != '8bit': # We need to test that the string can be converted to unicode and # back to a byte string, given the input and output codecs of the # charset. @@ -256,13 +256,13 @@ class Header: # Possibly raise UnicodeError if the byte string can't be # converted to a unicode with the input codec of the charset. incodec = charset.input_codec or 'us-ascii' - ustr = unicode(s, incodec, errors) + ustr = str(s, incodec, errors) # Now make sure that the unicode could be converted back to a # byte string with the output codec, which may be different # than the iput coded. Still, use the original byte string. outcodec = charset.output_codec or 'us-ascii' ustr.encode(outcodec, errors) - elif isinstance(s, unicode): + elif isinstance(s, str): # Now we have to be sure the unicode string can be converted # to a byte string with a reasonable output codec. We want to # use the byte string in the chunk. @@ -326,7 +326,7 @@ class Header: def _split_ascii(self, s, charset, firstlen, splitchars): chunks = _split_ascii(s, firstlen, self._maxlinelen, self._continuation_ws, splitchars) - return zip(chunks, [charset]*len(chunks)) + return list(zip(chunks, [charset]*len(chunks))) def _encode_chunks(self, newchunks, maxlinelen): # MIME-encode a header with many different charsets and/or encodings. @@ -454,7 +454,7 @@ def _split_ascii(s, firstlen, restlen, continuation_ws, splitchars): # If this part is longer than maxlen and we aren't already # splitting on whitespace, try to recursively split this line # on whitespace. - if partlen > maxlen and ch <> ' ': + if partlen > maxlen and ch != ' ': subl = _split_ascii(part, maxlen, restlen, continuation_ws, ' ') lines.extend(subl[:-1]) diff --git a/src/libs/python/bongo/external/email/iterators.py b/src/libs/python/bongo/external/email/iterators.py index e99f228..eb4cd67 100644 --- a/src/libs/python/bongo/external/email/iterators.py +++ b/src/libs/python/bongo/external/email/iterators.py @@ -12,7 +12,7 @@ __all__ = [ ] import sys -from cStringIO import StringIO +from io import StringIO @@ -39,7 +39,7 @@ def body_line_iterator(msg, decode=False): """ for subpart in msg.walk(): payload = subpart.get_payload(decode=decode) - if isinstance(payload, basestring): + if isinstance(payload, str): for line in StringIO(payload): yield line @@ -63,11 +63,11 @@ def _structure(msg, fp=None, level=0, include_default=False): if fp is None: fp = sys.stdout tab = ' ' * (level * 4) - print >> fp, tab + msg.get_content_type(), + print(tab + msg.get_content_type(), end=' ', file=fp) if include_default: - print >> fp, '[%s]' % msg.get_default_type() + print('[%s]' % msg.get_default_type(), file=fp) else: - print >> fp + print(file=fp) if msg.is_multipart(): for subpart in msg.get_payload(): _structure(subpart, fp, level+1, include_default) diff --git a/src/libs/python/bongo/external/email/message.py b/src/libs/python/bongo/external/email/message.py index ee883e3..6bc4a5a 100644 --- a/src/libs/python/bongo/external/email/message.py +++ b/src/libs/python/bongo/external/email/message.py @@ -7,7 +7,7 @@ __all__ = ['Message'] import re -from cStringIO import StringIO +from io import StringIO # Intrapackage imports import bongo.external.email.charset @@ -216,7 +216,7 @@ class Message: elif isinstance(self._payload, payloads.Payload) or isinstance(self._payload, list) : payload = self._payload else : - print "unsupported payload type: %s" % (str(self._payload)) + print("unsupported payload type: %s" % (str(self._payload))) raise TypeError('unsupported payload type for iterating') return payload @@ -229,7 +229,7 @@ class Message: """ if isinstance(payload, payloads.Payload): if payload.encoding: - if self.has_key('Content-Transfer-Encoding') : + if 'Content-Transfer-Encoding' in self : self.replace_header('Content-Transfer-Encoding', payload.encoding) else : self['Content-Transfer-Encoding'] = payload.encoding @@ -258,7 +258,7 @@ class Message: leftover = None for buf in payload.iter(subdecode): if encode : - if isinstance(buf, unicode) : + if isinstance(buf, str) : buf = buf.encode(charset.get_output_charset()) if charset.body_encoding == bongo.external.email.charset.BASE64 : @@ -310,9 +310,9 @@ class Message: # Charset constructor? self._charset = charset - if not self.has_key('MIME-Version'): + if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') - if not self.has_key('Content-Type'): + if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: @@ -369,7 +369,7 @@ class Message: name = name.lower() newheaders = [] for k, v in self._headers: - if k.lower() <> name: + if k.lower() != name: newheaders.append((k, v)) self._headers = newheaders @@ -458,7 +458,7 @@ class Message: msg.add_header('content-disposition', 'attachment', filename='bud.gif') """ parts = [] - for k, v in _params.items(): + for k, v in list(_params.items()): if v is None: parts.append(k.replace('_', '-')) else: @@ -475,7 +475,7 @@ class Message: raised. """ _name = _name.lower() - for i, (k, v) in zip(range(len(self._headers)), self._headers): + for i, (k, v) in zip(list(range(len(self._headers))), self._headers): if k.lower() == _name: self._headers[i] = (k, _value) break @@ -506,7 +506,7 @@ class Message: return self.get_default_type() ctype = paramre.split(value)[0].lower().strip() # RFC 2045, section 5.2 says if its invalid, use text/plain - if ctype.count('/') <> 1: + if ctype.count('/') != 1: return 'text/plain' return ctype @@ -615,7 +615,7 @@ class Message: VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. """ - if not self.has_key(header): + if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): @@ -646,7 +646,7 @@ class Message: if not isinstance(value, tuple) and charset: value = (charset, language, value) - if not self.has_key(header) and header.lower() == 'content-type': + if header not in self and header.lower() == 'content-type': ctype = 'text/plain' else: ctype = self.get(header) @@ -669,7 +669,7 @@ class Message: ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) - if ctype <> self.get(header): + if ctype != self.get(header): del self[header] self[header] = ctype @@ -681,17 +681,17 @@ class Message: False. Optional header specifies an alternative to the Content-Type header. """ - if not self.has_key(header): + if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): - if p.lower() <> param.lower(): + if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) - if new_ctype <> self.get(header): + if new_ctype != self.get(header): del self[header] self[header] = new_ctype @@ -717,7 +717,7 @@ class Message: if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' - if not self.has_key(header): + if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) @@ -822,12 +822,12 @@ class Message: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. - charset = unicode(charset[2], pcharset).encode('us-ascii') + charset = str(charset[2], pcharset).encode('us-ascii') except (LookupError, UnicodeError): charset = charset[2] # charset character must be in us-ascii range try: - charset = unicode(charset, 'us-ascii').encode('us-ascii') + charset = str(charset, 'us-ascii').encode('us-ascii') except UnicodeError: return failobj diff --git a/src/libs/python/bongo/external/email/mime/audio.py b/src/libs/python/bongo/external/email/mime/audio.py index 70c9038..d07a9d4 100644 --- a/src/libs/python/bongo/external/email/mime/audio.py +++ b/src/libs/python/bongo/external/email/mime/audio.py @@ -8,7 +8,7 @@ __all__ = ['MIMEAudio'] import sndhdr -from cStringIO import StringIO +from io import StringIO from bongo.external.email import encoders from bongo.external.email.mime.nonmultipart import MIMENonMultipart diff --git a/src/libs/python/bongo/external/email/parser.py b/src/libs/python/bongo/external/email/parser.py index b149f1d..dd0a987 100644 --- a/src/libs/python/bongo/external/email/parser.py +++ b/src/libs/python/bongo/external/email/parser.py @@ -7,7 +7,7 @@ __all__ = ['Parser', 'HeaderParser'] import warnings -from cStringIO import StringIO +from io import StringIO from bongo.external.email.feedparser import FeedParser from bongo.external.email.message import Message diff --git a/src/libs/python/bongo/external/email/quoprimime.py b/src/libs/python/bongo/external/email/quoprimime.py index 0edbca1..b3846d2 100644 --- a/src/libs/python/bongo/external/email/quoprimime.py +++ b/src/libs/python/bongo/external/email/quoprimime.py @@ -287,7 +287,7 @@ def decode(encoded, eol=NL): n = len(line) while i < n: c = line[i] - if c <> '=': + if c != '=': decoded += c i += 1 # Otherwise, c == "=". Are we at the end of the line? If so, add diff --git a/src/libs/python/bongo/external/email/test/test_email.py b/src/libs/python/bongo/external/email/test/test_email.py index e9f72b8..3a873e9 100644 --- a/src/libs/python/bongo/external/email/test/test_email.py +++ b/src/libs/python/bongo/external/email/test/test_email.py @@ -9,7 +9,7 @@ import base64 import difflib import unittest import warnings -from cStringIO import StringIO +from io import StringIO import bongo.external.email @@ -51,13 +51,13 @@ def openfile(filename, mode='r'): class TestEmailBase(unittest.TestCase): def ndiffAssertEqual(self, first, second): """Like failUnlessEqual except use ndiff for readable output.""" - if first <> second: + if first != second: sfirst = str(first) ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) fp = StringIO() - print >> fp, NL, NL.join(diff) - raise self.failureException, fp.getvalue() + print(NL, NL.join(diff), file=fp) + raise self.failureException(fp.getvalue()) def _msgobj(self, filename): fp = openfile(findfile(filename)) @@ -163,7 +163,7 @@ class TestMessageAPI(TestEmailBase): # header appears fifth. msg = self._msgobj('msg_01.txt') msg.set_boundary('BOUNDARY') - header, value = msg.items()[4] + header, value = list(msg.items())[4] eq(header.lower(), 'content-type') eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"') # This one has a Content-Type: header, with a boundary, stuck in the @@ -171,7 +171,7 @@ class TestMessageAPI(TestEmailBase): # be fifth. msg = self._msgobj('msg_04.txt') msg.set_boundary('BOUNDARY') - header, value = msg.items()[4] + header, value = list(msg.items())[4] eq(header.lower(), 'content-type') eq(value, 'multipart/mixed; boundary="BOUNDARY"') # And this one has no Content-Type: header at all. @@ -239,12 +239,12 @@ class TestMessageAPI(TestEmailBase): msg['From'] = 'Me' msg['to'] = 'You' # Check for case insensitivity - self.failUnless('from' in msg) - self.failUnless('From' in msg) - self.failUnless('FROM' in msg) - self.failUnless('to' in msg) - self.failUnless('To' in msg) - self.failUnless('TO' in msg) + self.assertTrue('from' in msg) + self.assertTrue('From' in msg) + self.assertTrue('FROM' in msg) + self.assertTrue('to' in msg) + self.assertTrue('To' in msg) + self.assertTrue('TO' in msg) def test_as_string(self): eq = self.assertEqual @@ -257,7 +257,7 @@ class TestMessageAPI(TestEmailBase): eq(text, msg.as_string()) fullrepr = str(msg) lines = fullrepr.split('\n') - self.failUnless(lines[0].startswith('From ')) + self.assertTrue(lines[0].startswith('From ')) eq(text, NL.join(lines[1:])) def test_bad_param(self): @@ -328,10 +328,10 @@ class TestMessageAPI(TestEmailBase): def test_has_key(self): msg = bongo.external.email.message_from_string('Header: exists') - self.failUnless(msg.has_key('header')) - self.failUnless(msg.has_key('Header')) - self.failUnless(msg.has_key('HEADER')) - self.failIf(msg.has_key('headeri')) + self.assertTrue('header' in msg) + self.assertTrue('Header' in msg) + self.assertTrue('HEADER' in msg) + self.assertFalse('headeri' in msg) def test_set_param(self): eq = self.assertEqual @@ -483,15 +483,15 @@ class TestMessageAPI(TestEmailBase): msg.add_header('First', 'One') msg.add_header('Second', 'Two') msg.add_header('Third', 'Three') - eq(msg.keys(), ['First', 'Second', 'Third']) - eq(msg.values(), ['One', 'Two', 'Three']) + eq(list(msg.keys()), ['First', 'Second', 'Third']) + eq(list(msg.values()), ['One', 'Two', 'Three']) msg.replace_header('Second', 'Twenty') - eq(msg.keys(), ['First', 'Second', 'Third']) - eq(msg.values(), ['One', 'Twenty', 'Three']) + eq(list(msg.keys()), ['First', 'Second', 'Third']) + eq(list(msg.values()), ['One', 'Twenty', 'Three']) msg.add_header('First', 'Eleven') msg.replace_header('First', 'One Hundred') - eq(msg.keys(), ['First', 'Second', 'Third', 'First']) - eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven']) + eq(list(msg.keys()), ['First', 'Second', 'Third', 'First']) + eq(list(msg.values()), ['One Hundred', 'Twenty', 'Three', 'Eleven']) self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing') def test_broken_base64_payload(self): @@ -577,7 +577,7 @@ bug demonstration utf8 = Charset("utf-8") g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. " cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. " - utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") + utf8_head = "\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") h = Header(g_head, g, header_name='Subject') h.append(cz_head, cz) h.append(utf8_head, utf8) @@ -915,7 +915,7 @@ class TestMIMEAudio(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], @@ -958,7 +958,7 @@ class TestMIMEImage(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._im.add_header('Content-Disposition', 'attachment', filename='dingusfish.gif') eq(self._im['content-disposition'], @@ -985,7 +985,7 @@ class TestMIMEText(unittest.TestCase): def test_types(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue eq(self._msg.get_content_type(), 'text/plain') eq(self._msg.get_param('charset'), 'us-ascii') missing = [] @@ -995,7 +995,7 @@ class TestMIMEText(unittest.TestCase): def test_payload(self): self.assertEqual(self._msg.get_payload(), 'hello there') - self.failUnless(not self._msg.is_multipart()) + self.assertTrue(not self._msg.is_multipart()) def test_charset(self): eq = self.assertEqual @@ -1050,7 +1050,7 @@ This is the dingus fish. def test_hierarchy(self): # convenience eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue raises = self.assertRaises # tests m = self._msg @@ -1364,7 +1364,7 @@ Content-Type: text/plain -- XXXX-- ''') - self.failUnless(msg.is_multipart()) + self.assertTrue(msg.is_multipart()) eq(msg.get_boundary(), ' XXXX') eq(len(msg.get_payload()), 2) @@ -1380,7 +1380,7 @@ Content-Transfer-Encoding: base64 YXNkZg== --===============0012394164==--""") - self.assertEquals(m.get_payload(0).get_payload(), 'YXNkZg==') + self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==') @@ -1394,7 +1394,7 @@ class TestNonConformant(TestEmailBase): eq(msg.get_content_subtype(), 'plain') def test_same_boundary_inner_outer(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_15.txt') # XXX We can probably eventually do better inner = msg.get_payload(0) @@ -1404,7 +1404,7 @@ class TestNonConformant(TestEmailBase): Errors.StartBoundaryNotFoundDefect)) def test_multipart_no_boundary(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_25.txt') unless(isinstance(msg.get_payload(), str)) self.assertEqual(len(msg.defects), 2) @@ -1462,7 +1462,7 @@ counter to RFC 2822, there's no separating newline here """) def test_lying_multipart(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_41.txt') unless(hasattr(msg, 'defects')) self.assertEqual(len(msg.defects), 2) @@ -1482,7 +1482,7 @@ counter to RFC 2822, there's no separating newline here # [*] This message is missing its start boundary bad = outer.get_payload(1).get_payload(0) self.assertEqual(len(bad.defects), 1) - self.failUnless(isinstance(bad.defects[0], + self.assertTrue(isinstance(bad.defects[0], Errors.StartBoundaryNotFoundDefect)) @@ -1508,7 +1508,7 @@ class TestRFC2047(unittest.TestCase): s = '=?ISO-8859-1?Q?Andr=E9?= Pirard ' dh = decode_header(s) eq(dh, [('Andr\xe9', 'iso-8859-1'), ('Pirard ', None)]) - hu = unicode(make_header(dh)).encode('latin-1') + hu = str(make_header(dh)).encode('latin-1') eq(hu, 'Andr\xe9 Pirard ') def test_whitespace_eater_unicode_2(self): @@ -1518,7 +1518,7 @@ class TestRFC2047(unittest.TestCase): eq(dh, [('The', None), ('quick brown fox', 'iso-8859-1'), ('jumped over the', None), ('lazy dog', 'iso-8859-1')]) hu = make_header(dh).__unicode__() - eq(hu, u'The quick brown fox jumped over the lazy dog') + eq(hu, 'The quick brown fox jumped over the lazy dog') @@ -1536,7 +1536,7 @@ class TestMIMEMessage(TestEmailBase): def test_valid_argument(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue subject = 'A sub-message' m = Message() m['Subject'] = subject @@ -1580,20 +1580,20 @@ Here is the body of the message. def test_parse_message_rfc822(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_11.txt') eq(msg.get_content_type(), 'message/rfc822') payload = msg.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) submsg = payload[0] - self.failUnless(isinstance(submsg, Message)) + self.assertTrue(isinstance(submsg, Message)) eq(submsg['subject'], 'An enclosed message') eq(submsg.get_payload(), 'Here is the body of the message.\n') def test_dsn(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue # msg 16 is a Delivery Status Notification, see RFC 1894 msg = self._msgobj('msg_16.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1855,7 +1855,7 @@ class TestIdempotent(TestEmailBase): eq(text, s.getvalue()) def test_parse_text_message(self): - eq = self.assertEquals + eq = self.assertEqual msg, text = self._msgobj('msg_01.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_content_maintype(), 'text') @@ -1867,7 +1867,7 @@ class TestIdempotent(TestEmailBase): self._idempotent(msg, text) def test_parse_untyped_message(self): - eq = self.assertEquals + eq = self.assertEqual msg, text = self._msgobj('msg_03.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_params(), None) @@ -1939,8 +1939,8 @@ class TestIdempotent(TestEmailBase): self._idempotent(msg, text) def test_content_type(self): - eq = self.assertEquals - unless = self.failUnless + eq = self.assertEqual + unless = self.assertTrue # Get a message object and reset the seek pointer for other tests msg, text = self._msgobj('msg_05.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1962,7 +1962,7 @@ class TestIdempotent(TestEmailBase): eq(msg2.get_payload(), 'Yadda yadda yadda\n') msg3 = msg.get_payload(2) eq(msg3.get_content_type(), 'message/rfc822') - self.failUnless(isinstance(msg3, Message)) + self.assertTrue(isinstance(msg3, Message)) payload = msg3.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) @@ -1971,8 +1971,8 @@ class TestIdempotent(TestEmailBase): eq(msg4.get_payload(), 'Yadda yadda yadda\n') def test_parser(self): - eq = self.assertEquals - unless = self.failUnless + eq = self.assertEqual + unless = self.assertTrue msg, text = self._msgobj('msg_06.txt') # Check some of the outer headers eq(msg.get_content_type(), 'message/rfc822') @@ -1982,9 +1982,9 @@ class TestIdempotent(TestEmailBase): unless(isinstance(payload, list)) eq(len(payload), 1) msg1 = payload[0] - self.failUnless(isinstance(msg1, Message)) + self.assertTrue(isinstance(msg1, Message)) eq(msg1.get_content_type(), 'text/plain') - self.failUnless(isinstance(msg1.get_payload(), str)) + self.assertTrue(isinstance(msg1.get_payload(), str)) eq(msg1.get_payload(), '\n') @@ -2021,7 +2021,7 @@ class TestMiscellaneous(TestEmailBase): fp.close() def test_message_from_string_with_class(self): - unless = self.failUnless + unless = self.assertTrue fp = openfile('msg_01.txt') try: text = fp.read() @@ -2044,7 +2044,7 @@ class TestMiscellaneous(TestEmailBase): unless(isinstance(subpart, MyMessage)) def test_message_from_file_with_class(self): - unless = self.failUnless + unless = self.assertTrue # Create a subclass class MyMessage(Message): pass @@ -2180,7 +2180,7 @@ class TestMiscellaneous(TestEmailBase): def test_charset_richcomparisons(self): eq = self.assertEqual - ne = self.failIfEqual + ne = self.assertNotEqual cset1 = Charset() cset2 = Charset() eq(cset1, 'us-ascii') @@ -2379,8 +2379,8 @@ class TestParsers(TestEmailBase): eq(msg['from'], 'ppp-request@zzz.org') eq(msg['to'], 'ppp@zzz.org') eq(msg.get_content_type(), 'multipart/mixed') - self.failIf(msg.is_multipart()) - self.failUnless(isinstance(msg.get_payload(), str)) + self.assertFalse(msg.is_multipart()) + self.assertTrue(isinstance(msg.get_payload(), str)) def test_whitespace_continuation(self): eq = self.assertEqual @@ -2489,8 +2489,8 @@ Here's the message body eq = self.assertEqual m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody' msg = bongo.external.email.message_from_string(m) - eq(len(msg.keys()), 3) - keys = msg.keys() + eq(len(list(msg.keys())), 3) + keys = list(msg.keys()) keys.sort() eq(keys, ['!"#QUX;~', '>From', 'From']) eq(msg.get_payload(), 'body') @@ -2499,13 +2499,13 @@ Here's the message body eq = self.assertEqual m = '>From foo@example.com 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody' msg = bongo.external.email.message_from_string(m) - eq(len(msg.keys()), 0) + eq(len(list(msg.keys())), 0) def test_rfc2822_one_character_header(self): eq = self.assertEqual m = 'A: first header\nB: second header\nCC: third header\n\nbody' msg = bongo.external.email.message_from_string(m) - headers = msg.keys() + headers = list(msg.keys()) headers.sort() eq(headers, ['A', 'B', 'CC']) eq(msg.get_payload(), 'body') @@ -2599,15 +2599,15 @@ class TestQuopri(unittest.TestCase): def test_header_quopri_check(self): for c in self.hlit: - self.failIf(quopriMIME.header_quopri_check(c)) + self.assertFalse(quopriMIME.header_quopri_check(c)) for c in self.hnon: - self.failUnless(quopriMIME.header_quopri_check(c)) + self.assertTrue(quopriMIME.header_quopri_check(c)) def test_body_quopri_check(self): for c in self.blit: - self.failIf(quopriMIME.body_quopri_check(c)) + self.assertFalse(quopriMIME.body_quopri_check(c)) for c in self.bnon: - self.failUnless(quopriMIME.body_quopri_check(c)) + self.assertTrue(quopriMIME.body_quopri_check(c)) def test_header_quopri_len(self): eq = self.assertEqual @@ -2746,7 +2746,7 @@ class TestCharset(unittest.TestCase): eq('hello w\xf6rld', c.body_encode('hello w\xf6rld')) def test_unicode_charset_name(self): - charset = Charset(u'us-ascii') + charset = Charset('us-ascii') self.assertEqual(str(charset), 'us-ascii') self.assertRaises(Errors.CharsetError, Charset, 'asc\xffii') @@ -2776,7 +2776,7 @@ class TestHeader(TestEmailBase): h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", maxlinelen=76) for l in h.encode(splitchars=' ').split('\n '): - self.failUnless(len(l) <= 76) + self.assertTrue(len(l) <= 76) def test_multilingual(self): eq = self.ndiffAssertEqual @@ -2785,7 +2785,7 @@ class TestHeader(TestEmailBase): utf8 = Charset("utf-8") g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. " cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. " - utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") + utf8_head = "\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") h = Header(g_head, g) h.append(cz_head, cz) h.append(utf8_head, utf8) @@ -2805,7 +2805,7 @@ class TestHeader(TestEmailBase): eq(decode_header(enc), [(g_head, "iso-8859-1"), (cz_head, "iso-8859-2"), (utf8_head, "utf-8")]) - ustr = unicode(h) + ustr = str(h) eq(ustr.encode('utf-8'), 'Die Mieter treten hier ein werden mit einem Foerderband ' 'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen ' @@ -2873,9 +2873,9 @@ A very long line that must get split to something other than at the def test_utf8_shortest(self): eq = self.assertEqual - h = Header(u'p\xf6stal', 'utf-8') + h = Header('p\xf6stal', 'utf-8') eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=') - h = Header(u'\u83ca\u5730\u6642\u592b', 'utf-8') + h = Header('\u83ca\u5730\u6642\u592b', 'utf-8') eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=') def test_bad_8bit_header(self): @@ -3009,7 +3009,7 @@ Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOC ''' msg = bongo.external.email.message_from_string(m) param = msg.get_param('NAME') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual( param, 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm') @@ -3131,7 +3131,7 @@ Content-Disposition: inline; ''' msg = bongo.external.email.message_from_string(m) self.assertEqual(msg.get_filename(), - u'This is even more ***fun*** is it not.pdf\ufffd') + 'This is even more ***fun*** is it not.pdf\ufffd') def test_rfc2231_unknown_encoding(self): m = """\ @@ -3162,7 +3162,7 @@ Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\" """ msg = bongo.external.email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "Frank's Document") def test_rfc2231_tick_attack_extended(self): @@ -3186,7 +3186,7 @@ Content-Type: application/x-foo; """ msg = bongo.external.email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "us-ascii'en-us'Frank's Document") def test_rfc2231_no_extended_values(self): diff --git a/src/libs/python/bongo/external/email/test/test_email_codecs.py b/src/libs/python/bongo/external/email/test/test_email_codecs.py index c73800a..718df48 100644 --- a/src/libs/python/bongo/external/email/test/test_email_codecs.py +++ b/src/libs/python/bongo/external/email/test/test_email_codecs.py @@ -13,7 +13,7 @@ from bongo.external.email.Message import Message # We're compatible with Python 2.3, but it doesn't have the built-in Asian # codecs, so we have to skip all these tests. try: - unicode('foo', 'euc-jp') + str('foo', 'euc-jp') except LookupError: raise TestSkipped @@ -42,7 +42,7 @@ Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?= ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), ('Gr\xfc\xdf Gott!', 'iso-8859-1')]) long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' - h = Header(long, j, header_name="Subject") + h = Header(int, j, header_name="Subject") # test a very long header enc = h.encode() # TK: splitting point may differ by codec design and/or Header encoding @@ -50,14 +50,14 @@ Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?= =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?= =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""") # TK: full decode comparison - eq(h.__unicode__().encode('euc-jp'), long) + eq(h.__unicode__().encode('euc-jp'), int) def test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' jcode = 'euc-jp' msg = Message() msg.set_payload(jhello, jcode) - ustr = unicode(msg.get_payload(), msg.get_content_charset()) + ustr = str(msg.get_payload(), msg.get_content_charset()) self.assertEqual(jhello, ustr.encode(jcode)) diff --git a/src/libs/python/bongo/external/email/test/test_email_codecs_renamed.py b/src/libs/python/bongo/external/email/test/test_email_codecs_renamed.py index 6813794..d033437 100644 --- a/src/libs/python/bongo/external/email/test/test_email_codecs_renamed.py +++ b/src/libs/python/bongo/external/email/test/test_email_codecs_renamed.py @@ -13,7 +13,7 @@ from bongo.external.email.message import Message # We're compatible with Python 2.3, but it doesn't have the built-in Asian # codecs, so we have to skip all these tests. try: - unicode('foo', 'euc-jp') + str('foo', 'euc-jp') except LookupError: raise TestSkipped @@ -42,7 +42,7 @@ Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?= ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), ('Gr\xfc\xdf Gott!', 'iso-8859-1')]) long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' - h = Header(long, j, header_name="Subject") + h = Header(int, j, header_name="Subject") # test a very long header enc = h.encode() # TK: splitting point may differ by codec design and/or Header encoding @@ -50,14 +50,14 @@ Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?= =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?= =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""") # TK: full decode comparison - eq(h.__unicode__().encode('euc-jp'), long) + eq(h.__unicode__().encode('euc-jp'), int) def test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' jcode = 'euc-jp' msg = Message() msg.set_payload(jhello, jcode) - ustr = unicode(msg.get_payload(), msg.get_content_charset()) + ustr = str(msg.get_payload(), msg.get_content_charset()) self.assertEqual(jhello, ustr.encode(jcode)) diff --git a/src/libs/python/bongo/external/email/test/test_email_renamed.py b/src/libs/python/bongo/external/email/test/test_email_renamed.py index 07e4e45..27a6b27 100644 --- a/src/libs/python/bongo/external/email/test/test_email_renamed.py +++ b/src/libs/python/bongo/external/email/test/test_email_renamed.py @@ -9,7 +9,7 @@ import base64 import difflib import unittest import warnings -from cStringIO import StringIO +from io import StringIO import email @@ -52,13 +52,13 @@ def openfile(filename, mode='r'): class TestEmailBase(unittest.TestCase): def ndiffAssertEqual(self, first, second): """Like failUnlessEqual except use ndiff for readable output.""" - if first <> second: + if first != second: sfirst = str(first) ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) fp = StringIO() - print >> fp, NL, NL.join(diff) - raise self.failureException, fp.getvalue() + print(NL, NL.join(diff), file=fp) + raise self.failureException(fp.getvalue()) def _msgobj(self, filename): fp = openfile(findfile(filename)) @@ -164,7 +164,7 @@ class TestMessageAPI(TestEmailBase): # header appears fifth. msg = self._msgobj('msg_01.txt') msg.set_boundary('BOUNDARY') - header, value = msg.items()[4] + header, value = list(msg.items())[4] eq(header.lower(), 'content-type') eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"') # This one has a Content-Type: header, with a boundary, stuck in the @@ -172,7 +172,7 @@ class TestMessageAPI(TestEmailBase): # be fifth. msg = self._msgobj('msg_04.txt') msg.set_boundary('BOUNDARY') - header, value = msg.items()[4] + header, value = list(msg.items())[4] eq(header.lower(), 'content-type') eq(value, 'multipart/mixed; boundary="BOUNDARY"') # And this one has no Content-Type: header at all. @@ -227,12 +227,12 @@ class TestMessageAPI(TestEmailBase): msg['From'] = 'Me' msg['to'] = 'You' # Check for case insensitivity - self.failUnless('from' in msg) - self.failUnless('From' in msg) - self.failUnless('FROM' in msg) - self.failUnless('to' in msg) - self.failUnless('To' in msg) - self.failUnless('TO' in msg) + self.assertTrue('from' in msg) + self.assertTrue('From' in msg) + self.assertTrue('FROM' in msg) + self.assertTrue('to' in msg) + self.assertTrue('To' in msg) + self.assertTrue('TO' in msg) def test_as_string(self): eq = self.assertEqual @@ -245,7 +245,7 @@ class TestMessageAPI(TestEmailBase): eq(text, msg.as_string()) fullrepr = str(msg) lines = fullrepr.split('\n') - self.failUnless(lines[0].startswith('From ')) + self.assertTrue(lines[0].startswith('From ')) eq(text, NL.join(lines[1:])) def test_bad_param(self): @@ -316,10 +316,10 @@ class TestMessageAPI(TestEmailBase): def test_has_key(self): msg = bongo.external.email.message_from_string('Header: exists') - self.failUnless(msg.has_key('header')) - self.failUnless(msg.has_key('Header')) - self.failUnless(msg.has_key('HEADER')) - self.failIf(msg.has_key('headeri')) + self.assertTrue('header' in msg) + self.assertTrue('Header' in msg) + self.assertTrue('HEADER' in msg) + self.assertFalse('headeri' in msg) def test_set_param(self): eq = self.assertEqual @@ -471,15 +471,15 @@ class TestMessageAPI(TestEmailBase): msg.add_header('First', 'One') msg.add_header('Second', 'Two') msg.add_header('Third', 'Three') - eq(msg.keys(), ['First', 'Second', 'Third']) - eq(msg.values(), ['One', 'Two', 'Three']) + eq(list(msg.keys()), ['First', 'Second', 'Third']) + eq(list(msg.values()), ['One', 'Two', 'Three']) msg.replace_header('Second', 'Twenty') - eq(msg.keys(), ['First', 'Second', 'Third']) - eq(msg.values(), ['One', 'Twenty', 'Three']) + eq(list(msg.keys()), ['First', 'Second', 'Third']) + eq(list(msg.values()), ['One', 'Twenty', 'Three']) msg.add_header('First', 'Eleven') msg.replace_header('First', 'One Hundred') - eq(msg.keys(), ['First', 'Second', 'Third', 'First']) - eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven']) + eq(list(msg.keys()), ['First', 'Second', 'Third', 'First']) + eq(list(msg.values()), ['One Hundred', 'Twenty', 'Three', 'Eleven']) self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing') def test_broken_base64_payload(self): @@ -565,7 +565,7 @@ bug demonstration utf8 = Charset("utf-8") g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. " cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. " - utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") + utf8_head = "\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") h = Header(g_head, g, header_name='Subject') h.append(cz_head, cz) h.append(utf8_head, utf8) @@ -903,7 +903,7 @@ class TestMIMEAudio(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], @@ -946,7 +946,7 @@ class TestMIMEImage(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._im.add_header('Content-Disposition', 'attachment', filename='dingusfish.gif') eq(self._im['content-disposition'], @@ -990,7 +990,7 @@ class TestMIMEText(unittest.TestCase): def test_types(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue eq(self._msg.get_content_type(), 'text/plain') eq(self._msg.get_param('charset'), 'us-ascii') missing = [] @@ -1000,7 +1000,7 @@ class TestMIMEText(unittest.TestCase): def test_payload(self): self.assertEqual(self._msg.get_payload(), 'hello there') - self.failUnless(not self._msg.is_multipart()) + self.assertTrue(not self._msg.is_multipart()) def test_charset(self): eq = self.assertEqual @@ -1055,7 +1055,7 @@ This is the dingus fish. def test_hierarchy(self): # convenience eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue raises = self.assertRaises # tests m = self._msg @@ -1369,7 +1369,7 @@ Content-Type: text/plain -- XXXX-- ''') - self.failUnless(msg.is_multipart()) + self.assertTrue(msg.is_multipart()) eq(msg.get_boundary(), ' XXXX') eq(len(msg.get_payload()), 2) @@ -1385,7 +1385,7 @@ Content-Transfer-Encoding: base64 YXNkZg== --===============0012394164==--""") - self.assertEquals(m.get_payload(0).get_payload(), 'YXNkZg==') + self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==') @@ -1399,7 +1399,7 @@ class TestNonConformant(TestEmailBase): eq(msg.get_content_subtype(), 'plain') def test_same_boundary_inner_outer(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_15.txt') # XXX We can probably eventually do better inner = msg.get_payload(0) @@ -1409,7 +1409,7 @@ class TestNonConformant(TestEmailBase): errors.StartBoundaryNotFoundDefect)) def test_multipart_no_boundary(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_25.txt') unless(isinstance(msg.get_payload(), str)) self.assertEqual(len(msg.defects), 2) @@ -1467,7 +1467,7 @@ counter to RFC 2822, there's no separating newline here """) def test_lying_multipart(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_41.txt') unless(hasattr(msg, 'defects')) self.assertEqual(len(msg.defects), 2) @@ -1487,7 +1487,7 @@ counter to RFC 2822, there's no separating newline here # [*] This message is missing its start boundary bad = outer.get_payload(1).get_payload(0) self.assertEqual(len(bad.defects), 1) - self.failUnless(isinstance(bad.defects[0], + self.assertTrue(isinstance(bad.defects[0], errors.StartBoundaryNotFoundDefect)) @@ -1513,7 +1513,7 @@ class TestRFC2047(unittest.TestCase): s = '=?ISO-8859-1?Q?Andr=E9?= Pirard ' dh = decode_header(s) eq(dh, [('Andr\xe9', 'iso-8859-1'), ('Pirard ', None)]) - hu = unicode(make_header(dh)).encode('latin-1') + hu = str(make_header(dh)).encode('latin-1') eq(hu, 'Andr\xe9 Pirard ') def test_whitespace_eater_unicode_2(self): @@ -1523,7 +1523,7 @@ class TestRFC2047(unittest.TestCase): eq(dh, [('The', None), ('quick brown fox', 'iso-8859-1'), ('jumped over the', None), ('lazy dog', 'iso-8859-1')]) hu = make_header(dh).__unicode__() - eq(hu, u'The quick brown fox jumped over the lazy dog') + eq(hu, 'The quick brown fox jumped over the lazy dog') @@ -1541,7 +1541,7 @@ class TestMIMEMessage(TestEmailBase): def test_valid_argument(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue subject = 'A sub-message' m = Message() m['Subject'] = subject @@ -1585,20 +1585,20 @@ Here is the body of the message. def test_parse_message_rfc822(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_11.txt') eq(msg.get_content_type(), 'message/rfc822') payload = msg.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) submsg = payload[0] - self.failUnless(isinstance(submsg, Message)) + self.assertTrue(isinstance(submsg, Message)) eq(submsg['subject'], 'An enclosed message') eq(submsg.get_payload(), 'Here is the body of the message.\n') def test_dsn(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue # msg 16 is a Delivery Status Notification, see RFC 1894 msg = self._msgobj('msg_16.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1860,7 +1860,7 @@ class TestIdempotent(TestEmailBase): eq(text, s.getvalue()) def test_parse_text_message(self): - eq = self.assertEquals + eq = self.assertEqual msg, text = self._msgobj('msg_01.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_content_maintype(), 'text') @@ -1872,7 +1872,7 @@ class TestIdempotent(TestEmailBase): self._idempotent(msg, text) def test_parse_untyped_message(self): - eq = self.assertEquals + eq = self.assertEqual msg, text = self._msgobj('msg_03.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_params(), None) @@ -1944,8 +1944,8 @@ class TestIdempotent(TestEmailBase): self._idempotent(msg, text) def test_content_type(self): - eq = self.assertEquals - unless = self.failUnless + eq = self.assertEqual + unless = self.assertTrue # Get a message object and reset the seek pointer for other tests msg, text = self._msgobj('msg_05.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1967,7 +1967,7 @@ class TestIdempotent(TestEmailBase): eq(msg2.get_payload(), 'Yadda yadda yadda\n') msg3 = msg.get_payload(2) eq(msg3.get_content_type(), 'message/rfc822') - self.failUnless(isinstance(msg3, Message)) + self.assertTrue(isinstance(msg3, Message)) payload = msg3.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) @@ -1976,8 +1976,8 @@ class TestIdempotent(TestEmailBase): eq(msg4.get_payload(), 'Yadda yadda yadda\n') def test_parser(self): - eq = self.assertEquals - unless = self.failUnless + eq = self.assertEqual + unless = self.assertTrue msg, text = self._msgobj('msg_06.txt') # Check some of the outer headers eq(msg.get_content_type(), 'message/rfc822') @@ -1987,9 +1987,9 @@ class TestIdempotent(TestEmailBase): unless(isinstance(payload, list)) eq(len(payload), 1) msg1 = payload[0] - self.failUnless(isinstance(msg1, Message)) + self.assertTrue(isinstance(msg1, Message)) eq(msg1.get_content_type(), 'text/plain') - self.failUnless(isinstance(msg1.get_payload(), str)) + self.assertTrue(isinstance(msg1.get_payload(), str)) eq(msg1.get_payload(), '\n') @@ -2026,7 +2026,7 @@ class TestMiscellaneous(TestEmailBase): fp.close() def test_message_from_string_with_class(self): - unless = self.failUnless + unless = self.assertTrue fp = openfile('msg_01.txt') try: text = fp.read() @@ -2049,7 +2049,7 @@ class TestMiscellaneous(TestEmailBase): unless(isinstance(subpart, MyMessage)) def test_message_from_file_with_class(self): - unless = self.failUnless + unless = self.assertTrue # Create a subclass class MyMessage(Message): pass @@ -2186,7 +2186,7 @@ class TestMiscellaneous(TestEmailBase): def test_charset_richcomparisons(self): eq = self.assertEqual - ne = self.failIfEqual + ne = self.assertNotEqual cset1 = Charset() cset2 = Charset() eq(cset1, 'us-ascii') @@ -2385,8 +2385,8 @@ class TestParsers(TestEmailBase): eq(msg['from'], 'ppp-request@zzz.org') eq(msg['to'], 'ppp@zzz.org') eq(msg.get_content_type(), 'multipart/mixed') - self.failIf(msg.is_multipart()) - self.failUnless(isinstance(msg.get_payload(), str)) + self.assertFalse(msg.is_multipart()) + self.assertTrue(isinstance(msg.get_payload(), str)) def test_whitespace_continuation(self): eq = self.assertEqual @@ -2495,8 +2495,8 @@ Here's the message body eq = self.assertEqual m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody' msg = bongo.external.email.message_from_string(m) - eq(len(msg.keys()), 3) - keys = msg.keys() + eq(len(list(msg.keys())), 3) + keys = list(msg.keys()) keys.sort() eq(keys, ['!"#QUX;~', '>From', 'From']) eq(msg.get_payload(), 'body') @@ -2505,13 +2505,13 @@ Here's the message body eq = self.assertEqual m = '>From foo@example.com 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody' msg = bongo.external.email.message_from_string(m) - eq(len(msg.keys()), 0) + eq(len(list(msg.keys())), 0) def test_rfc2822_one_character_header(self): eq = self.assertEqual m = 'A: first header\nB: second header\nCC: third header\n\nbody' msg = bongo.external.email.message_from_string(m) - headers = msg.keys() + headers = list(msg.keys()) headers.sort() eq(headers, ['A', 'B', 'CC']) eq(msg.get_payload(), 'body') @@ -2605,15 +2605,15 @@ class TestQuopri(unittest.TestCase): def test_header_quopri_check(self): for c in self.hlit: - self.failIf(quoprimime.header_quopri_check(c)) + self.assertFalse(quoprimime.header_quopri_check(c)) for c in self.hnon: - self.failUnless(quoprimime.header_quopri_check(c)) + self.assertTrue(quoprimime.header_quopri_check(c)) def test_body_quopri_check(self): for c in self.blit: - self.failIf(quoprimime.body_quopri_check(c)) + self.assertFalse(quoprimime.body_quopri_check(c)) for c in self.bnon: - self.failUnless(quoprimime.body_quopri_check(c)) + self.assertTrue(quoprimime.body_quopri_check(c)) def test_header_quopri_len(self): eq = self.assertEqual @@ -2752,7 +2752,7 @@ class TestCharset(unittest.TestCase): eq('hello w\xf6rld', c.body_encode('hello w\xf6rld')) def test_unicode_charset_name(self): - charset = Charset(u'us-ascii') + charset = Charset('us-ascii') self.assertEqual(str(charset), 'us-ascii') self.assertRaises(errors.CharsetError, Charset, 'asc\xffii') @@ -2782,7 +2782,7 @@ class TestHeader(TestEmailBase): h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", maxlinelen=76) for l in h.encode(splitchars=' ').split('\n '): - self.failUnless(len(l) <= 76) + self.assertTrue(len(l) <= 76) def test_multilingual(self): eq = self.ndiffAssertEqual @@ -2791,7 +2791,7 @@ class TestHeader(TestEmailBase): utf8 = Charset("utf-8") g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. " cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. " - utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") + utf8_head = "\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8") h = Header(g_head, g) h.append(cz_head, cz) h.append(utf8_head, utf8) @@ -2811,7 +2811,7 @@ class TestHeader(TestEmailBase): eq(decode_header(enc), [(g_head, "iso-8859-1"), (cz_head, "iso-8859-2"), (utf8_head, "utf-8")]) - ustr = unicode(h) + ustr = str(h) eq(ustr.encode('utf-8'), 'Die Mieter treten hier ein werden mit einem Foerderband ' 'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen ' @@ -2879,9 +2879,9 @@ A very long line that must get split to something other than at the def test_utf8_shortest(self): eq = self.assertEqual - h = Header(u'p\xf6stal', 'utf-8') + h = Header('p\xf6stal', 'utf-8') eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=') - h = Header(u'\u83ca\u5730\u6642\u592b', 'utf-8') + h = Header('\u83ca\u5730\u6642\u592b', 'utf-8') eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=') def test_bad_8bit_header(self): @@ -3012,7 +3012,7 @@ Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOC ''' msg = bongo.external.email.message_from_string(m) param = msg.get_param('NAME') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual( param, 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm') @@ -3134,7 +3134,7 @@ Content-Disposition: inline; ''' msg = bongo.external.email.message_from_string(m) self.assertEqual(msg.get_filename(), - u'This is even more ***fun*** is it not.pdf\ufffd') + 'This is even more ***fun*** is it not.pdf\ufffd') def test_rfc2231_unknown_encoding(self): m = """\ @@ -3165,7 +3165,7 @@ Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\" """ msg = bongo.external.email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "Frank's Document") def test_rfc2231_tick_attack_extended(self): @@ -3189,7 +3189,7 @@ Content-Type: application/x-foo; """ msg = bongo.external.email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "us-ascii'en-us'Frank's Document") def test_rfc2231_no_extended_values(self): diff --git a/src/libs/python/bongo/external/email/test/test_email_torture.py b/src/libs/python/bongo/external/email/test/test_email_torture.py index 161e72f..472a68c 100644 --- a/src/libs/python/bongo/external/email/test/test_email_torture.py +++ b/src/libs/python/bongo/external/email/test/test_email_torture.py @@ -9,7 +9,7 @@ import sys import os import unittest -from cStringIO import StringIO +from io import StringIO from types import ListType from bongo.external.email.test.test_email import TestEmailBase diff --git a/src/libs/python/bongo/external/email/utils.py b/src/libs/python/bongo/external/email/utils.py index 3ab51fd..f9b661c 100644 --- a/src/libs/python/bongo/external/email/utils.py +++ b/src/libs/python/bongo/external/email/utils.py @@ -25,9 +25,9 @@ import time import base64 import random import socket -import urllib +import urllib.request, urllib.parse, urllib.error import warnings -from cStringIO import StringIO +from io import StringIO from bongo.external.email._parseaddr import quote from bongo.external.email._parseaddr import AddressList as _AddressList @@ -44,7 +44,7 @@ from bongo.external.email.encoders import _bencode, _qencode COMMASPACE = ', ' EMPTYSTRING = '' -UEMPTYSTRING = u'' +UEMPTYSTRING = '' CRLF = '\r\n' TICK = "'" @@ -249,8 +249,8 @@ def encode_rfc2231(s, charset=None, language=None): charset is given but not language, the string is encoded using the empty string for language. """ - import urllib - s = urllib.quote(s, safe='') + import urllib.request, urllib.parse, urllib.error + s = urllib.parse.quote(s, safe='') if charset is None and language is None: return s if language is None: @@ -290,7 +290,7 @@ def decode_params(params): else: new_params.append((name, '"%s"' % quote(value))) if rfc2231_params: - for name, continuations in rfc2231_params.items(): + for name, continuations in list(rfc2231_params.items()): value = [] extended = False # Sort by number @@ -302,7 +302,7 @@ def decode_params(params): # language specifiers at the beginning of the string. for num, s, encoded in continuations: if encoded: - s = urllib.unquote(s) + s = urllib.parse.unquote(s) extended = True value.append(s) value = quote(EMPTYSTRING.join(value)) @@ -319,9 +319,9 @@ def collapse_rfc2231_value(value, errors='replace', rawval = unquote(value[2]) charset = value[0] or 'us-ascii' try: - return unicode(rawval, charset, errors) + return str(rawval, charset, errors) except LookupError: # XXX charset is unknown to Python. - return unicode(rawval, fallback_charset, errors) + return str(rawval, fallback_charset, errors) else: return unquote(value) diff --git a/src/libs/python/bongo/external/simplejson/__init__.py b/src/libs/python/bongo/external/simplejson/__init__.py index 39dd8f1..63b2e24 100644 --- a/src/libs/python/bongo/external/simplejson/__init__.py +++ b/src/libs/python/bongo/external/simplejson/__init__.py @@ -77,8 +77,8 @@ __all__ = [ 'JSONDecoder', 'JSONEncoder', ] -from decoder import JSONDecoder -from encoder import JSONEncoder +from .decoder import JSONDecoder +from .encoder import JSONEncoder def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, **kw): diff --git a/src/libs/python/bongo/external/simplejson/decoder.py b/src/libs/python/bongo/external/simplejson/decoder.py index b388cd7..cb78ba3 100644 --- a/src/libs/python/bongo/external/simplejson/decoder.py +++ b/src/libs/python/bongo/external/simplejson/decoder.py @@ -3,7 +3,7 @@ Implementation of JSONDecoder """ import re -from scanner import Scanner, pattern +from .scanner import Scanner, pattern FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL @@ -59,8 +59,8 @@ pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber) STRINGCHUNK = re.compile(r'(.*?)(["\\])', FLAGS) BACKSLASH = { - '"': u'"', '\\': u'\\', '/': u'/', - 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', + '"': '"', '\\': '\\', '/': '/', + 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', } DEFAULT_ENCODING = "utf-8" @@ -79,8 +79,8 @@ def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match): end = chunk.end() content, terminator = chunk.groups() if content: - if not isinstance(content, unicode): - content = unicode(content, encoding) + if not isinstance(content, str): + content = str(content, encoding) _append(content) if terminator == '"': break @@ -99,14 +99,14 @@ def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match): else: esc = s[end + 1:end + 5] try: - m = unichr(int(esc, 16)) + m = chr(int(esc, 16)) if len(esc) != 4 or not esc.isalnum(): raise ValueError except ValueError: raise ValueError(errmsg("Invalid \\uXXXX escape", s, end)) end += 5 _append(m) - return u''.join(chunks), end + return ''.join(chunks), end def JSONString(match, context): encoding = getattr(context, 'encoding', None) @@ -134,7 +134,7 @@ def JSONObject(match, context, _w=WHITESPACE.match): raise ValueError(errmsg("Expecting : delimiter", s, end)) end = _w(s, end + 1).end() try: - value, end = JSONScanner.iterscan(s, idx=end).next() + value, end = next(JSONScanner.iterscan(s, idx=end)) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value @@ -166,7 +166,7 @@ def JSONArray(match, context, _w=WHITESPACE.match): return values, end + 1 while True: try: - value, end = JSONScanner.iterscan(s, idx=end).next() + value, end = next(JSONScanner.iterscan(s, idx=end)) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) values.append(value) @@ -263,7 +263,7 @@ class JSONDecoder(object): """ kw.setdefault('context', self) try: - obj, end = self._scanner.iterscan(s, **kw).next() + obj, end = next(self._scanner.iterscan(s, **kw)) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end diff --git a/src/libs/python/bongo/external/simplejson/encoder.py b/src/libs/python/bongo/external/simplejson/encoder.py index bb1aba0..4868cdb 100644 --- a/src/libs/python/bongo/external/simplejson/encoder.py +++ b/src/libs/python/bongo/external/simplejson/encoder.py @@ -163,19 +163,19 @@ class JSONEncoder(object): encoder = encode_basestring allow_nan = self.allow_nan if self.sort_keys: - keys = dct.keys() + keys = list(dct.keys()) keys.sort() items = [(k,dct[k]) for k in keys] else: - items = dct.iteritems() + items = iter(dct.items()) for key, value in items: - if isinstance(key, basestring): + if isinstance(key, str): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = floatstr(key, allow_nan) - elif isinstance(key, (int, long)): + elif isinstance(key, int): key = str(key) elif key is True: key = 'true' @@ -200,7 +200,7 @@ class JSONEncoder(object): del markers[markerid] def _iterencode(self, o, markers=None): - if isinstance(o, basestring): + if isinstance(o, str): if self.ensure_ascii: encoder = encode_basestring_ascii else: @@ -212,7 +212,7 @@ class JSONEncoder(object): yield 'true' elif o is False: yield 'false' - elif isinstance(o, (int, long)): + elif isinstance(o, int): yield str(o) elif isinstance(o, float): yield floatstr(o, self.allow_nan) diff --git a/src/libs/python/bongo/external/simplejson/jsonfilter.py b/src/libs/python/bongo/external/simplejson/jsonfilter.py index 01ca21d..990bc60 100644 --- a/src/libs/python/bongo/external/simplejson/jsonfilter.py +++ b/src/libs/python/bongo/external/simplejson/jsonfilter.py @@ -16,7 +16,7 @@ class JSONFilter(object): if environ.get('REQUEST_METHOD', '') == 'POST': if environ.get('CONTENT_TYPE', '') == self.mime_type: args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _] - data = environ['wsgi.input'].read(*map(int, args)) + data = environ['wsgi.input'].read(*list(map(int, args))) environ['jsonfilter.json'] = simplejson.loads(data) res = simplejson.dumps(self.app(environ, json_start_response)) jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp') diff --git a/src/libs/python/bongo/external/simpletal/FixedHTMLParser.py b/src/libs/python/bongo/external/simpletal/FixedHTMLParser.py index edb2c1a..2ac90bd 100644 --- a/src/libs/python/bongo/external/simpletal/FixedHTMLParser.py +++ b/src/libs/python/bongo/external/simpletal/FixedHTMLParser.py @@ -35,10 +35,10 @@ """ import bongo.external.simpletal -import HTMLParser +import html.parser -class HTMLParser (HTMLParser.HTMLParser): +class HTMLParser (html.parser.HTMLParser): def unescape(self, s): # Just return the data - we don't partially unescaped data! return s diff --git a/src/libs/python/bongo/external/simpletal/simpleTAL.py b/src/libs/python/bongo/external/simpletal/simpleTAL.py index 0c2690d..84b00ac 100644 --- a/src/libs/python/bongo/external/simpletal/simpleTAL.py +++ b/src/libs/python/bongo/external/simpletal/simpleTAL.py @@ -39,7 +39,7 @@ try: except: import bongo.external.simpletal.DummyLogger as logging -import xml.sax, cgi, StringIO, codecs, re, types, copy, sys +import xml.sax, cgi, io, codecs, re, types, copy, sys import bongo.external.simpletal.sgmlentitynames as sgmlentitynames import bongo.external.simpletal as simpletal @@ -146,9 +146,10 @@ class TemplateInterpreter: self.commandHandler [METAL_DEFINE_SLOT] = self.cmdDefineSlot self.commandHandler [TAL_NOOP] = self.cmdNoOp - def tagAsText (self, (tag,atts), singletonFlag=0): + def tagAsText (self, xxx_todo_changeme, singletonFlag=0): """ This returns a tag as text. """ + (tag,atts) = xxx_todo_changeme result = ["<"] result.append (tag) for attName, attValue in atts: @@ -274,7 +275,7 @@ class TemplateInterpreter: self.context.setLocal (args[0], self.repeatVariable.getCurrentValue()) self.programCounter += 1 return - except IndexError, e: + except IndexError as e: # We have finished the repeat self.repeatVariable = None self.context.removeRepeat (args[0]) @@ -311,7 +312,7 @@ class TemplateInterpreter: if (hasattr (result, "__iter__") and callable (result.__iter__)): # We can get an iterator! self.repeatVariable = simpleTALES.IteratorRepeatVariable (result.__iter__()) - elif (hasattr (result, "next") and callable (result.next)): + elif (hasattr (result, "next") and callable (result.__next__)): # Treat as an iterator self.repeatVariable = simpleTALES.IteratorRepeatVariable (result) else: @@ -323,7 +324,7 @@ class TemplateInterpreter: try: curValue = self.repeatVariable.getCurrentValue() - except IndexError, e: + except IndexError as e: # The iterator ran out of values before we started - treat as an empty list self.outputTag = 0 self.repeatVariable = None @@ -378,20 +379,20 @@ class TemplateInterpreter: elif (not resultVal == simpleTALES.DEFAULTVALUE): # We have a value - let's use it! attsToRemove [attName]=1 - if (isinstance (resultVal, types.UnicodeType)): + if (isinstance (resultVal, str)): escapedAttVal = resultVal - elif (isinstance (resultVal, types.StringType)): + elif (isinstance (resultVal, bytes)): # THIS IS NOT A BUG! # Use Unicode in the Context object if you are not using Ascii - escapedAttVal = unicode (resultVal, 'ascii') + escapedAttVal = str (resultVal, 'ascii') else: # THIS IS NOT A BUG! # Use Unicode in the Context object if you are not using Ascii - escapedAttVal = unicode (resultVal) + escapedAttVal = str (resultVal) newAtts.append ((attName, escapedAttVal)) # Copy over the old attributes for oldAttName, oldAttValue in self.currentAttributes: - if (not attsToRemove.has_key (oldAttName)): + if (oldAttName not in attsToRemove): newAtts.append ((oldAttName, oldAttValue)) self.currentAttributes = newAtts # Evaluate all other commands @@ -437,27 +438,27 @@ class TemplateInterpreter: # End of the macro expansion (if any) so clear the parameters self.slotParameters = {} else: - if (isinstance (resultVal, types.UnicodeType)): + if (isinstance (resultVal, str)): self.file.write (resultVal) - elif (isinstance (resultVal, types.StringType)): + elif (isinstance (resultVal, bytes)): # THIS IS NOT A BUG! # Use Unicode in the Context object if you are not using Ascii - self.file.write (unicode (resultVal, 'ascii')) + self.file.write (str (resultVal, 'ascii')) else: # THIS IS NOT A BUG! # Use Unicode in the Context object if you are not using Ascii - self.file.write (unicode (resultVal)) + self.file.write (str (resultVal)) else: - if (isinstance (resultVal, types.UnicodeType)): + if (isinstance (resultVal, str)): self.file.write (cgi.escape (resultVal)) - elif (isinstance (resultVal, types.StringType)): + elif (isinstance (resultVal, bytes)): # THIS IS NOT A BUG! # Use Unicode in the Context object if you are not using Ascii - self.file.write (cgi.escape (unicode (resultVal, 'ascii'))) + self.file.write (cgi.escape (str (resultVal, 'ascii'))) else: # THIS IS NOT A BUG! # Use Unicode in the Context object if you are not using Ascii - self.file.write (cgi.escape (unicode (resultVal))) + self.file.write (cgi.escape (str (resultVal))) if (self.outputTag and not args[1]): # Do NOT output end tag if a singleton with no content @@ -536,7 +537,7 @@ class TemplateInterpreter: If the slotName is filled then that is used, otherwise the original conent is used. """ - if (self.currentSlots.has_key (args[0])): + if (args[0] in self.currentSlots): # This slot is filled, so replace us with that content self.outputTag = 0 self.tagContent = (1, self.currentSlots [args[0]]) @@ -557,14 +558,15 @@ class HTMLTemplateInterpreter (TemplateInterpreter): # Override the tagAsText method for this instance self.tagAsText = self.tagAsTextMinimizeAtts - def tagAsTextMinimizeAtts (self, (tag,atts), singletonFlag=0): + def tagAsTextMinimizeAtts (self, xxx_todo_changeme1, singletonFlag=0): """ This returns a tag as text. """ + (tag,atts) = xxx_todo_changeme1 result = ["<"] result.append (tag) upperTag = tag.upper() for attName, attValue in atts: - if (HTML_BOOLEAN_ATTS.has_key ('%s:%s' % (upperTag, attName.upper()))): + if ('%s:%s' % (upperTag, attName.upper()) in HTML_BOOLEAN_ATTS): # We should output a minimised boolean value result.append (' ') result.append (attName) @@ -588,7 +590,7 @@ class Template: self.doctype = doctype # Setup the macros - for macro in self.macros.values(): + for macro in list(self.macros.values()): macro.setParentTemplate (self) # Setup the slots @@ -596,7 +598,7 @@ class Template: if (cmnd == METAL_USE_MACRO): # Set the parent of each slot slotMap = arg[1] - for slot in slotMap.values(): + for slot in list(slotMap.values()): slot.setParentTemplate (self) def expand (self, context, outputFile, outputEncoding=None, interpreter=None): @@ -617,7 +619,7 @@ class Template: ourInterpreter = interpreter try: ourInterpreter.execute (self) - except UnicodeError, unierror: + except UnicodeError as unierror: logging.error ("UnicodeError caused by placing a non-Unicode string in the Context object.") raise simpleTALES.ContextContentException ("Found non-unicode string in Context!") @@ -633,16 +635,16 @@ class Template: result = result + "\n[%s] %s" % (str (index), str (cmd)) else: result = result + "\n[%s] %s, (%s{" % (str (index), str (cmd[0]), str (cmd[1][0])) - for slot in cmd[1][1].keys(): + for slot in list(cmd[1][1].keys()): result = result + "%s: %s" % (slot, str (cmd[1][1][slot])) result = result + "}, %s)" % str (cmd[1][2]) index += 1 result = result + "\n\nSymbols:\n" - for symbol in self.symbolTable.keys(): + for symbol in list(self.symbolTable.keys()): result = result + "Symbol: " + str (symbol) + " points to: " + str (self.symbolTable[symbol]) + ", which is command: " + str (self.commandList[self.symbolTable[symbol]]) + "\n" result = result + "\n\nMacros:\n" - for macro in self.macros.keys(): + for macro in list(self.macros.keys()): result = result + "Macro: " + str (macro) + " value of: " + str (self.macros[macro]) return result @@ -795,9 +797,10 @@ class TemplateCompiler: newPrefix = self.metal_namespace_prefix_stack.pop() self.setMETALPrefix (newPrefix) - def tagAsText (self, (tag,atts), singletonFlag=0): + def tagAsText (self, xxx_todo_changeme2, singletonFlag=0): """ This returns a tag as text. """ + (tag,atts) = xxx_todo_changeme2 result = ["<"] result.append (tag) for attName, attValue in atts: @@ -866,7 +869,7 @@ class TemplateCompiler: popCommandList = tagProperties.get ('popFunctionList', []) singletonTag = tagProperties.get ('singletonTag', 0) for func in popCommandList: - apply (func, ()) + func(*()) self.log.debug ("Popped tag %s off stack" % oldTag[0]) if (oldTag[0] == tag[0]): # We've found the right tag, now check to see if we have any TAL commands on it @@ -968,7 +971,7 @@ class TemplateCompiler: else: # It's nothing special, just an ordinary namespace declaration cleanAttributes.append ((att, value)) - elif (self.tal_attribute_map.has_key (commandAttName)): + elif (commandAttName in self.tal_attribute_map): # It's a TAL attribute cmnd = self.tal_attribute_map [commandAttName] if (cmnd == TAL_OMITTAG and TALElementNameSpace): @@ -976,7 +979,7 @@ class TemplateCompiler: else: foundCommandsArgs [cmnd] = value foundTALAtts.append (cmnd) - elif (self.metal_attribute_map.has_key (commandAttName)): + elif (commandAttName in self.metal_attribute_map): # It's a METAL attribute cmnd = self.metal_attribute_map [commandAttName] foundCommandsArgs [cmnd] = value @@ -1185,7 +1188,7 @@ class TemplateCompiler: msg = "Macro name %s is invalid." % argument self.log.error (msg) raise TemplateParseException (self.tagAsText (self.currentStartTag), msg) - if (self.macroMap.has_key (argument)): + if (argument in self.macroMap): msg = "Macro name %s is already defined!" % argument self.log.error (msg) raise TemplateParseException (self.tagAsText (self.currentStartTag), msg) @@ -1233,7 +1236,7 @@ class TemplateCompiler: self.log.error (msg) raise TemplateParseException (self.tagAsText (self.currentStartTag), msg) - if (slotMap.has_key (argument)): + if (argument in slotMap): msg = "Slot %s has already been filled!" % argument self.log.error (msg) raise TemplateParseException (self.tagAsText (self.currentStartTag), msg) @@ -1282,14 +1285,15 @@ class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser): self.feed (encodedFile.read()) self.close() - def tagAsText (self, (tag,atts), singletonFlag=0): + def tagAsText (self, xxx_todo_changeme3, singletonFlag=0): """ This returns a tag as text. """ + (tag,atts) = xxx_todo_changeme3 result = ["<"] result.append (tag) upperTag = tag.upper() for attName, attValue in atts: - if (self.minimizeBooleanAtts and HTML_BOOLEAN_ATTS.has_key ('%s:%s' % (upperTag, attName.upper()))): + if (self.minimizeBooleanAtts and '%s:%s' % (upperTag, attName.upper()) in HTML_BOOLEAN_ATTS): # We should output a minimised boolean value result.append (' ') result.append (attName) @@ -1307,7 +1311,7 @@ class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser): def handle_startendtag (self, tag, attributes): self.handle_starttag (tag, attributes) - if not (HTML_FORBIDDEN_ENDTAG.has_key (tag.upper())): + if not (tag.upper() in HTML_FORBIDDEN_ENDTAG): self.handle_endtag(tag) def handle_starttag (self, tag, attributes): @@ -1317,7 +1321,7 @@ class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser): # We need to spot empty tal:omit-tags if (attValue is None): if (att == self.tal_namespace_omittag): - atts.append ((att, u"")) + atts.append ((att, "")) else: atts.append ((att, att)) else: @@ -1335,16 +1339,16 @@ class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser): refValue = int (ref[3:-1], 16) else: refValue = int (ref[2:-1]) - goodAttValue.append (unichr (refValue)) + goodAttValue.append (chr (refValue)) else: # A named reference. - goodAttValue.append (unichr (sgmlentitynames.htmlNameToUnicodeNumber.get (ref[1:-1], 65533))) + goodAttValue.append (chr (sgmlentitynames.htmlNameToUnicodeNumber.get (ref[1:-1], 65533))) last = match.end() match = ENTITY_REF_REGEX.search (attValue, last) goodAttValue.append (attValue [last:]) - atts.append ((att, u"".join (goodAttValue))) + atts.append ((att, "".join (goodAttValue))) - if (HTML_FORBIDDEN_ENDTAG.has_key (tag.upper())): + if (tag.upper() in HTML_FORBIDDEN_ENDTAG): # This should have no end tag, so we just do the start and suppress the end self.parseStartTag (tag, atts) self.log.debug ("End tag forbidden, generating close tag with no output.") @@ -1354,7 +1358,7 @@ class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser): def handle_endtag (self, tag): self.log.debug ("Recieved End Tag: " + tag) - if (HTML_FORBIDDEN_ENDTAG.has_key (tag.upper())): + if (tag.upper() in HTML_FORBIDDEN_ENDTAG): self.log.warn ("HTML 4.01 forbids end tags for the %s element" % tag) else: # Normal end tag @@ -1366,24 +1370,24 @@ class HTMLTemplateCompiler (TemplateCompiler, FixedHTMLParser.HTMLParser): # These two methods are required so that we expand all character and entity references prior to parsing the template. def handle_charref (self, ref): self.log.debug ("Got Ref: %s", ref) - self.parseData (unichr (int (ref))) + self.parseData (chr (int (ref))) def handle_entityref (self, ref): self.log.debug ("Got Ref: %s", ref) # Use handle_data so that <&> are re-encoded as required. - self.handle_data( unichr (sgmlentitynames.htmlNameToUnicodeNumber.get (ref, 65533))) + self.handle_data( chr (sgmlentitynames.htmlNameToUnicodeNumber.get (ref, 65533))) # Handle document type declarations def handle_decl (self, data): - self.parseData (u'' % data) + self.parseData ('' % data) # Pass comments through un-affected. def handle_comment (self, data): - self.parseData (u'' % data) + self.parseData ('' % data) def handle_pi (self, data): self.log.debug ("Recieved processing instruction.") - self.parseData (u'' % data) + self.parseData ('' % data) def report_unbalanced (self, tag): self.log.warn ("End tag %s present with no corresponding open tag.") @@ -1443,7 +1447,7 @@ class XMLTemplateCompiler (TemplateCompiler, xml.sax.handler.ContentHandler, xml if (SINGLETON_XML_REGEX.match (xmlText)): # This is a singleton! self.singletonElement=1 - except xml.sax.SAXException, e: + except xml.sax.SAXException as e: # Parser doesn't support this property pass # Convert attributes into a list of tuples @@ -1465,11 +1469,11 @@ class XMLTemplateCompiler (TemplateCompiler, xml.sax.handler.ContentHandler, xml def processingInstruction (self, target, data): self.log.debug ("Recieved processing instruction.") - self.parseData (u'' % (target, data)) + self.parseData ('' % (target, data)) def comment (self, data): # This is only called if your XML parser supports the LexicalHandler interface. - self.parseData (u'' % data) + self.parseData ('' % data) def getTemplate (self): template = XMLTemplate (self.commandList, self.macroMap, self.symbolLocationTable, self.doctype) @@ -1480,9 +1484,9 @@ def compileHTMLTemplate (template, inputEncoding="ISO-8859-1", minimizeBooleanAt To use the resulting template object call: template.expand (context, outputFile) """ - if (isinstance (template, types.StringType) or isinstance (template, types.UnicodeType)): + if (isinstance (template, bytes) or isinstance (template, str)): # It's a string! - templateFile = StringIO.StringIO (template) + templateFile = io.StringIO (template) else: templateFile = template compiler = HTMLTemplateCompiler() @@ -1494,9 +1498,9 @@ def compileXMLTemplate (template): To use the resulting template object call: template.expand (context, outputFile) """ - if (isinstance (template, types.StringType)): + if (isinstance (template, bytes)): # It's a string! - templateFile = StringIO.StringIO (template) + templateFile = io.StringIO (template) else: templateFile = template compiler = XMLTemplateCompiler() diff --git a/src/libs/python/bongo/external/simpletal/simpleTALES.py b/src/libs/python/bongo/external/simpletal/simpleTALES.py index 9a73a72..655258a 100644 --- a/src/libs/python/bongo/external/simpletal/simpleTALES.py +++ b/src/libs/python/bongo/external/simpletal/simpleTALES.py @@ -38,7 +38,7 @@ import types, sys try: import logging except: - import DummyLogger as logging + from . import DummyLogger as logging import bongo.external.simpletal as simpletal @@ -63,7 +63,7 @@ class ContextVariable: def value (self, currentPath=None): if (callable (self.ourValue)): - return apply (self.ourValue, ()) + return self.ourValue(*()) return self.ourValue def rawValue (self): @@ -190,8 +190,8 @@ class IteratorRepeatVariable (RepeatVariable): if (self.iterStatus == 0): self.iterStatus = 1 try: - self.curValue = self.sequence.next() - except StopIteration, e: + self.curValue = next(self.sequence) + except StopIteration as e: self.iterStatus = 2 raise IndexError ("Repeat Finished") return self.curValue @@ -200,8 +200,8 @@ class IteratorRepeatVariable (RepeatVariable): # Need this for the repeat variable functions. self.position += 1 try: - self.curValue = self.sequence.next() - except StopIteration, e: + self.curValue = next(self.sequence) + except StopIteration as e: self.iterStatus = 2 raise IndexError ("Repeat Finished") @@ -214,7 +214,7 @@ class IteratorRepeatVariable (RepeatVariable): self.map ['start'] = self.getStart self.map ['end'] = self.getEnd # TODO: first and last need to be implemented. - self.map ['length'] = sys.maxint + self.map ['length'] = sys.maxsize self.map ['letter'] = self.getLowerLetter self.map ['Letter'] = self.getUpperLetter self.map ['roman'] = self.getLowerRoman @@ -233,7 +233,7 @@ class PathFunctionVariable (ContextVariable): def value (self, currentPath=None): if (currentPath is not None): index, paths = currentPath - result = ContextVariable (apply (self.func, ('/'.join (paths[index:]),))) + result = ContextVariable (self.func(*('/'.join (paths[index:]),))) # Fast track the result raise result @@ -362,7 +362,7 @@ class Context: else: # Not specified - so it's a path return self.evaluatePath (expr) - except PathNotFoundException, e: + except PathNotFoundException as e: if (suppressException): return None raise e @@ -374,7 +374,7 @@ class Context: #self.log.debug ("Evaluating python expression %s" % expr) globals={} - for name, value in self.globals.items(): + for name, value in list(self.globals.items()): if (isinstance (value, ContextVariable)): value = value.rawValue() globals [name] = value globals ['path'] = self.pythonPathFuncs.path @@ -384,7 +384,7 @@ class Context: globals ['test'] = self.pythonPathFuncs.test locals={} - for name, value in self.locals.items(): + for name, value in list(self.locals.items()): if (isinstance (value, ContextVariable)): value = value.rawValue() locals [name] = value @@ -393,7 +393,7 @@ class Context: if (isinstance (result, ContextVariable)): return result.value() return result - except Exception, e: + except Exception as e: # An exception occured evaluating the template, return the exception as text self.log.warn ("Exception occurred evaluating python path, exception: " + str (e)) return "Exception: %s" % str (e) @@ -406,7 +406,7 @@ class Context: # Evaluate this path try: return self.evaluate (path.strip ()) - except PathNotFoundException, e: + except PathNotFoundException as e: # Path didn't exist, try the next one pass # No paths evaluated - raise exception. @@ -424,7 +424,7 @@ class Context: try: result = self.traversePath (allPaths[0], canCall = 0) return self.true - except PathNotFoundException, e: + except PathNotFoundException as e: # Look at the rest of the paths. pass @@ -435,7 +435,7 @@ class Context: # If this is part of a "exists: path1 | exists: path2" path then we need to look at the actual result. if (pathResult): return self.true - except PathNotFoundException, e: + except PathNotFoundException as e: pass # If we get this far then there are *no* paths that exist. return self.false @@ -446,7 +446,7 @@ class Context: # The first path is for us try: return self.traversePath (allPaths[0], canCall = 0) - except PathNotFoundException, e: + except PathNotFoundException as e: # Try the rest of the paths. pass @@ -454,7 +454,7 @@ class Context: # Evaluate this path try: return self.evaluate (path.strip ()) - except PathNotFoundException, e: + except PathNotFoundException as e: pass # No path evaluated - raise error raise PATHNOTFOUNDEXCEPTION @@ -465,7 +465,7 @@ class Context: # Evaluate what I was passed try: pathResult = self.evaluate (expr) - except PathNotFoundException, e: + except PathNotFoundException as e: # In SimpleTAL the result of "not: no/such/path" should be TRUE not FALSE. return self.true @@ -492,7 +492,7 @@ class Context: #self.log.debug ("Evaluating String %s" % expr) result = "" skipCount = 0 - for position in xrange (0,len (expr)): + for position in range (0,len (expr)): if (skipCount > 0): skipCount -= 1 else: @@ -510,16 +510,16 @@ class Context: # Evaluate the path - missing paths raise exceptions as normal. try: pathResult = self.evaluate (path) - except PathNotFoundException, e: + except PathNotFoundException as e: # This part of the path didn't evaluate to anything - leave blank - pathResult = u'' + pathResult = '' if (pathResult is not None): - if (isinstance (pathResult, types.UnicodeType)): + if (isinstance (pathResult, str)): result += pathResult else: # THIS IS NOT A BUG! # Use Unicode in Context if you aren't using Ascii! - result += unicode (pathResult) + result += str (pathResult) skipCount = endPos - position else: # It's a variable @@ -530,18 +530,18 @@ class Context: # Evaluate the variable - missing paths raise exceptions as normal. try: pathResult = self.traversePath (path) - except PathNotFoundException, e: + except PathNotFoundException as e: # This part of the path didn't evaluate to anything - leave blank - pathResult = u'' + pathResult = '' if (pathResult is not None): - if (isinstance (pathResult, types.UnicodeType)): + if (isinstance (pathResult, str)): result += pathResult else: # THIS IS NOT A BUG! # Use Unicode in Context if you aren't using Ascii! - result += unicode (pathResult) + result += str (pathResult) skipCount = endPos - position - 1 - except IndexError, e: + except IndexError as e: # Trailing $ sign - just suppress it self.log.warn ("Trailing $ detected") pass @@ -564,19 +564,19 @@ class Context: path = pathList[0] if path.startswith ('?'): path = path[1:] - if self.locals.has_key(path): + if path in self.locals: path = self.locals[path] if (isinstance (path, ContextVariable)): path = path.value() - elif (callable (path)):path = apply (path, ()) + elif (callable (path)):path = path(*()) - elif self.globals.has_key(path): + elif path in self.globals: path = self.globals[path] if (isinstance (path, ContextVariable)): path = path.value() - elif (callable (path)):path = apply (path, ()) + elif (callable (path)):path = path(*()) #self.log.debug ("Dereferenced to %s" % path) - if self.locals.has_key(path): + if path in self.locals: val = self.locals[path] - elif self.globals.has_key(path): + elif path in self.globals: val = self.globals[path] else: # If we can't find it then raise an exception @@ -586,20 +586,20 @@ class Context: #self.log.debug ("Looking for path element %s" % path) if path.startswith ('?'): path = path[1:] - if self.locals.has_key(path): + if path in self.locals: path = self.locals[path] if (isinstance (path, ContextVariable)): path = path.value() - elif (callable (path)):path = apply (path, ()) - elif self.globals.has_key(path): + elif (callable (path)):path = path(*()) + elif path in self.globals: path = self.globals[path] if (isinstance (path, ContextVariable)): path = path.value() - elif (callable (path)):path = apply (path, ()) + elif (callable (path)):path = path(*()) #self.log.debug ("Dereferenced to %s" % path) try: if (isinstance (val, ContextVariable)): temp = val.value((index,pathList)) - elif (callable (val)):temp = apply (val, ()) + elif (callable (val)):temp = val(*()) else: temp = val - except ContextVariable, e: + except ContextVariable as e: # Fast path for those functions that return values return e.value() @@ -619,9 +619,9 @@ class Context: if (canCall): try: if (isinstance (val, ContextVariable)): result = val.value((index,pathList)) - elif (callable (val)):result = apply (val, ()) + elif (callable (val)):result = val(*()) else: result = val - except ContextVariable, e: + except ContextVariable as e: # Fast path for those functions that return values return e.value() else: @@ -643,7 +643,7 @@ class Context: vars['attrs'] = None # Add all of these to the global context - for name in vars.keys(): + for name in list(vars.keys()): self.addGlobal (name,vars[name]) # Add also under CONTEXTS diff --git a/src/libs/python/bongo/external/simpletal/simpleTALUtils.py b/src/libs/python/bongo/external/simpletal/simpleTALUtils.py index 5295098..7940f1a 100644 --- a/src/libs/python/bongo/external/simpletal/simpleTALUtils.py +++ b/src/libs/python/bongo/external/simpletal/simpleTALUtils.py @@ -34,7 +34,7 @@ Module Dependencies: None """ -import StringIO, os, stat, threading, sys, codecs, sgmllib, cgi, re, types +import io, os, stat, threading, sys, codecs, sgmllib, cgi, re, types import bongo.external.simpletal, bongo.external.simpleTAL __version__ = simpletal.__version__ @@ -56,12 +56,12 @@ class HTMLStructureCleaner (sgmllib.SGMLParser): The method returns a unicode string which is suitable for addition to a simpleTALES.Context object. """ - if (isinstance (content, types.StringType)): + if (isinstance (content, bytes)): # Not unicode, convert converter = codecs.lookup (encoding)[1] - file = StringIO.StringIO (converter (content)[0]) - elif (isinstance (content, types.UnicodeType)): - file = StringIO.StringIO (content) + file = io.StringIO (converter (content)[0]) + elif (isinstance (content, str)): + file = io.StringIO (content) else: # Treat it as a file type object - and convert it if we have an encoding if (encoding is not None): @@ -70,7 +70,7 @@ class HTMLStructureCleaner (sgmllib.SGMLParser): else: file = content - self.outputFile = StringIO.StringIO (u"") + self.outputFile = io.StringIO ("") self.feed (file.read()) self.close() return self.outputFile.getvalue() @@ -85,10 +85,10 @@ class HTMLStructureCleaner (sgmllib.SGMLParser): self.outputFile.write (cgi.escape (data)) def handle_charref (self, ref): - self.outputFile.write (u'&#%s;' % ref) + self.outputFile.write ('&#%s;' % ref) def handle_entityref (self, ref): - self.outputFile.write (u'&%s;' % ref) + self.outputFile.write ('&%s;' % ref) class FastStringOutput: @@ -123,7 +123,7 @@ class TemplateCache: inputEncoding is only used for HTML templates, and should be the encoding that the template is stored in. """ - if (self.templateCache.has_key (name)): + if (name in self.templateCache): template, oldctime = self.templateCache [name] ctime = os.stat (name)[stat.ST_MTIME] if (oldctime == ctime): @@ -136,7 +136,7 @@ class TemplateCache: def getXMLTemplate (self, name): """ Name should be the path of an XML template file. """ - if (self.templateCache.has_key (name)): + if (name in self.templateCache): template, oldctime = self.templateCache [name] ctime = os.stat (name)[stat.ST_MTIME] if (oldctime == ctime): @@ -164,7 +164,7 @@ class TemplateCache: tempFile.close() self.templateCache [name] = (template, os.stat (name)[stat.ST_MTIME]) self.misses += 1 - except Exception, e: + except Exception as e: self.cacheLock.release() raise e @@ -216,7 +216,7 @@ class MacroExpansionInterpreter (simpleTAL.TemplateInterpreter): def cmdOutputStartTag (self, command, args): newAtts = [] - for att, value in self.originalAttributes.items(): + for att, value in list(self.originalAttributes.items()): if (self.macroArg is not None and att == "metal:define-macro"): newAtts.append (("metal:use-macro",self.macroArg)) elif (self.inMacro and att=="metal:define-slot"): @@ -251,19 +251,19 @@ class MacroExpansionInterpreter (simpleTAL.TemplateInterpreter): # End of the macro self.inMacro = 0 else: - if (isinstance (resultVal, types.UnicodeType)): + if (isinstance (resultVal, str)): self.file.write (resultVal) - elif (isinstance (resultVal, types.StringType)): - self.file.write (unicode (resultVal, 'ascii')) + elif (isinstance (resultVal, bytes)): + self.file.write (str (resultVal, 'ascii')) else: - self.file.write (unicode (str (resultVal), 'ascii')) + self.file.write (str (str (resultVal), 'ascii')) else: - if (isinstance (resultVal, types.UnicodeType)): + if (isinstance (resultVal, str)): self.file.write (cgi.escape (resultVal)) - elif (isinstance (resultVal, types.StringType)): - self.file.write (cgi.escape (unicode (resultVal, 'ascii'))) + elif (isinstance (resultVal, bytes)): + self.file.write (cgi.escape (str (resultVal, 'ascii'))) else: - self.file.write (cgi.escape (unicode (str (resultVal), 'ascii'))) + self.file.write (cgi.escape (str (str (resultVal), 'ascii'))) if (self.outputTag and not args[1]): self.file.write ('') @@ -279,7 +279,7 @@ class MacroExpansionInterpreter (simpleTAL.TemplateInterpreter): self.programCounter += 1 def ExpandMacros (context, template, outputEncoding="ISO-8859-1"): - out = StringIO.StringIO() + out = io.StringIO() interp = MacroExpansionInterpreter() interp.initialise (context, out) template.expand (context, out, outputEncoding=outputEncoding, interpreter=interp) diff --git a/src/libs/python/bongo/external/vobject/__init__.py b/src/libs/python/bongo/external/vobject/__init__.py index 8676eed..2e7f088 100644 --- a/src/libs/python/bongo/external/vobject/__init__.py +++ b/src/libs/python/bongo/external/vobject/__init__.py @@ -76,8 +76,8 @@ VObject Overview """ -import base, icalendar, vcard -from base import readComponents, readOne, newFromBehavior +from . import base, icalendar, vcard +from .base import readComponents, readOne, newFromBehavior def iCalendar(): return newFromBehavior('vcalendar', '2.0') diff --git a/src/libs/python/bongo/external/vobject/base.py b/src/libs/python/bongo/external/vobject/base.py index fa956ff..bcee5ef 100644 --- a/src/libs/python/bongo/external/vobject/base.py +++ b/src/libs/python/bongo/external/vobject/base.py @@ -1,12 +1,12 @@ """vobject module for reading vCard and vCalendar files.""" # generator support for Python 2.3 -from __future__ import generators + import re import sys import logging -import StringIO +import io import string import exceptions import codecs @@ -21,11 +21,11 @@ if not logger.handlers: logger.setLevel(logging.ERROR) # Log errors DEBUG = False # Don't waste time on debug calls #----------------------------------- Constants --------------------------------- -CR = unichr(13) -LF = unichr(10) +CR = chr(13) +LF = chr(10) CRLF = CR + LF -SPACE = unichr(32) -TAB = unichr(9) +SPACE = chr(32) +TAB = chr(9) SPACEORTAB = SPACE + TAB #-------------------------------- Useful modules ------------------------------- # use doctest, it kills two birds with one stone and docstrings often become @@ -112,7 +112,7 @@ class VBase(object): else: try: return self.behavior.transformToNative(self) - except Exception, e: + except Exception as e: # wrap errors in transformation in a ParseError lineNumber = getattr(self, 'lineNumber', None) if isinstance(e, ParseError): @@ -123,7 +123,7 @@ class VBase(object): msg = "In transformToNative, unhandled exception: %s: %s" msg = msg % (sys.exc_info()[0], sys.exc_info()[1]) new_error = ParseError(msg, lineNumber) - raise ParseError, new_error, sys.exc_info()[2] + raise ParseError(new_error).with_traceback(sys.exc_info()[2]) def transformFromNative(self): @@ -142,7 +142,7 @@ class VBase(object): if self.isNative and self.behavior and self.behavior.hasNative: try: return self.behavior.transformFromNative(self) - except Exception, e: + except Exception as e: # wrap errors in transformation in a NativeError lineNumber = getattr(self, 'lineNumber', None) if isinstance(e, NativeError): @@ -153,7 +153,7 @@ class VBase(object): msg = "In transformFromNative, unhandled exception: %s: %s" msg = msg % (sys.exc_info()[0], sys.exc_info()[1]) new_error = NativeError(msg, lineNumber) - raise NativeError, new_error, sys.exc_info()[2] + raise NativeError(new_error).with_traceback(sys.exc_info()[2]) else: return self def transformChildrenToNative(self): @@ -188,7 +188,7 @@ class VBase(object): return defaultSerialize(self, buf, lineLength) def ascii(s): - return unicode(s).encode('ascii', 'replace') + return str(s).encode('ascii', 'replace') class ContentLine(VBase): """Holds one content line for formats like vCard and vCalendar. @@ -234,7 +234,7 @@ class ContentLine(VBase): else: paramlist = self.params.setdefault(x[0].upper(), []) paramlist.extend(x[1:]) - map(updateTable, params) + list(map(updateTable, params)) qp = False if 'ENCODING' in self.params: if 'QUOTED-PRINTABLE' in self.params['ENCODING']: @@ -267,9 +267,9 @@ class ContentLine(VBase): elif name.endswith('_paramlist'): return self.params[name[:-10].upper().replace('_', '-')] else: - raise exceptions.AttributeError, name + raise exceptions.AttributeError(name) except KeyError: - raise exceptions.AttributeError, name + raise exceptions.AttributeError(name) def __setattr__(self, name, value): """Make params accessible via self.foo_param or self.foo_paramlist. @@ -304,7 +304,7 @@ class ContentLine(VBase): else: object.__delattr__(self, name) except KeyError: - raise exceptions.AttributeError, name + raise exceptions.AttributeError(name) def __str__(self): return "<"+ascii(self.name)+ascii(self.params)+ascii(self.value)+">" @@ -314,12 +314,12 @@ class ContentLine(VBase): def prettyPrint(self, level = 0, tabwidth=3): pre = ' ' * level * tabwidth - print pre, self.name + ":", ascii(self.value) + print(pre, self.name + ":", ascii(self.value)) if self.params: - lineKeys= self.params.keys() - print pre, "params for ", self.name +':' + lineKeys= list(self.params.keys()) + print(pre, "params for ", self.name +':') for aKey in lineKeys: - print pre + ' ' * tabwidth, aKey, ascii(self.params[aKey]) + print(pre + ' ' * tabwidth, aKey, ascii(self.params[aKey])) class Component(VBase): """A complex property that can contain multiple ContentLines. @@ -375,7 +375,7 @@ class Component(VBase): else: return self.contents[name.replace('_', '-')][0] except KeyError: - raise exceptions.AttributeError, name + raise exceptions.AttributeError(name) normal_attributes = ['contents','name','behavior','parentBehavior','group'] def __setattr__(self, name, value): @@ -409,7 +409,7 @@ class Component(VBase): else: object.__delattr__(self, name) except KeyError: - raise exceptions.AttributeError, name + raise exceptions.AttributeError(name) def add(self, objOrName, group = None): """Add objOrName to contents, set behavior if it can be inferred. @@ -444,7 +444,7 @@ class Component(VBase): def getChildren(self): """Return an iterable of all children.""" - for objList in self.contents.values(): + for objList in list(self.contents.values()): for obj in objList: yield obj def components(self): @@ -461,7 +461,7 @@ class Component(VBase): except: first = [] - items = [k for k in self.contents.keys() if k not in first] + items = [k for k in list(self.contents.keys()) if k not in first] items.sort() return first + items @@ -477,14 +477,14 @@ class Component(VBase): """Recursively replace children with their native representation.""" #sort to get dependency order right, like vtimezone before vevent for childArray in [self.contents[k] for k in self.sortChildKeys()]: - for i in xrange(len(childArray)): + for i in range(len(childArray)): childArray[i]=childArray[i].transformToNative() childArray[i].transformChildrenToNative() def transformChildrenFromNative(self, clearBehavior=True): """Recursively transform native children to vanilla representations.""" - for childArray in self.contents.values(): - for i in xrange(len(childArray)): + for childArray in list(self.contents.values()): + for i in range(len(childArray)): childArray[i]=childArray[i].transformFromNative() childArray[i].transformChildrenFromNative(clearBehavior) if clearBehavior: @@ -502,11 +502,11 @@ class Component(VBase): def prettyPrint(self, level = 0, tabwidth=3): pre = ' ' * level * tabwidth - print pre, self.name + print(pre, self.name) if isinstance(self, Component): for line in self.getChildren(): line.prettyPrint(level + 1, tabwidth) - print + print() class VObjectError(Exception): def __init__(self, message, lineNumber=None): @@ -686,14 +686,14 @@ def getLogicalLines(fp, allowQP=True): for match in logical_lines_re.finditer(val): line, n = wrap_re.subn('', match.group()) if line != '': - if type(line[0]) != unicode: + if type(line[0]) != str: line = line.decode('utf-8') yield line, lineNumber lineNumber += n else: quotedPrintable=False - newbuffer = StringIO.StringIO + newbuffer = io.StringIO logicalLine = newbuffer() lineNumber = 0 lineStartNumber = 0 @@ -702,7 +702,7 @@ def getLogicalLines(fp, allowQP=True): if line == '': break else: - if type(line[0]) != unicode: + if type(line[0]) != str: line = line.decode('utf-8') line = line.rstrip(CRLF) lineNumber += 1 @@ -753,7 +753,7 @@ def dquoteEscape(param): return param def foldOneLine(outbuf, input, lineLength = 75): - if type(input) in (str, unicode): input = StringIO.StringIO(input) + if type(input) in (str, str): input = io.StringIO(input) input.seek(0) outbuf.write(input.read(lineLength) + CRLF) brokenline = input.read(lineLength - 1) @@ -765,7 +765,7 @@ def defaultSerialize(obj, buf, lineLength): """Encode and fold obj and its children, write to buf or return a string.""" if buf: outbuf = buf - else: outbuf=StringIO.StringIO() + else: outbuf=io.StringIO() if isinstance(obj, Component): if obj.group is None: @@ -773,24 +773,24 @@ def defaultSerialize(obj, buf, lineLength): else: groupString = obj.group + '.' if obj.useBegin: - foldOneLine(outbuf, groupString + u"BEGIN:" + obj.name, lineLength) + foldOneLine(outbuf, groupString + "BEGIN:" + obj.name, lineLength) for child in obj.getSortedChildren(): #validate is recursive, we only need to validate once child.serialize(outbuf, lineLength, validate=False) if obj.useBegin: - foldOneLine(outbuf, groupString + u"END:" + obj.name, lineLength) + foldOneLine(outbuf, groupString + "END:" + obj.name, lineLength) if DEBUG: logger.debug("Finished %s" % obj.name.upper()) elif isinstance(obj, ContentLine): startedEncoded = obj.encoded #TODO: X- lines should be considered TEXT, and should be encoded as such if obj.behavior and not startedEncoded: obj.behavior.encode(obj) - s=StringIO.StringIO() #unfolded buffer + s=io.StringIO() #unfolded buffer if obj.group is not None: s.write(obj.group + '.') if DEBUG: logger.debug("Serializing line" + str(obj)) s.write(obj.name.upper()) - for key, paramvals in obj.params.iteritems(): + for key, paramvals in obj.params.items(): s.write(';' + key + '=' + ','.join(map(dquoteEscape, paramvals))) s.write(':' + obj.value) if obj.behavior and not startedEncoded: obj.behavior.decode(obj) @@ -841,8 +841,8 @@ def readComponents(streamOrString, validate=False, transform=True): """ - if isinstance(streamOrString, basestring): - stream = StringIO.StringIO(streamOrString) + if isinstance(streamOrString, str): + stream = io.StringIO(streamOrString) else: stream = streamOrString stack = Stack() @@ -886,7 +886,7 @@ def readComponents(streamOrString, validate=False, transform=True): def readOne(stream, validate=False, transform=True): """Return the first component from stream.""" - return readComponents(stream, validate, transform).next() + return next(readComponents(stream, validate, transform)) #--------------------------- version registry ---------------------------------- __behaviorRegistry={} @@ -946,5 +946,5 @@ def backslashEscape(s): #------------------- Testing and running functions ----------------------------- if __name__ == '__main__': - import tests + from . import tests tests._test() diff --git a/src/libs/python/bongo/external/vobject/behavior.py b/src/libs/python/bongo/external/vobject/behavior.py index 862640f..7195556 100644 --- a/src/libs/python/bongo/external/vobject/behavior.py +++ b/src/libs/python/bongo/external/vobject/behavior.py @@ -1,6 +1,6 @@ """Behavior (validation, encoding, and transformations) for vobjects.""" -import base +from . import base #------------------------ Abstract class for behavior -------------------------- class Behavior(object): @@ -79,7 +79,7 @@ class Behavior(object): return False name=child.name.upper() count[name] = count.get(name, 0) + 1 - for key, val in cls.knownChildren.iteritems(): + for key, val in cls.knownChildren.items(): if count.get(key,0) < val[0]: if raiseException: m = "%s components must contain at least %i %s" diff --git a/src/libs/python/bongo/external/vobject/icalendar.py b/src/libs/python/bongo/external/vobject/icalendar.py index 37e2149..923d65b 100644 --- a/src/libs/python/bongo/external/vobject/icalendar.py +++ b/src/libs/python/bongo/external/vobject/icalendar.py @@ -1,18 +1,18 @@ """Definitions and behavior for iCalendar, also known as vCalendar 2.0""" # generator support for Python 2.3 -from __future__ import generators + import string -import behavior +from . import behavior import bongo.external.dateutil.rrule as rrule import bongo.external.dateutil.tz as tz -import StringIO +import io import datetime import socket, random #for generating a UID import itertools -from base import VObjectError, NativeError, ValidateError, ParseError, \ +from .base import VObjectError, NativeError, ValidateError, ParseError, \ VBase, Component, ContentLine, logger, defaultSerialize, \ registerBehavior, backslashEscape, foldOneLine, \ newFromBehavior, CRLF, LF @@ -21,7 +21,7 @@ from base import VObjectError, NativeError, ValidateError, ParseError, \ DATENAMES = ("rdate", "exdate") RULENAMES = ("exrule", "rrule") DATESANDRULES = ("exrule", "rrule", "rdate", "exdate") -PRODID = u"-//PYVOBJECT//NONSGML Version 1//EN" +PRODID = "-//PYVOBJECT//NONSGML Version 1//EN" WEEKDAYS = "MO", "TU", "WE", "TH", "FR", "SA", "SU" FREQUENCIES = ('YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', @@ -86,18 +86,18 @@ class TimezoneComponent(Component): # workaround for dateutil failing to parse some experimental properties good_lines = ('rdate', 'rrule', 'dtstart', 'tzname', 'tzoffsetfrom', 'tzoffsetto', 'tzid') - buffer = StringIO.StringIO() + buffer = io.StringIO() def customSerialize(obj): if isinstance(obj, Component): - foldOneLine(buffer, u"BEGIN:" + obj.name) + foldOneLine(buffer, "BEGIN:" + obj.name) for child in obj.lines(): if child.name.lower() in good_lines: child.serialize(buffer, 75, validate=False) for comp in obj.components(): customSerialize(comp) - foldOneLine(buffer, u"END:" + obj.name) + foldOneLine(buffer, "END:" + obj.name) customSerialize(self) - return tz.tzical(StringIO.StringIO(str(buffer.getvalue()))).get() + return tz.tzical(io.StringIO(str(buffer.getvalue()))).get() def settzinfo(self, tzinfo, start=2000, end=2030): """Create appropriate objects in self to represent tzinfo. @@ -131,7 +131,7 @@ class TimezoneComponent(Component): working = {'daylight' : None, 'standard' : None} # rule may be based on the nth week of the month or the nth from the last - for year in xrange(start, end + 1): + for year in range(start, end + 1): newyear = datetime.datetime(year, 1, 1) for transitionTo in 'daylight', 'standard': transition = getTransition(transitionTo, year, tzinfo) @@ -275,7 +275,7 @@ class TimezoneComponent(Component): else: # return tzname for standard (non-DST) time notDST = datetime.timedelta(0) - for month in xrange(1,13): + for month in range(1,13): dt = datetime.datetime(2000, month, 1) if tzinfo.dst(dt) == notDST: return tzinfo.tzname(dt) @@ -291,9 +291,9 @@ class TimezoneComponent(Component): def prettyPrint(self, level, tabwidth): pre = ' ' * level * tabwidth - print pre, self.name - print pre, "TZID:", self.tzid - print + print(pre, self.name) + print(pre, "TZID:", self.tzid) + print() class RecurringComponent(Component): """A vCalendar component like VEVENT or VTODO which may recur. @@ -365,7 +365,7 @@ class RecurringComponent(Component): if name in DATENAMES: if type(line.value[0]) == datetime.datetime: - map(addfunc, line.value) + list(map(addfunc, line.value)) elif type(line.value) == datetime.date: for dt in line.value: addfunc(datetime.datetime(dt.year, dt.month, dt.day)) @@ -375,7 +375,7 @@ class RecurringComponent(Component): elif name in RULENAMES: try: dtstart = self.dtstart.value - except AttributeError, KeyError: + except AttributeError as KeyError: # if there's no dtstart, just return None return None # rrulestr complains about unicode, so cast to str @@ -426,7 +426,7 @@ class RecurringComponent(Component): self.add(name).value = setlist elif name in RULENAMES: for rule in setlist: - buf = StringIO.StringIO() + buf = io.StringIO() buf.write('FREQ=') buf.write(FREQUENCIES[rule._freq]) @@ -482,7 +482,7 @@ class RecurringComponent(Component): # byhour, byminute, bysecond are always ignored for now - for key, paramvals in values.iteritems(): + for key, paramvals in values.items(): buf.write(';') buf.write(key) buf.write('=') @@ -777,7 +777,7 @@ class VCalendar2_0(behavior.Behavior): findTzids(obj, tzidsUsed) oldtzids = [x.tzid.value for x in getattr(obj, 'vtimezone_list', [])] - for tzid in tzidsUsed.keys(): + for tzid in list(tzidsUsed.keys()): if tzid == 'UTC' or tzid in oldtzids: continue obj.add(TimezoneComponent(tzinfo=getTzid(tzid))) generateImplicitParameters = classmethod(generateImplicitParameters) @@ -799,7 +799,7 @@ class VTimezone(behavior.Behavior): def validate(cls, obj, raiseException, *args): return True #TODO: FIXME - if obj.contents.has_key('standard') or obj.contents.has_key('daylight'): + if 'standard' in obj.contents or 'daylight' in obj.contents: return super(VTimezone, cls).validate(obj, raiseException, *args) else: if raiseException: @@ -877,7 +877,7 @@ class VEvent(RecurringBehavior): } def validate(cls, obj, raiseException, *args): - if obj.contents.has_key('DTEND') and obj.contents.has_key('DURATION'): + if 'DTEND' in obj.contents and 'DURATION' in obj.contents: if raiseException: m = "VEVENT components cannot contain both DTEND and DURATION\ components" @@ -932,7 +932,7 @@ class VTodo(RecurringBehavior): } def validate(cls, obj, raiseException, *args): - if obj.contents.has_key('DUE') and obj.contents.has_key('DURATION'): + if 'DUE' in obj.contents and 'DURATION' in obj.contents: if raiseException: m = "VTODO components cannot contain both DUE and DURATION\ components" @@ -1252,11 +1252,11 @@ registerBehavior(FreeBusy) #------------------------ Registration of common classes ----------------------- utcDateTimeList = ['LAST-MODIFIED', 'CREATED', 'COMPLETED', 'DTSTAMP'] -map(lambda x: registerBehavior(UTCDateTimeBehavior, x), utcDateTimeList) +list(map(lambda x: registerBehavior(UTCDateTimeBehavior, x), utcDateTimeList)) dateTimeOrDateList = ['DTEND', 'DTSTART', 'DUE', 'RECURRENCE-ID'] -map(lambda x: registerBehavior(DateOrDateTimeBehavior, x), - dateTimeOrDateList) +list(map(lambda x: registerBehavior(DateOrDateTimeBehavior, x), + dateTimeOrDateList)) registerBehavior(MultiDateBehavior, 'RDATE') registerBehavior(MultiDateBehavior, 'EXDATE') @@ -1265,10 +1265,10 @@ registerBehavior(MultiDateBehavior, 'EXDATE') textList = ['CALSCALE', 'METHOD', 'PRODID', 'CLASS', 'COMMENT', 'DESCRIPTION', 'LOCATION', 'STATUS', 'SUMMARY', 'TRANSP', 'CONTACT', 'RELATED-TO', 'UID', 'ACTION', 'REQUEST-STATUS', 'TZID'] -map(lambda x: registerBehavior(TextBehavior, x), textList) +list(map(lambda x: registerBehavior(TextBehavior, x), textList)) multiTextList = ['CATEGORIES', 'RESOURCES'] -map(lambda x: registerBehavior(MultiTextBehavior, x), multiTextList) +list(map(lambda x: registerBehavior(MultiTextBehavior, x), multiTextList)) #------------------------ Serializing helper functions ------------------------- @@ -1351,7 +1351,7 @@ def isDuration(s): return (string.find(s, "P") != -1) and (string.find(s, "P") < 2) def stringToDate(s, tzinfos=None): - if tzinfos != None: print "Didn't expect a tzinfos here" + if tzinfos != None: print("Didn't expect a tzinfos here") year = int( s[0:4] ) month = int( s[4:6] ) day = int( s[6:8] ) @@ -1387,7 +1387,7 @@ def stringToTextValues(s, strict=False): raise ParseError(msg) else: #logger.error(msg) - print msg + print(msg) #vars which control state machine charIterator = enumerate(s) @@ -1398,7 +1398,7 @@ def stringToTextValues(s, strict=False): while True: try: - charIndex, char = charIterator.next() + charIndex, char = next(charIterator) except: char = "eof" @@ -1472,7 +1472,7 @@ def stringToDurations(s, strict=False): while True: try: - charIndex, char = charIterator.next() + charIndex, char = next(charIterator) except: charIndex += 1 char = "eof" @@ -1494,7 +1494,7 @@ def stringToDurations(s, strict=False): current = current + char #update this part when updating "read field" else: state = "error" - print "got unexpected character %s reading in duration: %s" % (char, s) + print("got unexpected character %s reading in duration: %s" % (char, s)) error("got unexpected character %s reading in duration: %s" % (char, s)) elif state == "read field": @@ -1591,9 +1591,9 @@ def getTransition(transitionTo, year, tzinfo): def generateDates(year, month=None, day=None): """Iterate over possible dates with unspecified values.""" - months = range(1, 13) - days = range(1, 32) - hours = range(0, 24) + months = list(range(1, 13)) + days = list(range(1, 32)) + hours = list(range(0, 24)) if month is None: for month in months: yield datetime.datetime(year, month, 1) @@ -1646,7 +1646,7 @@ def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020): if not dt_test(datetime.datetime(startYear, 1, 1)): return False - for year in xrange(startYear, endYear): + for year in range(startYear, endYear): for transitionTo in 'daylight', 'standard': t1=getTransition(transitionTo, year, tzinfo1) t2=getTransition(transitionTo, year, tzinfo2) @@ -1657,5 +1657,5 @@ def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020): #------------------- Testing and running functions ----------------------------- if __name__ == '__main__': - import tests + from . import tests tests._test() diff --git a/src/libs/python/bongo/external/vobject/tests.py b/src/libs/python/bongo/external/vobject/tests.py index 188d1ef..84920df 100644 --- a/src/libs/python/bongo/external/vobject/tests.py +++ b/src/libs/python/bongo/external/vobject/tests.py @@ -1,6 +1,6 @@ """Long or boring tests for vobjects.""" -import base, behavior, StringIO, icalendar, vcard, re, dateutil.tz, datetime +import base, behavior, io, icalendar, vcard, re, dateutil.tz, datetime # setuptools is required to run the unit tests from pkg_resources import resource_stream diff --git a/src/libs/python/bongo/external/vobject/vcard.py b/src/libs/python/bongo/external/vobject/vcard.py index be12785..6961667 100644 --- a/src/libs/python/bongo/external/vobject/vcard.py +++ b/src/libs/python/bongo/external/vobject/vcard.py @@ -1,179 +1,179 @@ -"""Definitions and behavior for vCard 3.0""" - -import behavior -import itertools - -from base import VObjectError, NativeError, ValidateError, ParseError, \ - VBase, Component, ContentLine, logger, defaultSerialize, \ - registerBehavior, backslashEscape - -from icalendar import TextBehavior - -#------------------------ vCard structs ---------------------------------------- - -class Name(object): - def __init__(self, family = '', given = '', additional = '', prefix = '', - suffix = ''): - """Each name attribute can be a string or a list of strings.""" - self.family = family - self.given = given - self.additional = additional - self.prefix = prefix - self.suffix = suffix - - def toString(val): - """Turn a string or array value into a string.""" - if type(val) in (list, tuple): - return ' '.join(val) - return val - toString = staticmethod(toString) - - def __str__(self): - eng_order = ('prefix', 'given', 'additional', 'family', 'suffix') - return ' '.join([self.toString(getattr(self, val)) for val in eng_order]) - - def __repr__(self): - return "" % self.__str__() - -class Address(object): - def __init__(self, street = '', city = '', region = '', code = '', - country = '', box = '', extended = ''): - """Each name attribute can be a string or a list of strings.""" - self.box = box - self.extended = extended - self.street = street - self.city = city - self.region = region - self.code = code - self.country = country - - def toString(val, join_char='\n'): - """Turn a string or array value into a string.""" - if type(val) in (list, tuple): - return join_char.join(val) - return val - toString = staticmethod(toString) - - lines = ('box', 'extended', 'street') - one_line = ('city', 'region', 'code') - - def __str__(self): - lines = '\n'.join([self.toString(getattr(self, val)) for val in self.lines if getattr(self, val)]) - one_line = tuple([self.toString(getattr(self, val), ' ') for val in self.one_line]) - lines += "\n%s, %s %s" % one_line - if self.country: - lines += '\n' + self.toString(self.country) - return lines - - def __repr__(self): - return "" % self.__str__().replace('\n', '\\n') - -#------------------------ Registered Behavior subclasses ----------------------- -class VCardBehavior(behavior.Behavior): - allowGroup = True - -class VCard3_0(VCardBehavior): - """vCard 3.0 behavior.""" - name = 'VCARD' - description = 'vCard 3.0, defined in rfc2426' - versionString = '3.0' - isComponent = True - sortFirst = ('version', 'prodid', 'uid') - knownChildren = {'N': (1, 1, None),#min, max, behaviorRegistry id - 'FN': (1, 1, None), - 'VERSION': (1, 1, None),#required, auto-generated - 'PRODID': (0, 1, None), - 'LABEL': (0, None, None), - 'UID': (0, None, None), - 'ADR': (0, None, None) - } - - def generateImplicitParameters(cls, obj): - """Create PRODID, VERSION, and VTIMEZONEs if needed. - - VTIMEZONEs will need to exist whenever TZID parameters exist or when - datetimes with tzinfo exist. - - """ - if not hasattr(obj, 'version'): - obj.add(ContentLine('VERSION', [], cls.versionString)) - generateImplicitParameters = classmethod(generateImplicitParameters) -registerBehavior(VCard3_0, default=True) - -class VCardTextBehavior(TextBehavior): - allowGroup = True - base64string = 'B' - -class FN(VCardTextBehavior): - name = "FN" - description = 'Formatted name' -registerBehavior(FN) - -class Label(VCardTextBehavior): - name = "Label" - description = 'Formatted address' -registerBehavior(FN) - -def toListOrString(string): - if string.find(',') >= 0: - return string.split(',') - return string - -def splitFields(string): - """Return a list of strings or lists from a Name or Address.""" - return [toListOrString(i) for i in string.split(';')] - -def toList(stringOrList): - if isinstance(stringOrList, basestring): - return [stringOrList] - return stringOrList - -def serializeFields(obj, order): - """Turn an object's fields into a ';' and ',' seperated string.""" - return ';'.join([','.join(toList(getattr(obj, val))) for val in order]) - -NAME_ORDER = ('family', 'given', 'additional', 'prefix', 'suffix') - -class NameBehavior(VCardBehavior): - """A structured name.""" - hasNative = True - - def transformToNative(obj): - """Turn obj.value into a Name.""" - if obj.isNative: return obj - obj.isNative = True - obj.value = Name(**dict(zip(NAME_ORDER, splitFields(obj.value)))) - return obj - transformToNative = staticmethod(transformToNative) - - def transformFromNative(obj): - """Replace the Name in obj.value with a string.""" - obj.isNative = False - obj.value = serializeFields(obj.value, NAME_ORDER) - return obj - transformFromNative = staticmethod(transformFromNative) -registerBehavior(NameBehavior, 'N') - -ADDRESS_ORDER = ('box', 'extended', 'street', 'city', 'region', 'code', - 'country') - -class AddressBehavior(VCardBehavior): - """A structured address.""" - hasNative = True - - def transformToNative(obj): - """Turn obj.value into an Address.""" - if obj.isNative: return obj - obj.isNative = True - obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value)))) - return obj - transformToNative = staticmethod(transformToNative) - - def transformFromNative(obj): - """Replace the Address in obj.value with a string.""" - obj.isNative = False - obj.value = serializeFields(obj.value, ADDRESS_ORDER) - return obj - transformFromNative = staticmethod(transformFromNative) -registerBehavior(AddressBehavior, 'ADR') - +"""Definitions and behavior for vCard 3.0""" + +from . import behavior +import itertools + +from .base import VObjectError, NativeError, ValidateError, ParseError, \ + VBase, Component, ContentLine, logger, defaultSerialize, \ + registerBehavior, backslashEscape + +from .icalendar import TextBehavior + +#------------------------ vCard structs ---------------------------------------- + +class Name(object): + def __init__(self, family = '', given = '', additional = '', prefix = '', + suffix = ''): + """Each name attribute can be a string or a list of strings.""" + self.family = family + self.given = given + self.additional = additional + self.prefix = prefix + self.suffix = suffix + + def toString(val): + """Turn a string or array value into a string.""" + if type(val) in (list, tuple): + return ' '.join(val) + return val + toString = staticmethod(toString) + + def __str__(self): + eng_order = ('prefix', 'given', 'additional', 'family', 'suffix') + return ' '.join([self.toString(getattr(self, val)) for val in eng_order]) + + def __repr__(self): + return "" % self.__str__() + +class Address(object): + def __init__(self, street = '', city = '', region = '', code = '', + country = '', box = '', extended = ''): + """Each name attribute can be a string or a list of strings.""" + self.box = box + self.extended = extended + self.street = street + self.city = city + self.region = region + self.code = code + self.country = country + + def toString(val, join_char='\n'): + """Turn a string or array value into a string.""" + if type(val) in (list, tuple): + return join_char.join(val) + return val + toString = staticmethod(toString) + + lines = ('box', 'extended', 'street') + one_line = ('city', 'region', 'code') + + def __str__(self): + lines = '\n'.join([self.toString(getattr(self, val)) for val in self.lines if getattr(self, val)]) + one_line = tuple([self.toString(getattr(self, val), ' ') for val in self.one_line]) + lines += "\n%s, %s %s" % one_line + if self.country: + lines += '\n' + self.toString(self.country) + return lines + + def __repr__(self): + return "" % self.__str__().replace('\n', '\\n') + +#------------------------ Registered Behavior subclasses ----------------------- +class VCardBehavior(behavior.Behavior): + allowGroup = True + +class VCard3_0(VCardBehavior): + """vCard 3.0 behavior.""" + name = 'VCARD' + description = 'vCard 3.0, defined in rfc2426' + versionString = '3.0' + isComponent = True + sortFirst = ('version', 'prodid', 'uid') + knownChildren = {'N': (1, 1, None),#min, max, behaviorRegistry id + 'FN': (1, 1, None), + 'VERSION': (1, 1, None),#required, auto-generated + 'PRODID': (0, 1, None), + 'LABEL': (0, None, None), + 'UID': (0, None, None), + 'ADR': (0, None, None) + } + + def generateImplicitParameters(cls, obj): + """Create PRODID, VERSION, and VTIMEZONEs if needed. + + VTIMEZONEs will need to exist whenever TZID parameters exist or when + datetimes with tzinfo exist. + + """ + if not hasattr(obj, 'version'): + obj.add(ContentLine('VERSION', [], cls.versionString)) + generateImplicitParameters = classmethod(generateImplicitParameters) +registerBehavior(VCard3_0, default=True) + +class VCardTextBehavior(TextBehavior): + allowGroup = True + base64string = 'B' + +class FN(VCardTextBehavior): + name = "FN" + description = 'Formatted name' +registerBehavior(FN) + +class Label(VCardTextBehavior): + name = "Label" + description = 'Formatted address' +registerBehavior(FN) + +def toListOrString(string): + if string.find(',') >= 0: + return string.split(',') + return string + +def splitFields(string): + """Return a list of strings or lists from a Name or Address.""" + return [toListOrString(i) for i in string.split(';')] + +def toList(stringOrList): + if isinstance(stringOrList, str): + return [stringOrList] + return stringOrList + +def serializeFields(obj, order): + """Turn an object's fields into a ';' and ',' seperated string.""" + return ';'.join([','.join(toList(getattr(obj, val))) for val in order]) + +NAME_ORDER = ('family', 'given', 'additional', 'prefix', 'suffix') + +class NameBehavior(VCardBehavior): + """A structured name.""" + hasNative = True + + def transformToNative(obj): + """Turn obj.value into a Name.""" + if obj.isNative: return obj + obj.isNative = True + obj.value = Name(**dict(list(zip(NAME_ORDER, splitFields(obj.value))))) + return obj + transformToNative = staticmethod(transformToNative) + + def transformFromNative(obj): + """Replace the Name in obj.value with a string.""" + obj.isNative = False + obj.value = serializeFields(obj.value, NAME_ORDER) + return obj + transformFromNative = staticmethod(transformFromNative) +registerBehavior(NameBehavior, 'N') + +ADDRESS_ORDER = ('box', 'extended', 'street', 'city', 'region', 'code', + 'country') + +class AddressBehavior(VCardBehavior): + """A structured address.""" + hasNative = True + + def transformToNative(obj): + """Turn obj.value into an Address.""" + if obj.isNative: return obj + obj.isNative = True + obj.value = Address(**dict(list(zip(ADDRESS_ORDER, splitFields(obj.value))))) + return obj + transformToNative = staticmethod(transformToNative) + + def transformFromNative(obj): + """Replace the Address in obj.value with a string.""" + obj.isNative = False + obj.value = serializeFields(obj.value, ADDRESS_ORDER) + return obj + transformFromNative = staticmethod(transformFromNative) +registerBehavior(AddressBehavior, 'ADR') + diff --git a/src/libs/python/bongo/external/vobject/win32tz.py b/src/libs/python/bongo/external/vobject/win32tz.py index 35f997b..4f76aaf 100644 --- a/src/libs/python/bongo/external/vobject/win32tz.py +++ b/src/libs/python/bongo/external/vobject/win32tz.py @@ -1,21 +1,21 @@ -import _winreg +import winreg import struct import datetime -handle=_winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) -tzparent=_winreg.OpenKey(handle, +handle=winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) +tzparent=winreg.OpenKey(handle, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones") -parentsize=_winreg.QueryInfoKey(tzparent)[0] +parentsize=winreg.QueryInfoKey(tzparent)[0] -localkey=_winreg.OpenKey(handle, +localkey=winreg.OpenKey(handle, "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation") WEEKS=datetime.timedelta(7) def list_timezones(): """Return a list of all time zones known to the system.""" l=[] - for i in xrange(parentsize): - l.append(_winreg.EnumKey(tzparent, i)) + for i in range(parentsize): + l.append(winreg.EnumKey(tzparent, i)) return l class win32tz(datetime.tzinfo): @@ -76,7 +76,7 @@ def pickNthWeekday(year, month, dayofweek, hour, minute, whichweek): first = datetime.datetime(year=year, month=month, hour=hour, minute=minute, day=1) weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7 + 1)) - for n in xrange(whichweek - 1, -1, -1): + for n in range(whichweek - 1, -1, -1): dt=weekdayone + n * WEEKS if dt.month == month: return dt @@ -87,7 +87,7 @@ class win32tz_data(object): def __init__(self, path): """Load path, or if path is empty, load local time.""" if path: - keydict=valuesToDict(_winreg.OpenKey(tzparent, path)) + keydict=valuesToDict(winreg.OpenKey(tzparent, path)) self.display = keydict['Display'] self.dstname = keydict['Dlt'] self.stdname = keydict['Std'] @@ -117,7 +117,7 @@ class win32tz_data(object): self.stdname = keydict['StandardName'] self.dstname = keydict['DaylightName'] - sourcekey=_winreg.OpenKey(tzparent, self.stdname) + sourcekey=winreg.OpenKey(tzparent, self.stdname) self.display = valuesToDict(sourcekey)['Display'] self.stdoffset = -keydict['Bias']-keydict['StandardBias'] @@ -143,9 +143,9 @@ class win32tz_data(object): def valuesToDict(key): """Convert a registry key's values to a dictionary.""" dict={} - size=_winreg.QueryInfoKey(key)[1] - for i in xrange(size): - dict[_winreg.EnumValue(key, i)[0]]=_winreg.EnumValue(key, i)[1] + size=winreg.QueryInfoKey(key)[1] + for i in range(size): + dict[winreg.EnumValue(key, i)[0]]=winreg.EnumValue(key, i)[1] return dict def _test(): diff --git a/src/libs/python/bongo/nmap/CommandStream.py b/src/libs/python/bongo/nmap/CommandStream.py index 08a8e84..3be64a6 100755 --- a/src/libs/python/bongo/nmap/CommandStream.py +++ b/src/libs/python/bongo/nmap/CommandStream.py @@ -164,7 +164,7 @@ class AddressBookIterator: def __iter__(self): return self - def next(self): + def __next__(self): if self.count > 0: r = AddressBookItem(self.stream) self.count -= 1 @@ -188,7 +188,7 @@ class ResponseIterator: def __iter__(self): return self - def next(self): + def __next__(self): r = self.stream.GetResponse() if r.code == 1000: if re.match("\d+", r.message): @@ -218,7 +218,7 @@ class CalendarInfoIterator: def __iter__(self): return self - def next(self): + def __next__(self): if self.count > 0: r = CalendarInfoItem(self.stream.readline()) self.count -= 1 @@ -243,7 +243,7 @@ class MessageInfoIterator: def __iter__(self): return self - def next(self): + def __next__(self): if self.count > 0: r = MessageInfoItem(self.stream.readline()) self.count -= 1 @@ -262,7 +262,7 @@ class ItemIterator(ResponseIterator): ResponseIterator.__init__(self, stream) self.propCount = propCount - def next(self): + def __next__(self): item = Item(ResponseIterator.next(self)) for i in range(self.propCount): r = self.stream.GetResponse() diff --git a/src/libs/python/bongo/nmap/NmapClient.py b/src/libs/python/bongo/nmap/NmapClient.py index 1ea2222..78d8bd5 100755 --- a/src/libs/python/bongo/nmap/NmapClient.py +++ b/src/libs/python/bongo/nmap/NmapClient.py @@ -1,8 +1,8 @@ import logging from libbongo.libs import msgapi -from CommandStream import * -from NmapConnection import NmapConnection -from cStringIO import StringIO +from .CommandStream import * +from .NmapConnection import NmapConnection +from io import StringIO import bongo __all__ = ["DocTypes", diff --git a/src/libs/python/bongo/nmap/NmapConnection.py b/src/libs/python/bongo/nmap/NmapConnection.py index a60f814..54d586e 100755 --- a/src/libs/python/bongo/nmap/NmapConnection.py +++ b/src/libs/python/bongo/nmap/NmapConnection.py @@ -1,5 +1,5 @@ import socket -import CommandStream +from . import CommandStream import bongo, libbongo.libs import logging diff --git a/src/libs/python/bongo/nmap/QueueClient.py b/src/libs/python/bongo/nmap/QueueClient.py index 38eb306..0c4d0b2 100755 --- a/src/libs/python/bongo/nmap/QueueClient.py +++ b/src/libs/python/bongo/nmap/QueueClient.py @@ -1,6 +1,6 @@ import logging import bongo, libbongo.libs -from CommandStream import * +from .CommandStream import * from StoreConnection import StoreConnection class RoutingFlags: diff --git a/src/libs/python/bongo/store/CommandStream.py b/src/libs/python/bongo/store/CommandStream.py index 1ba372d..12e6676 100644 --- a/src/libs/python/bongo/store/CommandStream.py +++ b/src/libs/python/bongo/store/CommandStream.py @@ -153,7 +153,7 @@ class ResponseIterator: def __iter__(self): return self - def next(self): + def __next__(self): r = self.stream.GetResponse() if r.code == 1000: if re.match("^\d+$", r.message): @@ -176,7 +176,7 @@ class ItemIterator(ResponseIterator): ResponseIterator.__init__(self, stream) self.propCount = propCount - def next(self): + def __next__(self): item = Item(ResponseIterator.next(self)) for i in range(self.propCount): r = self.stream.GetResponse() @@ -184,8 +184,8 @@ class ItemIterator(ResponseIterator): (key, length) = r.message.split(" ", 2) data = self.stream.Read(int(length)) try: - item.props[key] = unicode(data, "utf-8") - except UnicodeDecodeError, e: + item.props[key] = str(data, "utf-8") + except UnicodeDecodeError as e: self.stream.log.error("Bad utf-8 property from store: '%s'", data) item.props[key] = data @@ -198,7 +198,7 @@ class CollectionIterator(ResponseIterator): def __init__(self, stream): ResponseIterator.__init__(self, stream) - def next(self): + def __next__(self): collection = Collection(ResponseIterator.next(self)) return collection diff --git a/src/libs/python/bongo/store/QueueClient.py b/src/libs/python/bongo/store/QueueClient.py index 717c2da..ac2298d 100644 --- a/src/libs/python/bongo/store/QueueClient.py +++ b/src/libs/python/bongo/store/QueueClient.py @@ -1,7 +1,7 @@ import logging import bongo -from CommandStream import * -from StoreConnection import StoreConnection +from .CommandStream import * +from .StoreConnection import StoreConnection class RoutingFlags: NoFlags = 0 diff --git a/src/libs/python/bongo/store/StoreClient.py b/src/libs/python/bongo/store/StoreClient.py index 0f149ab..c021608 100644 --- a/src/libs/python/bongo/store/StoreClient.py +++ b/src/libs/python/bongo/store/StoreClient.py @@ -1,12 +1,12 @@ import logging -from CommandStream import * -from StoreConnection import StoreConnection -from cStringIO import StringIO +from .CommandStream import * +from .StoreConnection import StoreConnection +from io import StringIO import bongo import re import time import random -import md5 +import hashlib import socket import string @@ -52,7 +52,7 @@ class DocFlags: # reverse the names hash so we can look up flags by name revNames = {} - for name, flag in names.items(): + for name, flag in list(names.items()): revNames[flag] = name # some helpful functions @@ -65,13 +65,13 @@ class DocFlags: ByName = staticmethod(ByName) def AllFlags(): - return DocFlags.names.keys() + return list(DocFlags.names.keys()) AllFlags = staticmethod(AllFlags) def GetMask(hash): flags = mask = 0 - for flag, status in hash.items(): + for flag, status in list(hash.items()): if status: flags = flags | flag mask = mask | flag @@ -157,15 +157,15 @@ class CalendarACL : return self.acl def _GetUid (self, *args): - t = long(time.time() * 1000) - r = long(random.random() * 100000000000000000L) + t = int(time.time() * 1000) + r = int(random.random() * 100000000000000000) try: a = socket.gethostbyname(socket.gethostname()) except: # if we can't get a network address, just imagine one - a = random.random() * 100000000000000000L + a = random.random() * 100000000000000000 data = str(t) + ' ' + str (r) + ' ' + str(a) + ' ' + str(args) - data = md5.md5(data).hexdigest() + data = hashlib.md5(data).hexdigest() return data @@ -312,7 +312,7 @@ class CalendarACL : address = split[0] password = split[1] - if addresses.has_key(address) : + if address in addresses : entry = addresses[address] else : entry = { "password": password, "rights": 0 } @@ -321,7 +321,7 @@ class CalendarACL : entry["rights"] = entry["rights"] | rights elif principal.startswith("token:") : password = principal[len("token:"):] - if (passwords.has_key(password)) : + if (password in passwords) : passwords[password] = passwords[password] | rights else : passwords[password] = rights @@ -701,8 +701,8 @@ class StoreClient: (key, length) = r.message.split(" ", 2) raw_data = self.stream.Read(int(length)) try: - data = unicode(raw_data, "utf-8") - except UnicodeDecodeError, e: + data = str(raw_data, "utf-8") + except UnicodeDecodeError as e: data = self.force_utf8(raw_data) # eat the \r\n afterward self.stream.Read(2) @@ -721,15 +721,15 @@ class StoreClient: (key, length) = r.message.split(" ", 2) raw_data = self.stream.Read(int(length)) try: - props[key] = unicode(raw_data, "utf-8") - except UnicodeDecodeError, e: + props[key] = str(raw_data, "utf-8") + except UnicodeDecodeError as e: data = self.force_utf8(raw_data) # eat the \r\n afterward self.stream.Read(2) r = self.stream.GetResponse() # automatically pull out imap_uid from Bongo 0.3. - if name is None and not props.has_key("nmap.mail.imapuid"): + if name is None and "nmap.mail.imapuid" not in props: self.stream.Write("PROPGET %s nmap.mail.imapuid" % (doc)) r = self.stream.GetResponse() if r.code != 2001: @@ -947,4 +947,3 @@ class StoreClient: def Reset(self) : self.stream.Write("RESET\r\n") self.stream.GetResponse() - diff --git a/src/libs/python/bongo/store/StoreConnection.py b/src/libs/python/bongo/store/StoreConnection.py index 9bbf0dd..18979d0 100644 --- a/src/libs/python/bongo/store/StoreConnection.py +++ b/src/libs/python/bongo/store/StoreConnection.py @@ -1,5 +1,5 @@ import socket -import CommandStream +from . import CommandStream import bongo import logging
Name