Save ui as self.ui in folder/Base class

Rather than regetting the ui with UIBase.getglobalui() all the time, we get it once in the base class and let all derivative classes just make use of self.ui rather than refetching the ui all the time, this makes for a bit less code and shorter lines.

Signed-off-by: Sebastian Spaeth <Sebastian@SSpaeth.de>
Signed-off-by: Nicolas Sebrecht <nicolas.s-dev@laposte.net>
This commit is contained in:
Sebastian Spaeth 2011-01-05 17:00:57 +01:00 committed by Nicolas Sebrecht
parent 67089248da
commit de618d84f3
3 changed files with 46 additions and 49 deletions

View File

@ -19,13 +19,15 @@
from threading import * from threading import *
from offlineimap import threadutil from offlineimap import threadutil
from offlineimap.threadutil import InstanceLimitedThread from offlineimap.threadutil import InstanceLimitedThread
from offlineimap.ui import UIBase from offlineimap.ui import getglobalui
import os.path, re import os.path
import re
import sys import sys
class BaseFolder: class BaseFolder:
def __init__(self): def __init__(self):
self.uidlock = Lock() self.uidlock = Lock()
self.ui = getglobalui()
def getname(self): def getname(self):
"""Returns name""" """Returns name"""
@ -202,8 +204,8 @@ class BaseFolder:
def syncmessagesto_neguid_msg(self, uid, dest, applyto, register = 1): def syncmessagesto_neguid_msg(self, uid, dest, applyto, register = 1):
if register: if register:
UIBase.getglobalui().registerthread(self.getaccountname()) self.ui.registerthread(self.getaccountname())
UIBase.getglobalui().copyingmessage(uid, self, applyto) self.ui.copyingmessage(uid, self, applyto)
successobject = None successobject = None
successuid = None successuid = None
message = self.getmessage(uid) message = self.getmessage(uid)
@ -269,8 +271,8 @@ class BaseFolder:
# really needed. # really needed.
try: try:
if register: if register:
UIBase.getglobalui().registerthread(self.getaccountname()) self.ui.registerthread(self.getaccountname())
UIBase.getglobalui().copyingmessage(uid, self, applyto) self.ui.copyingmessage(uid, self, applyto)
message = '' message = ''
# If any of the destinations actually stores the message body, # If any of the destinations actually stores the message body,
# load it up. # load it up.
@ -289,7 +291,7 @@ class BaseFolder:
self.deletemessage(uid) self.deletemessage(uid)
uid = newuid uid = newuid
except: except:
UIBase.getglobalui().warn("ERROR attempting to copy message " + str(uid) \ self.ui.warn("ERROR attempting to copy message " + str(uid) \
+ " for account " + self.getaccountname() + ":" + str(sys.exc_info()[1])) + " for account " + self.getaccountname() + ":" + str(sys.exc_info()[1]))
@ -334,7 +336,7 @@ class BaseFolder:
if not uid in self_messagelist: if not uid in self_messagelist:
deletelist.append(uid) deletelist.append(uid)
if len(deletelist): if len(deletelist):
UIBase.getglobalui().deletingmessages(deletelist, applyto) self.ui.deletingmessages(deletelist, applyto)
for object in applyto: for object in applyto:
object.deletemessages(deletelist) object.deletemessages(deletelist)
@ -375,10 +377,10 @@ class BaseFolder:
for object in applyto: for object in applyto:
for flag in addflaglist.keys(): for flag in addflaglist.keys():
UIBase.getglobalui().addingflags(addflaglist[flag], flag, [object]) self.ui.addingflags(addflaglist[flag], flag, [object])
object.addmessagesflags(addflaglist[flag], [flag]) object.addmessagesflags(addflaglist[flag], [flag])
for flag in delflaglist.keys(): for flag in delflaglist.keys():
UIBase.getglobalui().deletingflags(delflaglist[flag], flag, [object]) self.ui.deletingflags(delflaglist[flag], flag, [object])
object.deletemessagesflags(delflaglist[flag], [flag]) object.deletemessagesflags(delflaglist[flag], [flag])
def syncmessagesto(self, dest, applyto = None): def syncmessagesto(self, dest, applyto = None):
@ -394,7 +396,7 @@ class BaseFolder:
try: try:
self.syncmessagesto_neguid(dest, applyto) self.syncmessagesto_neguid(dest, applyto)
except: except:
UIBase.getglobalui().warn("ERROR attempting to handle negative uids " \ self.ui.warn("ERROR attempting to handle negative uids " \
+ "for account " + self.getaccountname() + ":" + str(sys.exc_info()[1])) + "for account " + self.getaccountname() + ":" + str(sys.exc_info()[1]))
#all threads launched here are in try / except clauses when they copy anyway... #all threads launched here are in try / except clauses when they copy anyway...
@ -403,7 +405,7 @@ class BaseFolder:
try: try:
self.syncmessagesto_delete(dest, applyto) self.syncmessagesto_delete(dest, applyto)
except: except:
UIBase.getglobalui().warn("ERROR attempting to delete messages " \ self.ui.warn("ERROR attempting to delete messages " \
+ "for account " + self.getaccountname() + ":" + str(sys.exc_info()[1])) + "for account " + self.getaccountname() + ":" + str(sys.exc_info()[1]))
# Now, the message lists should be identical wrt the uids present. # Now, the message lists should be identical wrt the uids present.
@ -413,7 +415,7 @@ class BaseFolder:
try: try:
self.syncmessagesto_flags(dest, applyto) self.syncmessagesto_flags(dest, applyto)
except: except:
UIBase.getglobalui().warn("ERROR attempting to sync flags " \ self.ui.warn("ERROR attempting to sync flags " \
+ "for account " + self.getaccountname() + ":" + str(sys.exc_info()[1])) + "for account " + self.getaccountname() + ":" + str(sys.exc_info()[1]))

