Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
self.ui.collectingdata(None, self)
imapobj = self.imapserver.acquireconnection()
try:
msgsToFetch = self._msgs_to_fetch(
imapobj, min_date=min_date, min_uid=min_uid)
if not msgsToFetch:
return # No messages to sync
# Get the flags and UIDs for these. single-quotes prevent
# imaplib2 from quoting the sequence.
#
# NB: msgsToFetch are sequential numbers, not UID's
res_type, response = imapobj.fetch("'%s'"% msgsToFetch,
'(FLAGS X-GM-LABELS UID)')
if res_type != 'OK':
six.reraise(OfflineImapError,
OfflineImapError(
"FETCHING UIDs in folder [%s]%s failed. "%
(self.getrepository(), self) +
"Server responded '[%s] %s'"%
(res_type, response),
OfflineImapError.ERROR.FOLDER),
exc_info()[2])
finally:
self.imapserver.releaseconnection(imapobj)
for messagestr in response:
# looks like: '1 (FLAGS (\\Seen Old) X-GM-LABELS (\\Inbox \\Favorites) UID 4807)' or None if no msg
# Discard initial message number.
if messagestr == None:
continue
messagestr = messagestr.split(' ', 1)[1]
def savemessageflags(self, uid, flags):
imapobj = self.imapserver.acquireconnection()
try:
try:
imapobj.select(self.getfullname())
except imapobj.readonly:
UIBase.getglobalui().flagstoreadonly(self, [uid], flags)
return
result = imapobj.uid('store', '%d' % uid, 'FLAGS',
imaputil.flagsmaildir2imap(flags))
assert result[0] == 'OK', 'Error with store: ' + r[1]
finally:
self.imapserver.releaseconnection(imapobj)
result = result[1][0]
if not result:
self.messagelist[uid]['flags'] = flags
else:
flags = imaputil.flags2hash(imaputil.imapsplit(result)[1])['FLAGS']
self.messagelist[uid]['flags'] = imaputil.flagsimap2maildir(flags)
def savemessage_searchforheader(self, imapobj, headername, headervalue):
if imapobj.untagged_responses.has_key('APPENDUID'):
return long(imapobj.untagged_responses['APPENDUID'][-1].split(' ')[1])
ui = UIBase.getglobalui()
ui.debug('imap', 'savemessage_searchforheader called for %s: %s' % \
(headername, headervalue))
# Now find the UID it got.
headervalue = imapobj._quote(headervalue)
try:
matchinguids = imapobj.uid('search', 'HEADER', headername, headervalue)[1][0]
except imapobj.error, err:
# 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))
return 0
ui.debug('imap', 'savemessage_searchforheader got initial matchinguids: ' + repr(matchinguids))
if matchinguids == '':
ui.debug('imap', "savemessage_searchforheader: UID SEARCH for message with header %s yielded no results" % headername)
return 0
def syncitall(accounts, config):
currentThread().setExitMessage('SYNC_WITH_TIMER_TERMINATE')
ui = UIBase.getglobalui()
threads = threadutil.threadlist()
mbnames.init(config, accounts)
for accountname in accounts:
syncaccount(threads, config, accountname)
# Wait for the threads to finish.
threads.reset()
try:
labels_str = '(' + ' '.join([imaputil.quote(lb) for lb in labels]) + ')'
# Coalesce uid's into ranges
uid_str = imaputil.uid_sequence(uidlist)
result = self._store_to_imap(imapobj, uid_str, arg, labels_str)
except imapobj.readonly:
self.ui.labelstoreadonly(self, uidlist, labels)
return None
finally:
self.imapserver.releaseconnection(imapobj)
if result:
retlabels = imaputil.flags2hash(imaputil.imapsplit(result)[1])['X-GM-LABELS']
retlabels = set([imaputil.dequote(lb) for lb in imaputil.imapsplit(retlabels)])
return retlabels
return None
if result != 'OK':
raise OfflineImapError("Could not list the folders for"
" repository %s. Server responded: %s"%
(self.name, self, str(listresult)),
OfflineImapError.ERROR.FOLDER)
finally:
self.imapserver.releaseconnection(imapobj)
for s in listresult:
if s == None or \
(isinstance(s, str) and s == ''):
# Bug in imaplib: empty strings in results from
# literals. TODO: still relevant?
continue
try:
flags, delim, name = imaputil.imapsplit(s)
except ValueError:
self.ui.error(
"could not correctly parse server response; got: %s"% s)
raise
flaglist = [x.lower() for x in imaputil.flagsplit(flags)]
if '\\noselect' in flaglist:
continue
retval.append(self.getfoldertype()(self.imapserver, name,
self))
# Add all folderincludes
if len(self.folderincludes):
imapobj = self.imapserver.acquireconnection()
try:
for foldername in self.folderincludes:
try:
imapobj.select(imaputil.utf8_IMAP(foldername), readonly=True)
if self.delim == None:
listres = imapobj.list(self.reference, '""')[1]
if listres == [None] or listres == None:
# Some buggy IMAP servers do not respond well to LIST "" ""
# Work around them.
listres = imapobj.list(self.reference, '"*"')[1]
if listres == [None] or listres == None:
# No Folders were returned. This occurs, e.g. if the
# 'reference' prefix does not exist on the mail
# server. Raise exception.
err = "Server '%s' returned no folders in '%s'"% \
(self.repos.getname(), self.reference)
self.ui.warn(err)
raise Exception(err)
self.delim, self.root = \
imaputil.imapsplit(listres[0])[1:]
self.delim = imaputil.dequote(self.delim)
self.root = imaputil.dequote(self.root)
with self.connectionlock:
self.assignedconnections.append(imapobj)
self.lastowner[imapobj] = curThread.ident
return imapobj
except Exception as e:
"""If we are here then we did not succeed in getting a
connection - we should clean up and then re-raise the
error..."""
self.semaphore.release()
severity = OfflineImapError.ERROR.REPO
if type(e) == gaierror:
(probably severity MESSAGE) if e.g. no message with
this UID could be found.
"""
data = self._fetch_from_imap(str(uid), self.retrycount)
# data looks now e.g.
#[('320 (X-GM-LABELS (...) UID 17061 BODY[] {2565}','msgbody....')]
# we only asked for one message, and that msg is in data[0].
# msbody is in [0][1].
body = data[0][1].replace("\r\n", "\n")
# Embed the labels into the message headers
if self.synclabels:
m = re.search('X-GM-LABELS\s*[(](.*)[)]', data[0][0])
if m:
labels = set([imaputil.dequote(lb) for lb in imaputil.imapsplit(m.group(1))])
else:
labels = set()
labels = labels - self.ignorelabels
labels_str = imaputil.format_labels_string(self.labelsheader, sorted(labels))
# First remove old label headers that may be in the message content retrieved
# from gmail Then add a labels header with current gmail labels.
body = self.deletemessageheaders(body, self.labelsheader)
body = self.addmessageheader(body, '\n', self.labelsheader, labels_str)
if len(body)>200:
dbg_output = "%s...%s"% (str(body)[:150], str(body)[-50:])
else:
dbg_output = body
self.ui.debug('imap', "Returned object from fetching %d: '%s'"%
def _messagelabels_aux(self, arg, uidlist, labels):
"""Common code to savemessagelabels and addmessagelabels"""
labels = labels - self.ignorelabels
uidlist = [uid for uid in uidlist if uid > 0]
if len(uidlist) > 0:
imapobj = self.imapserver.acquireconnection()
try:
labels_str = '(' + ' '.join([imaputil.quote(lb) for lb in labels]) + ')'
# Coalesce uid's into ranges
uid_str = imaputil.uid_sequence(uidlist)
result = self._store_to_imap(imapobj, uid_str, arg, labels_str)
except imapobj.readonly:
self.ui.labelstoreadonly(self, uidlist, labels)
return None
finally:
self.imapserver.releaseconnection(imapobj)
if result:
retlabels = imaputil.flags2hash(imaputil.imapsplit(result)[1])['X-GM-LABELS']
retlabels = set([imaputil.dequote(lb) for lb in imaputil.imapsplit(retlabels)])
return retlabels
return None
operation + 'FLAGS',
imaputil.flagsmaildir2imap(flags))
assert r[0] == 'OK', 'Error with store: ' + r[1]
r = r[1]
finally:
self.imapserver.releaseconnection(imapobj)
# Some IMAP servers do not always return a result. Therefore,
# only update the ones that it talks about, and manually fix
# the others.
needupdate = copy(uidlist)
for result in r:
if result == None:
# Compensate for servers that don't return anything from
# STORE.
continue
attributehash = imaputil.flags2hash(imaputil.imapsplit(result)[1])
if not ('UID' in attributehash and 'FLAGS' in attributehash):
# Compensate for servers that don't return a UID attribute.
continue
flags = attributehash['FLAGS']
uid = long(attributehash['UID'])
self.messagelist[uid]['flags'] = imaputil.flagsimap2maildir(flags)
try:
needupdate.remove(uid)
except ValueError: # Let it slide if it's not in the list
pass
for uid in needupdate:
if operation == '+':
for flag in flags:
if not flag in self.messagelist[uid]['flags']:
self.messagelist[uid]['flags'].append(flag)
self.messagelist[uid]['flags'].sort()