View File

@ -19,7 +19,6 @@
from Base import BaseFolder from Base import BaseFolder
import imaplib import imaplib
from offlineimap import imaputil, imaplibutil from offlineimap import imaputil, imaplibutil
from offlineimap.ui import UIBase
from offlineimap.version import versionstr from offlineimap.version import versionstr
import rfc822, time, string, random, binascii, re import rfc822, time, string, random, binascii, re
from StringIO import StringIO from StringIO import StringIO
@ -41,6 +40,7 @@ class IMAPFolder(BaseFolder):
self.repository = repository self.repository = repository
self.randomgenerator = random.Random() self.randomgenerator = random.Random()
BaseFolder.__init__(self) BaseFolder.__init__(self)
#self.ui is set in BaseFolder
def selectro(self, imapobj): def selectro(self, imapobj):
"""Select this folder when we do not need write access. """Select this folder when we do not need write access.
@ -188,7 +188,7 @@ class IMAPFolder(BaseFolder):
messagestr = string.split(messagestr, maxsplit = 1)[1] messagestr = string.split(messagestr, maxsplit = 1)[1]
options = imaputil.flags2hash(messagestr) options = imaputil.flags2hash(messagestr)
if not options.has_key('UID'): if not options.has_key('UID'):
UIBase.getglobalui().warn('No UID in message with options %s' %\ self.ui.warn('No UID in message with options %s' %\
str(options), str(options),
minor = 1) minor = 1)
else: else:
@ -201,12 +201,11 @@ class IMAPFolder(BaseFolder):
return self.messagelist return self.messagelist
def getmessage(self, uid): def getmessage(self, uid):
ui = UIBase.getglobalui()
imapobj = self.imapserver.acquireconnection() imapobj = self.imapserver.acquireconnection()
try: try:
imapobj.select(self.getfullname(), readonly = 1) imapobj.select(self.getfullname(), readonly = 1)
initialresult = imapobj.uid('fetch', '%d' % uid, '(BODY.PEEK[])') initialresult = imapobj.uid('fetch', '%d' % uid, '(BODY.PEEK[])')
ui.debug('imap', 'Returned object from fetching %d: %s' % \ self.ui.debug('imap', 'Returned object from fetching %d: %s' % \
(uid, str(initialresult))) (uid, str(initialresult)))
return initialresult[1][0][1].replace("\r\n", "\n") return initialresult[1][0][1].replace("\r\n", "\n")
@ -230,31 +229,29 @@ class IMAPFolder(BaseFolder):
return (headername, headervalue) return (headername, headervalue)
def savemessage_addheader(self, content, headername, headervalue): def savemessage_addheader(self, content, headername, headervalue):
ui = UIBase.getglobalui() self.ui.debug('imap',
ui.debug('imap',
'savemessage_addheader: called to add %s: %s' % (headername, 'savemessage_addheader: called to add %s: %s' % (headername,
headervalue)) headervalue))
insertionpoint = content.find("\r\n") insertionpoint = content.find("\r\n")
ui.debug('imap', 'savemessage_addheader: insertionpoint = %d' % insertionpoint) self.ui.debug('imap', 'savemessage_addheader: insertionpoint = %d' % insertionpoint)
leader = content[0:insertionpoint] leader = content[0:insertionpoint]
ui.debug('imap', 'savemessage_addheader: leader = %s' % repr(leader)) self.ui.debug('imap', 'savemessage_addheader: leader = %s' % repr(leader))
if insertionpoint == 0 or insertionpoint == -1: if insertionpoint == 0 or insertionpoint == -1:
newline = '' newline = ''
insertionpoint = 0 insertionpoint = 0
else: else:
newline = "\r\n" newline = "\r\n"
newline += "%s: %s" % (headername, headervalue) newline += "%s: %s" % (headername, headervalue)
ui.debug('imap', 'savemessage_addheader: newline = ' + repr(newline)) self.ui.debug('imap', 'savemessage_addheader: newline = ' + repr(newline))
trailer = content[insertionpoint:] trailer = content[insertionpoint:]
ui.debug('imap', 'savemessage_addheader: trailer = ' + repr(trailer)) self.ui.debug('imap', 'savemessage_addheader: trailer = ' + repr(trailer))
return leader + newline + trailer return leader + newline + trailer
def savemessage_searchforheader(self, imapobj, headername, headervalue): def savemessage_searchforheader(self, imapobj, headername, headervalue):
if imapobj.untagged_responses.has_key('APPENDUID'): if imapobj.untagged_responses.has_key('APPENDUID'):
return long(imapobj.untagged_responses['APPENDUID'][-1].split(' ')[1]) return long(imapobj.untagged_responses['APPENDUID'][-1].split(' ')[1])
ui = UIBase.getglobalui() self.ui.debug('imap', 'savemessage_searchforheader called for %s: %s' % \
ui.debug('imap', 'savemessage_searchforheader called for %s: %s' % \
(headername, headervalue)) (headername, headervalue))
# Now find the UID it got. # Now find the UID it got.
headervalue = imapobj._quote(headervalue) headervalue = imapobj._quote(headervalue)
@ -262,16 +259,16 @@ class IMAPFolder(BaseFolder):
matchinguids = imapobj.uid('search', 'HEADER', headername, headervalue)[1][0] matchinguids = imapobj.uid('search', 'HEADER', headername, headervalue)[1][0]
except imapobj.error, err: except imapobj.error, err:
# IMAP server doesn't implement search or had a problem. # IMAP server doesn't implement search or had a problem.
ui.debug('imap', "savemessage_searchforheader: got IMAP error '%s' while attempting to UID SEARCH for message with header %s" % (err, headername)) self.ui.debug('imap', "savemessage_searchforheader: got IMAP error '%s' while attempting to UID SEARCH for message with header %s" % (err, headername))
return 0 return 0
ui.debug('imap', 'savemessage_searchforheader got initial matchinguids: ' + repr(matchinguids)) self.ui.debug('imap', 'savemessage_searchforheader got initial matchinguids: ' + repr(matchinguids))
if matchinguids == '': if matchinguids == '':
ui.debug('imap', "savemessage_searchforheader: UID SEARCH for message with header %s yielded no results" % headername) self.ui.debug('imap', "savemessage_searchforheader: UID SEARCH for message with header %s yielded no results" % headername)
return 0 return 0
matchinguids = matchinguids.split(' ') matchinguids = matchinguids.split(' ')
ui.debug('imap', 'savemessage_searchforheader: matchinguids now ' + \ self.ui.debug('imap', 'savemessage_searchforheader: matchinguids now ' + \
repr(matchinguids)) repr(matchinguids))
if len(matchinguids) != 1 or matchinguids[0] == None: if len(matchinguids) != 1 or matchinguids[0] == None:
raise ValueError, "While attempting to find UID for message with header %s, got wrong-sized matchinguids of %s" % (headername, str(matchinguids)) raise ValueError, "While attempting to find UID for message with header %s, got wrong-sized matchinguids of %s" % (headername, str(matchinguids))
@ -280,13 +277,12 @@ class IMAPFolder(BaseFolder):
def savemessage(self, uid, content, flags, rtime): def savemessage(self, uid, content, flags, rtime):
imapobj = self.imapserver.acquireconnection() imapobj = self.imapserver.acquireconnection()
ui = UIBase.getglobalui() self.ui.debug('imap', 'savemessage: called')
ui.debug('imap', 'savemessage: called')
try: try:
try: try:
imapobj.select(self.getfullname()) # Needed for search imapobj.select(self.getfullname()) # Needed for search
except imapobj.readonly: except imapobj.readonly:
ui.msgtoreadonly(self, uid, content, flags) self.ui.msgtoreadonly(self, uid, content, flags)
# Return indicating message taken, but no UID assigned. # Return indicating message taken, but no UID assigned.
# Fudge it. # Fudge it.
return 0 return 0
@ -324,17 +320,17 @@ class IMAPFolder(BaseFolder):
# but some IMAP servers nonetheless choke on 1902. # but some IMAP servers nonetheless choke on 1902.
date = imaplib.Time2Internaldate(time.localtime()) date = imaplib.Time2Internaldate(time.localtime())
ui.debug('imap', 'savemessage: using date ' + str(date)) self.ui.debug('imap', 'savemessage: using date ' + str(date))
content = re.sub("(?<!\r)\n", "\r\n", content) content = re.sub("(?<!\r)\n", "\r\n", content)
ui.debug('imap', 'savemessage: initial content is: ' + repr(content)) self.ui.debug('imap', 'savemessage: initial content is: ' + repr(content))
(headername, headervalue) = self.savemessage_getnewheader(content) (headername, headervalue) = self.savemessage_getnewheader(content)
ui.debug('imap', 'savemessage: new headers are: %s: %s' % \ self.ui.debug('imap', 'savemessage: new headers are: %s: %s' % \
(headername, headervalue)) (headername, headervalue))
content = self.savemessage_addheader(content, headername, content = self.savemessage_addheader(content, headername,
headervalue) headervalue)
ui.debug('imap', 'savemessage: new content is: ' + repr(content)) self.ui.debug('imap', 'savemessage: new content is: ' + repr(content))
ui.debug('imap', 'savemessage: new content length is ' + \ self.ui.debug('imap', 'savemessage: new content length is ' + \
str(len(content))) str(len(content)))
assert(imapobj.append(self.getfullname(), assert(imapobj.append(self.getfullname(),
@ -345,12 +341,12 @@ class IMAPFolder(BaseFolder):
assert(imapobj.check()[0] == 'OK') assert(imapobj.check()[0] == 'OK')
# Keep trying until we get the UID. # Keep trying until we get the UID.
ui.debug('imap', 'savemessage: first attempt to get new UID') self.ui.debug('imap', 'savemessage: first attempt to get new UID')
uid = self.savemessage_searchforheader(imapobj, headername, uid = self.savemessage_searchforheader(imapobj, headername,
headervalue) headervalue)
# See docs for savemessage in Base.py for explanation of this and other return values # See docs for savemessage in Base.py for explanation of this and other return values
if uid <= 0: if uid <= 0:
ui.debug('imap', 'savemessage: first attempt to get new UID failed. Going to run a NOOP and try again.') self.ui.debug('imap', 'savemessage: first attempt to get new UID failed. Going to run a NOOP and try again.')
assert(imapobj.noop()[0] == 'OK') assert(imapobj.noop()[0] == 'OK')
uid = self.savemessage_searchforheader(imapobj, headername, uid = self.savemessage_searchforheader(imapobj, headername,
headervalue) headervalue)
@ -360,7 +356,7 @@ class IMAPFolder(BaseFolder):
if uid: # avoid UID FETCH 0 crash happening later on if uid: # avoid UID FETCH 0 crash happening later on
self.messagelist[uid] = {'uid': uid, 'flags': flags} self.messagelist[uid] = {'uid': uid, 'flags': flags}
ui.debug('imap', 'savemessage: returning %d' % uid) self.ui.debug('imap', 'savemessage: returning %d' % uid)
return uid return uid
def savemessageflags(self, uid, flags): def savemessageflags(self, uid, flags):
@ -369,7 +365,7 @@ class IMAPFolder(BaseFolder):
try: try:
imapobj.select(self.getfullname()) imapobj.select(self.getfullname())
except imapobj.readonly: except imapobj.readonly:
UIBase.getglobalui().flagstoreadonly(self, [uid], flags) self.ui.flagstoreadonly(self, [uid], flags)
return return
result = imapobj.uid('store', '%d' % uid, 'FLAGS', result = imapobj.uid('store', '%d' % uid, 'FLAGS',
imaputil.flagsmaildir2imap(flags)) imaputil.flagsmaildir2imap(flags))
@ -413,7 +409,7 @@ class IMAPFolder(BaseFolder):
try: try:
imapobj.select(self.getfullname()) imapobj.select(self.getfullname())
except imapobj.readonly: except imapobj.readonly:
UIBase.getglobalui().flagstoreadonly(self, uidlist, flags) self.ui.flagstoreadonly(self, uidlist, flags)
return return
r = imapobj.uid('store', r = imapobj.uid('store',
imaputil.listjoin(uidlist), imaputil.listjoin(uidlist),
@ -472,7 +468,7 @@ class IMAPFolder(BaseFolder):
try: try:
imapobj.select(self.getfullname()) imapobj.select(self.getfullname())
except imapobj.readonly: except imapobj.readonly:
UIBase.getglobalui().deletereadonly(self, uidlist) self.ui.deletereadonly(self, uidlist)
return return
if self.expunge: if self.expunge:
assert(imapobj.expunge()[0] == 'OK') assert(imapobj.expunge()[0] == 'OK')

View File

@ -19,7 +19,6 @@
import os.path, os, re, time, socket import os.path, os, re, time, socket
from Base import BaseFolder from Base import BaseFolder
from offlineimap import imaputil from offlineimap import imaputil
from offlineimap.ui import UIBase
from threading import Lock from threading import Lock
try: try:
@ -61,6 +60,7 @@ class MaildirFolder(BaseFolder):
self.repository = repository self.repository = repository
self.accountname = accountname self.accountname = accountname
BaseFolder.__init__(self) BaseFolder.__init__(self)
#self.ui is set in BaseFolder.init()
def getaccountname(self): def getaccountname(self):
return self.accountname return self.accountname
@ -193,8 +193,7 @@ class MaildirFolder(BaseFolder):
def savemessage(self, uid, content, flags, rtime): def savemessage(self, uid, content, flags, rtime):
# This function only ever saves to tmp/, # This function only ever saves to tmp/,
# but it calls savemessageflags() to actually save to cur/ or new/. # but it calls savemessageflags() to actually save to cur/ or new/.
ui = UIBase.getglobalui() self.ui.debug('maildir', 'savemessage: called to write with flags %s and content %s' % \
ui.debug('maildir', 'savemessage: called to write with flags %s and content %s' % \
(repr(flags), repr(content))) (repr(flags), repr(content)))
if uid < 0: if uid < 0:
# We cannot assign a new uid. # We cannot assign a new uid.
@ -226,7 +225,7 @@ class MaildirFolder(BaseFolder):
else: else:
break break
tmpmessagename = messagename.split(',')[0] tmpmessagename = messagename.split(',')[0]
ui.debug('maildir', 'savemessage: using temporary name %s' % tmpmessagename) self.ui.debug('maildir', 'savemessage: using temporary name %s' % tmpmessagename)
file = open(os.path.join(tmpdir, tmpmessagename), "wt") file = open(os.path.join(tmpdir, tmpmessagename), "wt")
file.write(content) file.write(content)
@ -238,7 +237,7 @@ class MaildirFolder(BaseFolder):
file.close() file.close()
if rtime != None: if rtime != None:
os.utime(os.path.join(tmpdir,tmpmessagename), (rtime,rtime)) os.utime(os.path.join(tmpdir,tmpmessagename), (rtime,rtime))
ui.debug('maildir', 'savemessage: moving from %s to %s' % \ self.ui.debug('maildir', 'savemessage: moving from %s to %s' % \
(tmpmessagename, messagename)) (tmpmessagename, messagename))
if tmpmessagename != messagename: # then rename it if tmpmessagename != messagename: # then rename it
os.rename(os.path.join(tmpdir, tmpmessagename), os.rename(os.path.join(tmpdir, tmpmessagename),
@ -256,7 +255,7 @@ class MaildirFolder(BaseFolder):
self.messagelist[uid] = {'uid': uid, 'flags': [], self.messagelist[uid] = {'uid': uid, 'flags': [],
'filename': os.path.join(tmpdir, messagename)} 'filename': os.path.join(tmpdir, messagename)}
self.savemessageflags(uid, flags) self.savemessageflags(uid, flags)
ui.debug('maildir', 'savemessage: returning uid %d' % uid) self.ui.debug('maildir', 'savemessage: returning uid %d' % uid)
return uid return uid
def getmessageflags(self, uid): def getmessageflags(self, uid):