aboutsummaryrefslogtreecommitdiff
path: root/ayatanawebmail
diff options
context:
space:
mode:
authorRobert Tari <robert@tari.in>2020-08-17 17:40:59 +0200
committerRobert Tari <robert@tari.in>2020-08-17 17:40:59 +0200
commit711050055339f6a14f0c3da4d3d28f707b97a102 (patch)
tree7c69fbc7809bc1592bab47c811c6d9e4ddf964da /ayatanawebmail
downloadayatana-webmail-711050055339f6a14f0c3da4d3d28f707b97a102.tar.gz
ayatana-webmail-711050055339f6a14f0c3da4d3d28f707b97a102.tar.bz2
ayatana-webmail-711050055339f6a14f0c3da4d3d28f707b97a102.zip
Initial port from Unity Mail
Diffstat (limited to 'ayatanawebmail')
-rwxr-xr-xayatanawebmail/__init__.py1
-rwxr-xr-xayatanawebmail/accounts.py57
-rwxr-xr-xayatanawebmail/actions.py36
-rwxr-xr-xayatanawebmail/appdata.py18
-rwxr-xr-xayatanawebmail/application.py1207
-rwxr-xr-xayatanawebmail/common.py112
-rwxr-xr-xayatanawebmail/dialog.py583
-rwxr-xr-xayatanawebmail/idler.py79
-rwxr-xr-xayatanawebmail/imaplib2.py2618
9 files changed, 4711 insertions, 0 deletions
diff --git a/ayatanawebmail/__init__.py b/ayatanawebmail/__init__.py
new file mode 100755
index 0000000..8b13789
--- /dev/null
+++ b/ayatanawebmail/__init__.py
@@ -0,0 +1 @@
+
diff --git a/ayatanawebmail/accounts.py b/ayatanawebmail/accounts.py
new file mode 100755
index 0000000..c21af56
--- /dev/null
+++ b/ayatanawebmail/accounts.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Ayatana Webmail, message actions dialog
+# Authors: Robert Tari <robert@tari.in>
+# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html
+
+import gi
+
+gi.require_version('Gtk', '3.0')
+
+from gi.repository import Gtk
+from ayatanawebmail.appdata import APPNAME
+
+class DialogAccounts(Gtk.Dialog):
+
+ def __init__(self, strKey, getDataPath, lstAccounts):
+
+ Gtk.Dialog.__init__(self, _('Select account'), None, 0, (Gtk.STOCK_OK, Gtk.ResponseType.OK))
+
+ self.lstURLs = []
+ self.set_icon_from_file(getDataPath('/usr/share/icons/hicolor/scalable/apps/' + APPNAME + '.svg'))
+ self.set_position(Gtk.WindowPosition.CENTER)
+ oImage = Gtk.Image()
+ oImage.set_from_file(getDataPath('/usr/share/icons/hicolor/scalable/apps/' + APPNAME + '.svg'))
+ oImage.props.valign = Gtk.Align.START
+ oImage.props.icon_size = Gtk.IconSize.DIALOG
+ oGrid = Gtk.Grid(border_width=10, row_spacing=2, column_spacing=10)
+ oGrid.attach(oImage, 0, 0, 1, 4)
+ oGrid.attach(Gtk.Label('<b>'+_('Which account\'s command/web page would you like to open?')+'</b>', use_markup=True, xalign=0, margin_bottom=10), 1, 0, 1, 1)
+
+ for nIndex, dctAccount in enumerate(lstAccounts):
+
+ self.__dict__['oRadioButton' + str(nIndex)] = Gtk.RadioButton.new_with_label_from_widget(None if not 'oRadioButton0' in self.__dict__ else self.__dict__['oRadioButton0'], dctAccount['Login'] + '@' + dctAccount['Host'])
+ self.__dict__['oRadioButton' + str(nIndex)].props.valign = Gtk.Align.START
+
+ if nIndex == len(lstAccounts) - 1:
+ self.__dict__['oRadioButton' + str(nIndex)].props.vexpand = True
+
+ oGrid.attach(self.__dict__['oRadioButton' + str(nIndex)] , 1, 1 + nIndex, 1, 1)
+ self.lstURLs.append(dctAccount[strKey])
+
+ self.get_content_area().add(oGrid)
+ self.connect('response', self.onResponse)
+ self.set_keep_above(True)
+ self.show_all()
+ self.strURL = None
+
+ def onResponse(self, oWidget, nResponse):
+
+ if nResponse == Gtk.ResponseType.OK:
+
+ for nIndex, strURL in enumerate(self.lstURLs):
+
+ if self.__dict__['oRadioButton' + str(nIndex)].get_active():
+
+ self.strURL = strURL
+ break
diff --git a/ayatanawebmail/actions.py b/ayatanawebmail/actions.py
new file mode 100755
index 0000000..03ea6bf
--- /dev/null
+++ b/ayatanawebmail/actions.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Ayatana Webmail, message actions dialog
+# Authors: Robert Tari <robert@tari.in>
+# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html
+
+from gi.repository import Gtk
+from ayatanawebmail.common import getDataPath
+from ayatanawebmail.appdata import APPNAME
+
+class DialogActions(Gtk.Dialog):
+
+ def __init__(self, strSender, strSubject):
+
+ Gtk.Dialog.__init__(self, _('Message actions'), None, 0, (_('Delete'), 100, _('Mark as read'), 200, _('Open message/Run command'), 300))
+ self.set_icon_from_file(getDataPath('/usr/share/icons/hicolor/scalable/apps/' + APPNAME + '.svg'))
+ self.set_position(Gtk.WindowPosition.CENTER)
+ oImage = Gtk.Image()
+ oImage.set_from_file(getDataPath('/usr/share/icons/hicolor/scalable/apps/' + APPNAME + '.svg'))
+ oImage.props.valign = Gtk.Align.START
+ oImage.props.icon_size = Gtk.IconSize.DIALOG
+ oGrid = Gtk.Grid(border_width=10, row_spacing=2, column_spacing=10)
+ oGrid.attach(oImage, 0, 0, 1, 4)
+ oGrid.attach(Gtk.Label('<b>' + _('Sender') + '</b>', xalign=0, use_markup=True, valign = Gtk.Align.START), 1, 0, 1, 1)
+ oGrid.attach(Gtk.Label(strSender, xalign=0, margin_bottom=10, valign = Gtk.Align.START), 1, 1, 1, 1)
+ oGrid.attach(Gtk.Label('<b>' + _('Subject') + '</b>', xalign=0, use_markup=True, valign = Gtk.Align.START), 1, 2, 1, 1)
+ oGrid.attach(Gtk.Label(strSubject, xalign=0, valign = Gtk.Align.START, vexpand = True), 1, 3, 1, 1)
+ self.get_content_area().add(oGrid)
+ oButtonDelete = self.get_widget_for_response(100)
+ oButtonDelete.set_image(Gtk.Image.new_from_icon_name('gtk-delete', Gtk.IconSize.BUTTON))
+ oButtonMark = self.get_widget_for_response(200)
+ oButtonMark.set_image(Gtk.Image.new_from_icon_name('gtk-ok', Gtk.IconSize.BUTTON))
+ oButtonOpen = self.get_widget_for_response(300)
+ oButtonOpen.set_image(Gtk.Image.new_from_icon_name('web-browser', Gtk.IconSize.BUTTON))
+ self.set_keep_above(True)
+ self.show_all()
diff --git a/ayatanawebmail/appdata.py b/ayatanawebmail/appdata.py
new file mode 100755
index 0000000..aba29f6
--- /dev/null
+++ b/ayatanawebmail/appdata.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+APPNAME = 'ayatanawebmail'
+APPEXECUTABLE='/usr/bin/ayatana-webmail'
+APPDEPENDENCIES = ['gir1.2-messagingmenu-1.0', 'python3-gi', 'gir1.2-gtk-3.0', 'gir1.2-notify-0.7', 'python3-secretstorage', 'gnome-session-canberra', 'python3-psutil', 'python3-babel', 'python3-urllib3']
+APPRECOMMENDS = ['gir1.2-unity-5.0']
+APPVERSION = '20.8.16'
+APPSHOWSETTINGS = 180603
+APPYEAR = '2016'
+APPTITLE = 'Ayatana Webmail'
+APPDESCRIPTION = 'Webmail notifications and actions for any desktop'
+APPLONGDESCRIPTION = 'Ayatana Webmail is an application that integrates your webmail into MATE, Xfce, LXDE and other environments. It displays notifications about incoming mail, shows the number of unread messages and displays subjects in the Messaging Menu. The Launcher item also has a quicklist that provides quick access to your mail folders (configured for GMail by default). It also allows you to quickly compose a new message. Ayatana Webmail starts automatically, all you have to do is to enter your accounts settings in a configuration dialog.'
+APPAUTHOR = 'Robert Tari'
+APPMAIL = 'robert@tari.in'
+APPURL = 'https://tari.in/www/software/ayatana-webmail/'
+APPKEYWORDS = ['ayatanawebmail', 'ayatana-webmail', 'e-mail','notification','gmail','indicator','mate','ayatana']
+APPDEBUG = []
diff --git a/ayatanawebmail/application.py b/ayatanawebmail/application.py
new file mode 100755
index 0000000..4c1ba92
--- /dev/null
+++ b/ayatanawebmail/application.py
@@ -0,0 +1,1207 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Ayatana Webmail, the main application class
+# Authors: Dmitry Shachnev <mitya57@gmail.com>
+# Robert Tari <robert@tari.in>
+# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html
+
+import gi
+
+gi.require_version('Gtk', '3.0')
+gi.require_version('Notify', '0.7')
+
+import email
+import email.errors
+import email.header
+import email.utils
+import dbus
+import dbus.service
+import logging
+import secretstorage
+import subprocess
+import sys
+import time
+import re
+import ayatanawebmail.imaplib2 as imaplib
+import os.path
+import os
+import urllib3
+import importlib
+import locale
+import psutil
+from gi.repository import Gio, GLib, Gtk, Notify
+from socket import error as socketerror
+from dbus.mainloop.glib import DBusGMainLoop
+from babel.dates import format_timedelta
+from ayatanawebmail.common import g_oTranslation, g_oSettings, openURLOrCommand, g_lstAccounts, g_dctDefaultURLs
+from ayatanawebmail.idler import Idler
+from ayatanawebmail.dialog import PreferencesDialog, MESSAGEACTION
+from ayatanawebmail.actions import DialogActions
+from ayatanawebmail.appdata import APPNAME
+
+urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+imaplib._MAXLINE = 500000#160000 # See discussion in LP: #1309566
+logger = logging.getLogger('Ayatana Webmail')
+logger.setLevel(logging.DEBUG)
+handler = logging.StreamHandler()
+handler.setFormatter(logging.Formatter('%(asctime)s: %(name)s: %(levelname)s: %(message)s'))
+logger.addHandler(handler)
+logger.propagate = False
+m_reThrid = re.compile(b'THRID (\\d+)')
+fixFormat = lambda string: string.replace('%(t0)s', '{t0}').replace('%(t1)s', '{t1}')
+
+def checkNetwork():
+
+ try:
+
+ oResult = urllib3.PoolManager().request('HEAD', 'https://www.google.com', timeout=5)
+ return True
+
+ except Exception as oException:
+
+ return False
+
+def decodeWrapper(header):
+
+ # Decodes an Email header, returns a string
+ # A hack for headers without a space between decoded name and email
+ try:
+
+ dec = email.header.decode_header(header.replace('=?=<', '=?= <'))
+
+ except email.errors.HeaderParseError:
+
+ logger.warning('Exception in decode, skipping.')
+ return header
+
+ parts = []
+
+ for dec_part in dec:
+
+ if dec_part[1]:
+
+ try:
+ parts.append(dec_part[0].decode(dec_part[1]))
+ except (AttributeError, LookupError, UnicodeDecodeError):
+ logger.warning('Exception in decode, skipping.')
+
+ elif isinstance(dec_part[0], bytes):
+
+ parts.append(dec_part[0].decode())
+
+ else:
+ parts.append(dec_part[0])
+
+ return str.join(' ', parts)
+
+def getHeaderWrapper(message, header_name, decode):
+
+ header = message[header_name]
+
+ if isinstance(header, str):
+
+ header = header.replace(' \r\n', '').replace('\r\n', '')
+ return (decodeWrapper(header) if decode else header)
+
+ return ''
+
+def getSenderName(sender):
+
+ # Strips address, and returns only name
+ sname = email.utils.parseaddr(sender)[0]
+
+ return sname if sname else sender
+
+class MessagingMenu(object):
+
+ oUnity = None
+ oMessagingMenu = None
+ oAppIndicator = None
+
+ def __init__(self, fnActivate, fnSettings, fnUpdateMessageAges, fnCheckNetwork):
+
+ self.fnActivate = fnActivate
+ self.launcher = None
+ self.nMenuItems = 0
+ self.nMessageAgeTimer = None
+ self.nNetworkTimer = GLib.timeout_add_seconds(60, fnCheckNetwork)
+ self.oMenuItemClear = None
+ self.oMailIcon = Gio.Icon.new_for_string('mail-unread')
+
+ try:
+
+ gi.require_version('Unity', '7.0')
+ self.oUnity = importlib.import_module('gi.repository.Unity')
+
+ strDesktopId = 'ayatana-webmail.desktop'
+
+ for strId in self.oUnity.LauncherFavorites.get_default().enumerate_ids():
+
+ if APPNAME in strId:
+
+ strDesktopId = strId
+ break
+
+ self.oLauncher = self.oUnity.LauncherEntry.get_for_desktop_id(strDesktopId)
+
+ except Exception as oException:
+
+ pass
+
+ lstProcesses = [oProcess.name() for oProcess in psutil.process_iter()]
+
+ if 'ayatana-indicator-messages-service' in lstProcesses:
+
+ try:
+
+ gi.require_version('AyatanaMessagingMenu', '1.0')
+ self.oMessagingMenu = importlib.import_module('gi.repository.AyatanaMessagingMenu')
+
+ except Exception as oException:
+
+ gi.require_version('MessagingMenu', '1.0')
+ self.oMessagingMenu = importlib.import_module('gi.repository.MessagingMenu')
+
+ elif 'indicator-messages-service' in lstProcesses:
+
+ gi.require_version('MessagingMenu', '1.0')
+ self.oMessagingMenu = importlib.import_module('gi.repository.MessagingMenu')
+
+ if self.oMessagingMenu:
+
+ self.oIndicator = self.oMessagingMenu.App(desktop_id='ayatana-webmail.desktop')
+ self.oIndicator.register()
+ self.oIndicator.connect('activate-source', lambda a, i: self.onMenuItemClicked(i))
+
+ return
+
+ if 'ayatana-indicator-application-service' in lstProcesses:
+
+ try:
+
+ gi.require_version('AyatanaAppIndicator3', '0.1')
+ self.oAppIndicator = importlib.import_module('gi.repository.AyatanaAppIndicator3')
+
+ except Exception as oException:
+
+ gi.require_version('AppIndicator3', '0.1')
+ self.oAppIndicator = importlib.import_module('gi.repository.AppIndicator3')
+
+ if not self.oAppIndicator:
+
+ gi.require_version('AppIndicator3', '0.1')
+ self.oAppIndicator = importlib.import_module('gi.repository.AppIndicator3')
+
+ self.oIndicator = self.oAppIndicator.Indicator.new(APPNAME, 'indicator-messages', self.oAppIndicator.IndicatorCategory.APPLICATION_STATUS)
+ self.oIndicator.set_attention_icon('indicator-messages-new')
+ self.oIndicator.set_status(self.oAppIndicator.IndicatorStatus.ACTIVE)
+ self.oMenu = Gtk.Menu()
+ self.oMenu.append(Gtk.SeparatorMenuItem())
+ oMenuItemInbox = Gtk.MenuItem()
+ oMenuItemInbox.connect('activate', lambda w: openURLOrCommand('Home'))
+ oBoxInbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)
+ oBoxInbox.pack_start(Gtk.Image.new_from_stock(Gtk.STOCK_HOME, Gtk.IconSize.MENU), False, False, 0)
+ oBoxInbox.pack_start(Gtk.Label(_('Open webmail home page'), xalign=0), True, True, 0)
+ oMenuItemInbox.add(oBoxInbox)
+ self.oMenu.append(oMenuItemInbox)
+ self.oMenuItemClear = Gtk.MenuItem(sensitive=False)
+ self.oMenuItemClear.connect('activate', self.onClear)
+ oBoxClear = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)
+ oBoxClear.pack_start(Gtk.Image.new_from_icon_name('gtk-clear', Gtk.IconSize.MENU), False, False, 0)
+ oBoxClear.pack_start(Gtk.Label(_('Clear'), xalign=0), True, True, 0)
+ self.oMenuItemClear.add(oBoxClear)
+ self.oMenu.append(self.oMenuItemClear)
+ oMenuItemConfig = Gtk.MenuItem()
+ oMenuItemConfig.connect('activate', lambda w: fnSettings())
+ oBoxConfig = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)
+ oBoxConfig.pack_start(Gtk.Image.new_from_stock(Gtk.STOCK_PREFERENCES, Gtk.IconSize.MENU), False, False, 0)
+ oBoxConfig.pack_start(Gtk.Label(_('Settings'), xalign=0), True, True, 0)
+ oMenuItemConfig.add(oBoxConfig)
+ self.oMenu.append(oMenuItemConfig)
+ self.oMenu.show_all()
+ self.oIndicator.set_menu(self.oMenu)
+ self.nMenuItems = len(self.oMenu.get_children())
+ self.nMessageAgeTimer = GLib.timeout_add_seconds(60, fnUpdateMessageAges)
+
+ def getMessageAge(self, nTimestamp):
+
+ nTimeDelta = int(time.time() - nTimestamp / 1000000)
+ strGranularity = 'minute'
+
+ if nTimeDelta > (7 * 24 * 60 * 60):
+ strGranularity = 'week'
+ elif nTimeDelta > (24 * 60 * 60):
+ strGranularity = 'day'
+ elif nTimeDelta > (60 * 60):
+ strGranularity = 'hour'
+ elif nTimeDelta < 60:
+ nTimeDelta = 61
+
+ return ' (' + format_timedelta(nTimeDelta, granularity=strGranularity, format='short', locale=locale.getlocale()[0]) + ')'
+
+ def onMenuItemClicked(self, strId):
+
+ if self.fnActivate(strId):
+
+ self.setCount(-1, True)
+
+ if not self.oMessagingMenu:
+ self.remove(strId)
+
+ def append(self, strId, strTitle, nTimestamp, bDrawAttention):
+
+ if self.oMessagingMenu:
+
+ self.oIndicator.append_source_with_time(strId, self.oMailIcon, strTitle, nTimestamp)
+
+ if bDrawAttention:
+ self.oIndicator.draw_attention(strId)
+
+ else:
+
+ oMenuItem = Gtk.MenuItem()
+ oMenuItem.props.name = strId
+ oMenuItem.connect('activate', lambda w: self.onMenuItemClicked(w.props.name))
+ oBox = Gtk.Box(Gtk.Orientation.HORIZONTAL, 6)
+ oBox.pack_start(Gtk.Image.new_from_icon_name('mail-unread', Gtk.IconSize.MENU), False, False, 0)
+ oBox.pack_start(Gtk.Label(strTitle + self.getMessageAge(nTimestamp), xalign=0), True, True, 0)
+ oMenuItem.add(oBox)
+ oMenuItem.show_all()
+ self.oMenu.insert(oMenuItem, len(self.oMenu.get_children()) - self.nMenuItems)
+
+ if bDrawAttention:
+ self.oIndicator.set_status(self.oAppIndicator.IndicatorStatus.ATTENTION)
+
+ self.oMenuItemClear.set_sensitive(True)
+
+ return False
+
+ def remove(self, strId):
+
+ if self.oMessagingMenu:
+
+ if self.oIndicator.has_source(strId):
+ self.oIndicator.remove_source(strId)
+
+ else:
+
+ for oItem in self.oMenu.get_children()[0:-self.nMenuItems]:
+
+ if oItem.props.name == strId:
+ self.oMenu.remove(oItem)
+
+ if len(self.oMenu.get_children()) - self.nMenuItems == 0:
+
+ self.oIndicator.set_status(self.oAppIndicator.IndicatorStatus.ACTIVE)
+ self.oMenuItemClear.set_sensitive(False)
+
+ return False
+
+ def hasSource(self, strId):
+
+ if self.oMessagingMenu:
+
+ return self.oIndicator.has_source(strId)
+
+ else:
+
+ for oItem in self.oMenu.get_children()[0:-self.nMenuItems]:
+
+ if oItem.props.name == strId:
+ return True
+
+ return False
+
+ def close(self):
+
+ if not self.oMessagingMenu:
+ GLib.source_remove(self.nMessageAgeTimer)
+
+ GLib.source_remove(self.nNetworkTimer)
+
+ def update(self, strId, nTimestamp):
+
+ for oItem in self.oMenu.get_children()[0:-self.nMenuItems]:
+
+ if oItem.props.name == strId:
+
+ oLabel = oItem.get_children()[0].get_children()[1]
+ oLabel.set_text(oLabel.get_text().rpartition(' (')[0] + self.getMessageAge(nTimestamp))
+
+ return False
+
+ def onClear(self, oWidget):
+
+ for oItem in self.oMenu.get_children()[0:-self.nMenuItems]:
+ self.oMenu.remove(oItem)
+
+ if len(self.oMenu.get_children()) - self.nMenuItems == 0:
+
+ self.oIndicator.set_status(self.oAppIndicator.IndicatorStatus.ACTIVE)
+ self.oMenuItemClear.set_sensitive(False)
+
+ self.setCount(0, True)
+
+ def setCount(self, nCount, bVisible):
+
+ if nCount == -1:
+
+ if self.oUnity:
+ nCount = self.oLauncher.get_property('count') - 1
+ elif not self.oMessagingMenu:
+ nCount = int(self.oIndicator.get_label()) - 1
+
+ bVisible = bVisible and ((nCount > 0) or not g_oSettings.get_boolean('hide-messages-count'))
+
+ if self.oUnity:
+
+ self.oLauncher.set_property('count', nCount)
+ self.oLauncher.set_property('count_visible', bVisible)
+
+ elif not self.oMessagingMenu:
+ self.oIndicator.set_label(str(nCount) if bVisible else '', '')
+
+ return False
+
+class SessionBus(dbus.service.Object):
+
+ fnSettings = None
+ fnClear = None
+ fnIsInit = None
+
+ def __init__(self, fnSettings, fnClear, fnIsInit, fnOpenURL):
+
+ oBusName = dbus.service.BusName('org.ayatana.webmail', bus=dbus.SessionBus())
+ dbus.service.Object.__init__(self, oBusName, '/org/ayatana/webmail')
+
+ self.fnSettings = fnSettings
+ self.fnClear = fnClear
+ self.fnIsInit = fnIsInit
+ self.fnOpenURL = fnOpenURL
+
+ @dbus.service.method('org.ayatana.webmail')
+ def settings(self):
+ self.fnSettings()
+
+ @dbus.service.method('org.ayatana.webmail')
+ def clear(self):
+ self.fnClear()
+
+ @dbus.service.method('org.ayatana.webmail')
+ def isinit(self):
+ return self.fnIsInit()
+
+ @dbus.service.method('org.ayatana.webmail', in_signature='s')
+ def openurl(self, strURL):
+ return self.fnOpenURL(strURL)
+
+class Connection(object):
+
+ def __init__(self, bDebug, host, port, login, passwd, folder, fnIdle, strInbox):
+
+ self.bDebug = bDebug
+ self.strHost = host
+ self.nPort = port
+ self.strLogin = login
+ self.strPasswd = passwd
+ self.oImap = None
+ self.lstNotificationQueue = []
+ self.oIdler = None
+ self.strFolder = folder
+ self.fnIdle = fnIdle
+ self.strInbox = strInbox
+ self.bConnecting = False
+
+ def close(self):
+
+ if self.oIdler:
+
+ self.oIdler.stop()
+ self.oIdler.join()
+ self.oIdler = None
+
+ if self.oImap:
+
+ try:
+ self.oImap.close()
+ except Exception as oException:
+ pass
+
+ try:
+ self.oImap.logout()
+ except Exception as oException:
+ pass
+
+ self.oImap = None
+
+ logger.info('"{0}:{1}" has been cleaned up.'.format(self.strLogin, self.strFolder))
+
+ def connect(self):
+
+ try:
+
+ self.oImap = imaplib.IMAP4_SSL(self.strHost, self.nPort, debug=int(self.bDebug)*5)
+
+ except Exception as e:
+
+ logger.warning('"{0}:{1}" IMAP4_SSL failed, trying IMAP4.'.format(self.strLogin, self.strFolder))
+
+ self.oImap = imaplib.IMAP4(self.strHost, self.nPort, debug=int(self.bDebug)*5)
+
+ if 'STARTTLS' in self.oImap.capabilities:
+ self.oImap.starttls()
+
+ try:
+ self.oImap.login(self.strLogin, self.strPasswd)
+
+ except Exception as e:
+
+ logger.error('"{0}:{1}" login failed.'.format(self.strLogin, self.strFolder))
+ raise
+
+ strFolderUTF7 = bytes(self.strFolder, 'utf-7').replace(b'+', b'&').replace(b' &', b'- &')
+
+ if b' ' in strFolderUTF7:
+ strFolderUTF7 = b'"' + strFolderUTF7 + b'"'
+
+ if self.oImap.select(mailbox=strFolderUTF7)[0] != 'OK':
+
+ raise Exception('Mailbox "{0}:{1}" does not exist.'.format(self.strLogin, self.strFolder))
+
+ else:
+
+ logger.info('"{0}:{1}" is now connected.'.format(self.strLogin, self.strFolder))
+ self.fnIdle(self, False)
+ self.oIdler = Idler(self, self.fnIdle, logger)
+ self.oIdler.start()
+
+ def isOpen(self):
+
+ return checkNetwork() and self.oImap and self.oImap.state != imaplib.LOGOUT and not self.oImap.Terminate
+
+class Message(object):
+
+ def __init__(self, oConnection, strUId, title, message_id, timestamp, strSender, thread_id=''):
+
+ self.oConnection = oConnection
+ self.strUId = strUId
+ self.title = title
+ self.message_id = message_id
+ self.timestamp = timestamp
+ self.thread_id = thread_id
+ self.strSender = strSender
+
+class AyatanaWebmail(object):
+
+ def __init__(self, bDebug):
+
+ self.bDebug = bDebug
+ self.dlgSettings = None
+ self.nLastMailTimestamp = 0
+ self.first_run = True
+ self.lstConnections = []
+ self.lstUnreadMessages = []
+ self.bDrawAttention = False
+ self.bIdlerRunning = False
+ self.bNoNetwork = True
+ self.oMessagingMenu = MessagingMenu(self.onMenuItemClicked, self.openDialog, self.updateMessageAges, self.fnCheckNetwork)
+
+ self.initKeyring()
+ self.initConfig()
+ DBusGMainLoop(set_as_default=True)
+ SessionBus(self.openDialog, self.clear, lambda: bool(g_lstAccounts), openURLOrCommand)
+ oSystemBus = dbus.SystemBus()
+ oSystemBus.add_signal_receiver(self.onPrepareForSleep, 'PrepareForSleep', 'org.freedesktop.login1.Manager', 'org.freedesktop.login1')
+ Notify.init('Ayatana Webmail')
+ GLib.set_application_name('Ayatana Webmail')
+
+ if not self.bIdlerRunning:
+
+ self.bIdlerRunning = True
+
+ for oConnection in self.lstConnections:
+ oConnection.bConnecting = True
+
+ GLib.timeout_add_seconds(5, self.connect, self.lstConnections)
+
+ try:
+ GLib.MainLoop().run()
+ except KeyboardInterrupt:
+ self.close(0)
+
+ def onPrepareForSleep(self, bGoing):
+
+ if not bGoing:
+
+ logger.info('The System has resumed from sleep, reconnecting accounts.')
+
+ for oConnection in self.lstConnections:
+
+ oConnection.bConnecting = True
+ oConnection.close()
+
+ GLib.timeout_add_seconds(5, self.connect, self.lstConnections)
+
+ def fnCheckNetwork(self):
+
+ if not checkNetwork():
+
+ logger.info('No network connection, checking in 1 minute.')
+ self.bNoNetwork = True
+ self.bIdlerRunning = False
+
+ elif self.bNoNetwork:
+
+ self.bNoNetwork = False
+
+ if not self.bIdlerRunning:
+
+ self.bIdlerRunning = True
+
+ for oConnection in self.lstConnections:
+ oConnection.bConnecting = True
+
+ GLib.timeout_add_seconds(5, self.connect, self.lstConnections)
+
+ return True
+
+ def clear(self):
+
+ # WARNING: loadDataFromDicts also calls this!
+ if g_lstAccounts:
+
+ for oMessage in self.lstUnreadMessages:
+
+ #self.markMessageAsRead(message)
+ GLib.idle_add(self.oMessagingMenu.remove, oMessage.message_id)
+ time.sleep(0.01)
+
+ self.setLauncherCount(0)
+
+ def closeConnections(self):
+
+ for oConnection in self.lstConnections:
+ oConnection.close()
+
+ self.lstConnections = []
+ self.bIdlerRunning = False
+
+ def close(self, nCode):
+
+ self.oMessagingMenu.close()
+ self.closeConnections()
+ print()
+ sys.exit(nCode)
+
+ def onMenuItemClicked(self, strId):
+
+ for message in self.lstUnreadMessages:
+
+ if message.message_id == strId:
+
+ if self.nMessageAction == MESSAGEACTION['MARK']:
+
+ self.markMessageAsRead(message)
+
+ elif self.nMessageAction == MESSAGEACTION['ASK']:
+
+ dlg = DialogActions(message.strSender, message.title)
+ nResponse = dlg.run()
+ dlg.destroy()
+
+ if nResponse == 100:
+
+ try:
+
+ if any(s in message.oConnection.strHost for s in ['gmail', 'google']):
+
+ message.oConnection.oImap.uid('STORE', message.strUId, '+X-GM-LABELS', '\\Trash')
+
+ else:
+
+ message.oConnection.oImap.uid('STORE', message.strUId, '+FLAGS', '\\Deleted')
+ message.oConnection.oImap.expunge()
+
+ except (imaplib.IMAP4.error, socketerror) as oError:
+
+ logger.error(str(oError))
+
+ elif nResponse == 200:
+
+ self.markMessageAsRead(message)
+
+ elif nResponse == 300:
+
+ openURLOrCommand(message.oConnection.strInbox.replace('$MSG_THREAD', message.thread_id).replace('$MSG_UID', message.strUId.decode('utf-8')))
+
+ else:
+
+ self.bDrawAttention = not message.timestamp < self.nLastMailTimestamp
+ self.appendToIndicator(message)
+ self.bDrawAttention = False
+ return False
+
+ else:
+
+ openURLOrCommand(message.oConnection.strInbox.replace('$MSG_THREAD', message.thread_id).replace('$MSG_UID', message.strUId.decode('utf-8')))
+
+ # True removes the message from Appindicator3
+ return True
+
+ def markMessageAsRead(self, message):
+
+ # Mark entire conversation
+ lstIndexes = [message.strUId]
+
+ if message.thread_id and self.bMergeConversation:
+
+ lstSearch = []
+
+ try:
+
+ lstSearch = message.oConnection.oImap.uid('SEARCH', None, '(X-GM-THRID ' + str(int(message.thread_id, 16)) + ')')
+
+ except imaplib.IMAP4.error as oError:
+
+ logger.error(str(oError))
+ return
+
+ if lstSearch[1][0] is not None:
+ lstIndexes = [m for m in lstSearch[1][0].split()]
+
+ for strIndex in lstIndexes:
+
+ try:
+
+ message.oConnection.oImap.uid('STORE', strIndex, '+FLAGS', '\\Seen')
+
+ except (imaplib.IMAP4.error, socketerror) as e:
+
+ logger.error(str(e))
+
+ def initConfig(self):
+
+ self.nMaxCount = g_oSettings.get_int('max-item-count')
+ self.bEnableNotifications = g_oSettings.get_boolean('enable-notifications')
+ self.bPlaySound = g_oSettings.get_boolean('enable-sound')
+ self.bHideCount = g_oSettings.get_boolean('hide-messages-count')
+ self.strCommand = g_oSettings.get_string('exec-on-receive')
+ self.custom_sound = g_oSettings.get_string('custom-sound')
+ self.bMergeConversation = g_oSettings.get_boolean('merge-messages')
+ self.nMessageAction = g_oSettings.get_enum('message-action')
+
+ def initKeyring(self):
+
+ bus = secretstorage.dbus_init()
+
+ try:
+
+ self.collection = secretstorage.get_default_collection(bus)
+ self.collection.is_locked()
+
+ except secretstorage.SecretStorageException as e:
+
+ logger.critical(str(e))
+ self.close(1)
+
+ if self.collection.is_locked():
+ self.collection.unlock()
+
+ if self.collection.is_locked():
+
+ logger.critical('Failed to unlock the collection, exiting.')
+ self.close(1)
+
+ self.mail_keys = list(self.collection.search_items({'application': 'ayatana-webmail'}))
+
+ if not self.mail_keys:
+ self.openDialog()
+
+ if not g_lstAccounts:
+
+ for key in sorted(self.mail_keys, key=lambda item: item.item_path):
+
+ dctAttributes = key.get_attributes()
+ strHost = dctAttributes['server']
+ nPort = int(dctAttributes['port'])
+ strLogin = dctAttributes['username']
+ strPasswd = key.get_secret().decode('utf-8')
+ strFolders = dctAttributes['folders']
+ strHome = g_oSettings.get_string('home')
+ strCompose = g_oSettings.get_string('compose')
+ strInbox = g_oSettings.get_string('inbox')
+ strSent = g_oSettings.get_string('sent')
+ strInboxAppend = ''
+
+ try:
+
+ strHome = dctAttributes['home']
+ strCompose = dctAttributes['compose']
+ strInbox = dctAttributes['inbox']
+ strSent = dctAttributes['sent']
+
+ except KeyError:
+
+ pass
+
+ try:
+
+ strInboxAppend = dctAttributes['InboxAppend']
+
+ except KeyError:
+
+ if strInbox == g_dctDefaultURLs['Inbox']:
+ strInboxAppend = '/$MSG_THREAD'
+
+ pass
+
+ g_lstAccounts.append({'Host': strHost, 'Port': nPort, 'Login': strLogin, 'Passwd': strPasswd, 'Folders': strFolders, 'Home': strHome, 'Compose': strCompose, 'Inbox': strInbox, 'Sent': strSent, 'InboxAppend': strInboxAppend})
+
+ for strFolder in strFolders.split('\t'):
+ self.lstConnections.append(Connection(self.bDebug, strHost, nPort, strLogin, strPasswd, strFolder, self.onIdle, strInbox + strInboxAppend))
+
+ def createKeyringItem(self, ind, update=False):
+
+ attrs = {'application': 'ayatana-webmail', 'service': 'imap', 'server': g_lstAccounts[ind]['Host'], 'port': str(g_lstAccounts[ind]['Port']), 'username': g_lstAccounts[ind]['Login'], 'folders': g_lstAccounts[ind]['Folders'], 'home': g_lstAccounts[ind]['Home'], 'compose': g_lstAccounts[ind]['Compose'], 'inbox': g_lstAccounts[ind]['Inbox'], 'sent': g_lstAccounts[ind]['Sent'], 'InboxAppend': g_lstAccounts[ind]['InboxAppend']}
+ label = 'ayatana-webmail: ' + g_lstAccounts[ind]['Login'] + ' at ' + g_lstAccounts[ind]['Host']
+
+ if update:
+
+ self.mail_keys[ind].set_attributes(attrs)
+ self.mail_keys[ind].set_secret(g_lstAccounts[ind]['Passwd'])
+ self.mail_keys[ind].set_label(label)
+
+ else:
+
+ self.collection.unlock()
+ self.collection.create_item(label, attrs, g_lstAccounts[ind]['Passwd'], True)
+
+ def openDialog(self):
+
+ if not self.dlgSettings:
+
+ self.dlgSettings = PreferencesDialog()
+ self.dlgSettings.connect('response', self.onDialogResponse)
+
+ if self.mail_keys:
+ self.dlgSettings.setAccounts(g_lstAccounts)
+
+ self.dlgSettings.run()
+ self.dlgSettings.destroy()
+ self.dlgSettings = None
+
+ def onDialogResponse(self, dlg, response):
+
+ global g_lstAccounts
+
+ if response == Gtk.ResponseType.APPLY:
+
+ dlg.updateAccounts()
+ dlg.saveAllSettings()
+
+ g_lstAccounts = dlg.lstDicts[:]
+
+ self.loadDataFromDicts()
+
+ for index in range(len(g_lstAccounts), len(self.mail_keys)):
+
+ # Remove old keys
+ self.mail_keys[index].delete()
+
+ for index in range(len(g_lstAccounts)):
+
+ # Create new keys or update existing
+ self.createKeyringItem(index, update=(index < len(self.mail_keys)))
+
+ self.mail_keys = list(self.collection.search_items({'application': 'ayatana-webmail'}))
+
+ if self.mail_keys and g_lstAccounts and all(self.lstConnections) and not self.bIdlerRunning:
+
+ self.bIdlerRunning = True
+
+ for oConnection in self.lstConnections:
+ oConnection.bConnecting = True
+
+ GLib.timeout_add_seconds(5, self.connect, self.lstConnections)
+
+ if response in [Gtk.ResponseType.APPLY, Gtk.ResponseType.CANCEL]:
+ dlg.destroy()
+
+ def loadDataFromDicts(self):
+
+ self.closeConnections()
+ self.initConfig()
+ self.clear()
+ self.lstUnreadMessages = []
+ self.nLastMailTimestamp = 0
+ self.first_run = True
+
+ for dct in g_lstAccounts:
+
+ strFolders = 'INBOX'
+
+ try:
+ strFolders = dct['Folders']
+ except KeyError:
+ pass
+
+ nPort = 993
+
+ try:
+ nPort = int(dct['Port'])
+ except ValueError:
+ pass
+
+ for strFolder in strFolders.split('\t'):
+ self.lstConnections.append(Connection(self.bDebug, dct['Host'], nPort, dct['Login'], dct['Passwd'], strFolder, self.onIdle, dct['Inbox'] + dct['InboxAppend']))
+
+ def appendToIndicator(self, message):
+
+ if self.oMessagingMenu.hasSource(message.message_id):
+ return
+
+ title = message.title
+
+ if len(title) > 50:
+ title = title[:50] + '...'
+
+ if len(g_lstAccounts) > 1:
+ title = '↪ ' + message.oConnection.strLogin + '\n' + title
+
+ GLib.idle_add(self.oMessagingMenu.append, message.message_id, title, message.timestamp, self.bDrawAttention)
+ time.sleep(0.01)
+
+ def onIdle(self, oConnection, bAborted):
+
+ if bAborted or not oConnection.isOpen():
+
+ if not oConnection.bConnecting:
+
+ oConnection.bConnecting = True
+ GLib.timeout_add_seconds(1, oConnection.close)
+ logger.info('"{0}:{1}" will try to reconnect in 1 minute.'.format(oConnection.strLogin, oConnection.strFolder))
+ GLib.timeout_add_seconds(60, self.connect, [oConnection])
+
+ return
+
+ lstMessages = []
+ lstNewMessages = []
+ lstUnread = []
+
+ search = oConnection.oImap.uid('SEARCH', '(UNSEEN)')
+
+ if search[1][0] is not None:
+ lstMessages = search[1][0].split()
+
+ for m in lstMessages[-self.nMaxCount:]:
+
+ typ = None
+ msg_data = None
+ thread_id = ''
+ msg = None
+
+ try:
+
+ typ, msg_data = oConnection.oImap.uid('FETCH', m, '(X-GM-THRID BODY.PEEK[HEADER.FIELDS (DATE SUBJECT FROM MESSAGE-ID)])')
+
+ for lstField in msg_data:
+
+ if 'THRID' in str(lstField):
+
+ thread_id = '%x' % int(m_reThrid.search(lstField[0]).group(1))
+ break
+
+ except imaplib.IMAP4.error:
+
+ typ, msg_data = oConnection.oImap.uid('FETCH', m, '(BODY.PEEK[HEADER.FIELDS (DATE SUBJECT FROM MESSAGE-ID)])')
+
+ for response_part in msg_data:
+
+ if isinstance(response_part, tuple):
+ msg = email.message_from_bytes(response_part[1])
+
+ if msg is None:
+ continue
+
+ message_id = msg['Message-Id']
+
+ if not isinstance(message_id, str):
+ message_id = oConnection.strHost + ':' + oConnection.strLogin + ':' + oConnection.strFolder + ':' + str(m.decode())
+
+ bMessageExists = False
+
+ for cMessage in self.lstUnreadMessages:
+
+ if cMessage.message_id == message_id:
+
+ bMessageExists = True
+ break
+
+ if not bMessageExists:
+
+ sender = getHeaderWrapper(msg, 'From', True)
+ subj = getHeaderWrapper(msg, 'Subject', True)
+ date = getHeaderWrapper(msg, 'Date', False)
+
+ try:
+
+ tuple_time = email.utils.parsedate_tz(date)
+ timestamp = email.utils.mktime_tz(tuple_time)
+
+ if timestamp > time.time():
+
+ # Message time is larger than the current one
+ timestamp = time.time()
+
+ except TypeError:
+
+ # Failed to get time from message
+ timestamp = time.time()
+
+ # Number of seconds to number of microseconds
+ timestamp *= (10**6)
+
+ while subj.lower().startswith('re:'):
+ subj = subj[3:]
+
+ while subj.lower().startswith('fwd:'):
+ subj = subj[4:]
+
+ subj = subj.strip()
+
+ if sender.startswith('"'):
+
+ pos = sender[1:].find('"')
+
+ if pos >= 0:
+ sender = sender[1:pos+1]+sender[pos+2:]
+
+ ilabel = subj if subj else _('No subject')
+
+ # Display only last message in thread
+ bConversationInUnread = False
+ bConversationInNew = False
+
+ if thread_id and self.bMergeConversation:
+
+ for oMessage in self.lstUnreadMessages:
+
+ if oMessage.thread_id == thread_id:
+
+ oMessage.timestamp = max(timestamp, oMessage.timestamp)
+ bConversationInUnread = True
+ break
+
+ if not bConversationInUnread:
+
+ for oMessage in lstNewMessages:
+
+ if oMessage.thread_id == thread_id:
+
+ oMessage.timestamp = max(timestamp, oMessage.timestamp)
+ bConversationInNew = True
+ break
+
+ if not bConversationInUnread and not bConversationInNew:
+
+ message = Message(oConnection, m, ilabel, message_id, timestamp, sender, thread_id)
+ lstNewMessages.append(message)
+
+ if timestamp > self.nLastMailTimestamp:
+
+ if self.bEnableNotifications:
+
+ if not bConversationInNew:
+
+ oConnection.lstNotificationQueue.append([sender, subj, oConnection, thread_id])
+
+ else:
+
+ for lstNotification in oConnection.lstNotificationQueue:
+
+ if lstNotification[3] == thread_id:
+
+ lstNotification[0] = sender
+ break
+
+ self.nLastMailTimestamp = timestamp
+ self.bDrawAttention = True
+
+ if self.strCommand and not self.first_run:
+
+ try:
+
+ subprocess.call((self.strCommand, sender, ilabel))
+
+ except OSError as e:
+
+ # File doesn't exist or is not executable
+ logger.warning('Cannot execute command: {0}'.format(str(e)))
+
+ else:
+
+ lstUnread.append(message_id)
+
+ self.updateIndicator(lstNewMessages, [oMessage for oMessage in self.lstUnreadMessages if oMessage.oConnection == oConnection and oMessage.message_id not in lstUnread], oConnection)
+
+ def updateIndicator(self, lstNewMessages, lstRemovedMessages, oConnection):
+
+ for oMessage in [oMessage for oMessage in self.lstUnreadMessages if oMessage.oConnection == oConnection]:
+
+ # Removed outside the app
+ if oMessage in lstRemovedMessages:
+
+ GLib.idle_add(self.oMessagingMenu.remove, oMessage.message_id)
+ time.sleep(0.01)
+
+ # Cleared
+ if not self.oMessagingMenu.hasSource(oMessage.message_id) and oMessage not in lstNewMessages:
+
+ self.markMessageAsRead(oMessage)
+ self.lstUnreadMessages.remove(oMessage)
+
+ self.lstUnreadMessages = sorted(self.lstUnreadMessages + lstNewMessages, key=lambda m: m.timestamp)[-self.nMaxCount:]
+
+ #logger.debug('Unread: {0}, New: {1}, Removed: {2}'.format(len(self.lstUnreadMessages), len(lstNewMessages), len(lstRemovedMessages)))
+
+ if lstNewMessages:
+
+ for cMessage in lstNewMessages:
+ self.appendToIndicator(cMessage)
+
+ try:
+
+ if self.first_run and oConnection != self.lstConnections[-1]:
+
+ pass
+
+ elif self.first_run and oConnection == self.lstConnections[-1]:
+
+ self.showNotifications()
+ self.first_run = False
+
+ elif lstNewMessages:
+
+ self.showNotifications()
+
+ except GLib.GError as e:
+
+ logger.warning(str(e))
+
+ self.setLauncherCount(len(self.lstUnreadMessages))
+
+ if not self.first_run:
+ self.bDrawAttention = False
+
+ def updateMessageAges(self):
+
+ for oMessage in self.lstUnreadMessages:
+
+ GLib.idle_add(self.oMessagingMenu.update, oMessage.message_id, oMessage.timestamp)
+ time.sleep(0.01)
+
+ return True
+
+ def connect(self, lstConnections):
+
+ logger.info('Checking network...')
+
+ if not checkNetwork():
+ return False
+
+ logger.info('Network connection active, connecting...')
+
+ for oConnection in lstConnections:
+
+ oConnection.close()
+
+ try:
+
+ oConnection.connect()
+ oConnection.bConnecting = False
+
+ except KeyboardInterrupt:
+
+ self.close(0)
+
+ except Exception as oException:
+
+ logger.error('"{0}:{1}" could not connect: {2}'.format(oConnection.strLogin, oConnection.strFolder, str(oException)))
+
+ oNotification = Notify.Notification.new(_('Connection error'), '', APPNAME)
+ oNotification.set_property('body', _('Unable to connect to account "{accountName}", the application will now exit.').format(accountName=oConnection.strLogin) + '\n\n' + _('You can run "{command}" to delete all your login settings.').format(command='ayatana-webmail-reset'))
+ oNotification.set_hint('desktop-entry', GLib.Variant.new_string(APPNAME))
+ oNotification.set_timeout(Notify.EXPIRES_NEVER)
+ oNotification.show()
+ self.close(1)
+
+ return False
+
+ def setLauncherCount(self, nCount):
+
+ GLib.idle_add(self.oMessagingMenu.setCount, nCount, any([oImap for oImap in self.lstConnections]))
+ time.sleep(0.01)
+
+ def showNotifications(self):
+
+ lstNotificationsQueue = []
+
+ for oConnection in self.lstConnections:
+
+ if oConnection:
+
+ lstNotificationsQueue += oConnection.lstNotificationQueue
+ oConnection.lstNotificationQueue = []
+
+ number_of_mails = len(lstNotificationsQueue)
+ basemessage = g_oTranslation.ngettext('You have %d unread mail', 'You have %d unread mails', number_of_mails)
+ basemessage = basemessage.replace('%d', '{0}')
+
+ if number_of_mails and self.bPlaySound:
+
+ try:
+
+ if self.custom_sound:
+ subprocess.call(('canberra-gtk-play', '-f', self.custom_sound))
+ else:
+ subprocess.call(('canberra-gtk-play', '-i', 'message-new-email'))
+
+ except OSError as e:
+
+ logger.warning(str(e))
+
+ if number_of_mails > 1:
+
+ senders = set(getSenderName(lstNotification[0]) for lstNotification in lstNotificationsQueue)
+ unknown_sender = ('' in senders)
+
+ if unknown_sender:
+ senders.remove('')
+
+ ts = tuple(senders)
+
+ if len(ts) > 2 or (len(ts) == 2 and unknown_sender):
+ message = fixFormat(_('from %(t0)s, %(t1)s and others')).format(t0=ts[0], t1=ts[1])
+ elif len(ts) == 2 and not unknown_sender:
+ message = fixFormat(_('from %(t0)s and %(t1)s')).format(t0=ts[0], t1=ts[1])
+ elif len(ts) == 1 and not unknown_sender:
+ message = _('from %s').replace('%s', '{0}').format(getSenderName(ts[0]))
+ else:
+ message = None
+
+ oNotification = Notify.Notification.new(basemessage.format(number_of_mails), message, APPNAME)
+ oNotification.set_hint('desktop-entry', GLib.Variant.new_string(APPNAME))
+ oNotification.show()
+
+ elif number_of_mails:
+
+ lstNotification = lstNotificationsQueue[0]
+
+ if lstNotification[0]:
+ message = _('New mail from %s').replace('%s', '{0}').format(getSenderName(lstNotification[0]))
+ else:
+ message = basemessage.format(1)
+
+ oNotification = Notify.Notification.new(message, lstNotification[1], APPNAME)
+ oNotification.set_hint('desktop-entry', GLib.Variant.new_string(APPNAME))
+ oNotification.show()
diff --git a/ayatanawebmail/common.py b/ayatanawebmail/common.py
new file mode 100755
index 0000000..95d3797
--- /dev/null
+++ b/ayatanawebmail/common.py
@@ -0,0 +1,112 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Ayatana Webmail, message actions dialog
+# Authors: Robert Tari <robert@tari.in>
+# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html
+
+import gettext
+import os
+import psutil
+import subprocess
+import webbrowser
+from gi.repository import Gio
+from ayatanawebmail.appdata import APPEXECUTABLE, APPNAME
+from ayatanawebmail.accounts import DialogAccounts
+
+try:
+ g_oTranslation = gettext.translation(APPNAME)
+except IOError:
+ g_oTranslation = gettext.NullTranslations()
+
+g_oTranslation.install()
+
+g_dctDefaultURLs = {'Home': 'https://mail.google.com/mail/', 'Compose': 'https://mail.google.com/mail/#compose', 'Inbox': 'https://mail.google.com/mail/#inbox', 'Sent': 'https://mail.google.com/mail/#sent'}
+g_oSettings = Gio.Settings.new('org.ayatana.webmail')
+g_lstAccounts = []
+
+def getDataPath(strPath):
+
+ try:
+
+ strExecPath = os.path.split(APPEXECUTABLE)[0]
+ strDataPath = os.getcwd().replace(strExecPath, '')
+ strRelativePath = os.path.join(strDataPath, strPath.lstrip('/'))
+
+ if os.path.exists(strRelativePath):
+ return strRelativePath
+
+ except:
+
+ pass
+
+ return strPath
+
+def isRunning():
+
+ nCount = 0
+
+ for oProc in psutil.process_iter():
+
+ strName = oProc.name
+
+ if not isinstance(strName, str):
+
+ strName = oProc.name()
+
+ if strName == 'python3' or strName == 'python':
+
+ lstCmdline = oProc.cmdline
+
+ if not isinstance(lstCmdline, list):
+ lstCmdline = oProc.cmdline()
+
+ for strCmd in lstCmdline:
+
+ if strCmd.endswith('ayatana-webmail'):
+ nCount += 1
+
+ elif strName.endswith('ayatana-webmail'):
+
+ nCount += 1
+
+ return nCount
+
+def resolveURL(strURL):
+
+ if strURL.startswith('Exec:'):
+ subprocess.Popen(strURL[5:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
+ elif strURL.startswith('http'):
+ webbrowser.open_new_tab(strURL)
+
+def openURLOrCommand(strURL):
+
+ if strURL in g_dctDefaultURLs:
+
+ strURL0 = g_lstAccounts[0][strURL]
+
+ if len(g_lstAccounts) > 1:
+
+ for dctAccount in g_lstAccounts[1:]:
+
+ if dctAccount[strURL] != strURL0:
+
+ oDialogAccounts = DialogAccounts(strURL, getDataPath, g_lstAccounts)
+ oDialogAccounts.run()
+ strURL = oDialogAccounts.strURL
+ oDialogAccounts.destroy()
+
+ if strURL:
+ resolveURL(strURL)
+
+ return
+
+ resolveURL(strURL0)
+
+ elif strURL.startswith('Exec:') or strURL.startswith('http'):
+
+ resolveURL(strURL)
+
+ else:
+
+ print('Unknown URL name!')
+ print('Possible URL names: "Home", "Compose", "Inbox", "Sent", "Exec:...", "http..."')
diff --git a/ayatanawebmail/dialog.py b/ayatanawebmail/dialog.py
new file mode 100755
index 0000000..453592a
--- /dev/null
+++ b/ayatanawebmail/dialog.py
@@ -0,0 +1,583 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Ayatana Webmail, the Preferences Dialog
+# Authors: Dmitry Shachnev <mitya57@gmail.com>
+# Robert Tari <robert@tari.in>
+# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html
+
+import ayatanawebmail.imaplib2 as imaplib
+import os.path
+from socket import error as socketerror
+from gi.repository import Gtk, GdkPixbuf, Gdk
+from ayatanawebmail.common import g_oSettings, getDataPath, g_dctDefaultURLs
+from ayatanawebmail.appdata import APPVERSION, APPURL, APPDESCRIPTION, APPAUTHOR, APPYEAR, APPTITLE
+import webbrowser
+
+MESSAGEACTION = {'OPEN': 1, 'MARK': 2, 'ASK': 3}
+
+def utf7dec(lstInput):
+
+ if not isinstance(lstInput, bytes):
+
+ return lstInput
+
+ lstResult = []
+ lstBytes = bytearray()
+
+ for nChar in lstInput:
+
+ if nChar == b'&'[0] and not lstBytes:
+
+ lstBytes.append(nChar)
+
+ elif nChar == b'-'[0] and lstBytes:
+
+ if len(lstBytes) == 1:
+ lstResult.append('&')
+ else:
+ lstResult.append((b'+' + lstBytes[1:].replace(b',', b'/') + b'-').decode('utf-7'))
+
+ lstBytes = bytearray()
+
+ elif lstBytes:
+
+ lstBytes.append(nChar)
+
+ else:
+
+ lstResult.append(chr(nChar))
+
+ if lstBytes:
+ lstResult.append((b'+' + lstBytes[1:].replace(b',', b'/') + b'-').decode('utf-7'))
+
+ return ''.join(lstResult)
+
+class ComboEntry(Gtk.ButtonBox):
+
+ def __init__(self, strId, **kwargs):
+
+ Gtk.ButtonBox.__init__(self, orientation=Gtk.Orientation.HORIZONTAL, layout_style=Gtk.ButtonBoxStyle.EXPAND, **kwargs)
+
+ self.oComboBoxText = Gtk.ComboBoxText()
+ self.oComboBoxText.append('HTTP:', _('Web page'))
+ self.oComboBoxText.append('Exec:', _('Command'))
+ self.oEntry = Gtk.Entry()
+ self.oEntry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, 'gtk-revert-to-saved-ltr')
+ self.oEntry.connect('icon-press', self.onReset)
+ self.oComboBoxText.set_active_id('HTTP:')
+ self.pack_start(self.oComboBoxText, False, False, 0)
+ self.pack_start(self.oEntry, True, True, 0)
+ self.set_homogeneous(False)
+ self.strId = strId
+
+ def onReset(self, oWidget, nPosition, oEvent):
+
+ self.setText(g_dctDefaultURLs[self.strId]);
+
+ def setText(self, strText):
+
+ self.oEntry.set_text(strText[5:] if strText.startswith('Exec:') else strText)
+ self.oComboBoxText.set_active_id('Exec:' if strText.startswith('Exec:') else 'HTTP:')
+
+ def getText(self):
+
+ return ('Exec:' if self.oComboBoxText.get_active_id() == 'Exec:' else '') + self.oEntry.get_text()
+
+class EntryReset(Gtk.Entry):
+
+ def __init__(self, oComboEntry, **kwargs):
+
+ Gtk.Entry.__init__(self, **kwargs)
+
+ self.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, 'gtk-revert-to-saved-ltr')
+ self.connect('icon-press', self.onReset)
+ self.oComboEntry = oComboEntry
+ self.set_tooltip_text(_('Append an additional string - you can use the $MSG_THREAD and $MSG_UID placeholders.'))
+
+ def onReset(self, oWidget, nPosition, oEvent):
+
+ strText = ''
+
+ if self.oComboEntry.oComboBoxText.get_active_id() == 'HTTP:' and self.oComboEntry.getText() == g_dctDefaultURLs['Inbox']:
+ strText = '/$MSG_THREAD'
+
+ self.set_text(strText);
+
+class FileChooserButtonEx(Gtk.ButtonBox):
+
+ def __init__(self, strFilename, **kwargs):
+
+ Gtk.ButtonBox.__init__(self, orientation=Gtk.Orientation.HORIZONTAL, layout_style=Gtk.ButtonBoxStyle.EXPAND, **kwargs)
+
+ oButtonClear = Gtk.Button.new_from_icon_name('gtk-clear', Gtk.IconSize.BUTTON)
+ oButtonClear.connect('clicked', self.onClear)
+ oButtonOpen = Gtk.Button()
+ oButtonOpen.connect('clicked', self.onOpen)
+ self.oLabel = Gtk.Label(os.path.basename(strFilename) or _('(None)'), xalign=0, margin_left=5)
+ oImage = Gtk.Image.new_from_icon_name('gtk-open', Gtk.IconSize.BUTTON)
+ oBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
+ oBox.pack_start(oImage, False, False, 0)
+ oBox.pack_start(self.oLabel, True, True, 0)
+ oButtonOpen.add(oBox)
+ self.pack_start(oButtonOpen, True, True, 0)
+ self.pack_start(oButtonClear, False, False, 0)
+ self.set_homogeneous(False)
+ self.strFilename = strFilename
+
+ def onClear(self, oWidget):
+
+ self.strFilename = ''
+ self.oLabel.set_text(_('(None)'))
+
+ def onOpen(self, oWidget):
+
+ oDlg = Gtk.FileChooserDialog(None, oWidget.get_toplevel(), 0, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.APPLY))
+
+ if self.strFilename:
+ oDlg.set_filename(self.strFilename)
+
+ nResponse = oDlg.run()
+
+ if nResponse == Gtk.ResponseType.APPLY:
+
+ self.strFilename = oDlg.get_filename()
+ self.oLabel.set_text(os.path.basename(self.strFilename))
+
+ oDlg.destroy()
+
+ def getFilename(self):
+
+ return self.strFilename
+
+class PreferencesDialog(Gtk.Dialog):
+
+ def __init__(self):
+
+ self.bInit = False
+ self.initConfig()
+ Gtk.Dialog.__init__(self, _('Ayatana Webmail Preferences'), None, 0, (Gtk.STOCK_CONNECT, 100, Gtk.STOCK_APPLY, Gtk.ResponseType.APPLY, Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
+ self.set_icon_name('ayatana-webmail')
+ self.connect('destroy', lambda w: Gtk.main_quit())
+ self.connect('response', self.onResponse)
+ self.set_position(Gtk.WindowPosition.CENTER)
+ self.set_property('width-request', 640)
+ self.set_property('height-request', 480)
+ self.oNotebook = Gtk.Notebook(vexpand=True, margin_left=5, margin_top=5, margin_right=5)
+ self.oNotebook.append_page(self.pageAccounts(), Gtk.Label(_('Accounts')))
+ self.oNotebook.append_page(self.pageOptions(), Gtk.Label(_('Options')))
+ self.oNotebook.append_page(self.pageSupport(), Gtk.Label(_('Support')))
+ self.oNotebook.append_page(self.pageAbout(), Gtk.Label(_('About')))
+ oContentArea = self.get_content_area()
+ oContentArea.set_property('vexpand', True)
+ oContentArea.add(self.oNotebook)
+ self.oButtonConnect = self.get_widget_for_response(100)
+ self.oButtonApply = self.get_widget_for_response(Gtk.ResponseType.APPLY)
+ self.lstDicts = [{'Host': 'imap.gmail.com', 'Port': '993', 'Login': '', 'Passwd': '', 'Folders': 'INBOX', 'InboxAppend': '/$MSG_THREAD'}]
+ self.lstDicts[0].update(g_dctDefaultURLs)
+ self.set_keep_above(True)
+ self.show_all()
+ self.bInit = True
+ self.nIndex = 0
+
+ def onResponse(self, oWidget, nResponse):
+
+ if nResponse == 100:
+
+ self.oNotebook.set_current_page(0)
+ self.oListStore.clear()
+ self.getFolderList(True)
+ self.updateUI()
+
+ def getFolderList(self, bAutoselect):
+
+ try:
+
+ oImap = None
+
+ try:
+
+ oImap = imaplib.IMAP4_SSL(self.EntryHost.get_text(), int(self.EntryPort.get_text()))
+
+ except Exception:
+
+ oImap = imaplib.IMAP4(self.EntryHost.get_text(), int(self.EntryPort.get_text()))
+ oImap.starttls()
+
+ oImap.login(self.EntryLogin.get_text(), self.EntryPassword.get_text())
+
+ for f in oImap.list()[1]:
+
+ flags, b, c = utf7dec(f).partition(' ')
+ separator, b, strName = c.partition(' ')
+ strName = strName.replace('"', '').replace('/ ', '')
+
+ if strName != '[Gmail]' and 'All Mail' not in strName:
+ self.oListStore.append([strName, strName.replace('[Gmail]/', ''), strName.upper() == 'INBOX' if bAutoselect else False])
+
+ oImap.logout()
+
+ except (imaplib.IMAP4.error, socketerror) as oError:
+
+ oDlg = Gtk.MessageDialog(self, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, '')
+
+ strError = str(oError)
+
+ if strError.startswith("b'"):
+ strError = strError[1:]
+
+ if 'https://support.google.com/mail/accounts/answer/78754' in strError:
+
+ oDlg.set_markup( _('Please visit the following link and enable access for less secure apps:') + '\n\n<a href="https://www.google.com/settings/security/lesssecureapps">https://www.google.com/settings/security/lesssecureapps</a>')
+ oDlg.set_property('message_type', Gtk.MessageType.INFO)
+ oDlg.set_title(_('Access blocked by Google'))
+
+ else:
+
+ oDlg.set_property('text', _('Failed to connect to mail account. The returned error was:') + '\n\n' + strError)
+ oDlg.set_title(_('Connection failure'))
+
+ oDlg.run()
+ oDlg.destroy()
+
+ def initConfig(self):
+
+ self.nMaxCount = g_oSettings.get_int('max-item-count')
+ self.bEnableNotifications = g_oSettings.get_boolean('enable-notifications')
+ self.bPlaySound = g_oSettings.get_boolean('enable-sound')
+ self.bHideCount = g_oSettings.get_boolean('hide-messages-count')
+ self.strCommand = g_oSettings.get_string('exec-on-receive')
+ self.strCustomSound = g_oSettings.get_string('custom-sound')
+ self.bMergeConversation = g_oSettings.get_boolean('merge-messages')
+ self.nMessageAction = g_oSettings.get_enum('message-action')
+
+ def pageAccounts(self):
+
+ acclabel = Gtk.Label(xalign=0, hexpand=True)
+ acclabel.set_markup('<b>'+_('Choose an account')+'</b>')
+ self.sb = Gtk.SpinButton.new_with_range(1, 1, 1)
+ self.sb.set_numeric(True)
+ self.sb.set_update_policy(Gtk.SpinButtonUpdatePolicy.IF_VALID)
+ self.sb.connect('value-changed', self.onAccountChanged)
+ self.addbtn = Gtk.Button.new_with_label(_('Add'))
+ self.addbtn.connect('clicked', self.onAddAccount)
+ self.rmbtn = Gtk.Button.new_with_label(_('Remove'))
+ self.rmbtn.connect('clicked', self.onRemoveAccount)
+ accbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5, hexpand=True)
+ accbox.pack_start(self.sb, True, True, 0)
+ accbox.pack_end(self.rmbtn, False, False, 0)
+ accbox.pack_end(self.addbtn, False, False, 0)
+ self.EntryHost = Gtk.Entry(hexpand=True)
+ self.EntryHost.connect('changed', lambda w: self.updateUI())
+ self.EntryPort = Gtk.Entry(hexpand=True)
+ self.EntryPort.connect('changed', lambda w: self.updateUI())
+ self.EntryLogin = Gtk.Entry(hexpand=True)
+ self.EntryLogin.connect('changed', lambda w: self.updateUI())
+ self.EntryPassword = Gtk.Entry(visibility=False, caps_lock_warning=True, hexpand=True)
+ self.EntryPassword.connect('changed', lambda w: self.updateUI())
+ srvlabel = Gtk.Label(xalign=0, margin_top=5, hexpand=True)
+ srvlabel.set_markup('<b>'+_('Server data')+'</b>')
+ infolabel = Gtk.Label(xalign=0, margin_top=5, hexpand=True)
+ infolabel.set_markup('<b>'+_('Account data')+'</b>')
+ self.oListStore = Gtk.ListStore(str, str, bool)
+ oTreeView = Gtk.TreeView(self.oListStore, headers_visible=False, activate_on_single_click=True, margin_left=5, margin_top=5, margin_right=5, margin_bottom=5)
+ oTreeView.connect('row-activated', self.onFolderActivated)
+ oTreeViewColumnBool = Gtk.TreeViewColumn('bool', Gtk.CellRendererToggle(), active=2)
+ oTreeViewColumnBool.get_cells()[0].set_property('xalign', 1.0)
+ oTreeView.append_column(Gtk.TreeViewColumn('folder', Gtk.CellRendererText(), text=1))
+ oTreeView.append_column(oTreeViewColumnBool)
+ oFrame = Gtk.ScrolledWindow(shadow_type=Gtk.ShadowType.IN, hexpand=True, vexpand=True)
+ oFrame.add(oTreeView)
+ oLabelLinks = Gtk.Label(xalign=0, margin_top=5, hexpand=True)
+ oLabelLinks.set_markup('<b>'+_('Links')+'</b>')
+ self.oEntryHome = ComboEntry('Home', hexpand=True)
+ self.oEntryCompose = ComboEntry('Compose', hexpand=True)
+ self.oEntryInbox = ComboEntry('Inbox', hexpand=True)
+ self.oEntrySent = ComboEntry('Sent', hexpand=True)
+ self.oEntryInboxAppend = EntryReset(self.oEntryInbox)
+ oGrid = Gtk.Grid(row_spacing=5, column_spacing=5, vexpand=True)
+ oGrid.attach(srvlabel, 0, 0, 3, 1)
+ oGrid.attach(Gtk.Label(_('Host:'), xalign=0, margin_right=5), 0, 1, 1, 1)
+ oGrid.attach(self.EntryHost, 1, 1, 2, 1)
+ oGrid.attach(Gtk.Label(_('Port:'), xalign=0, margin_right=5), 0, 2, 1, 1)
+ oGrid.attach(self.EntryPort, 1, 2, 2, 1)
+ oGrid.attach(infolabel, 0, 3, 3, 1)
+ oGrid.attach(Gtk.Label(_('Login:'), xalign=0, margin_right=5), 0, 4, 1, 1)
+ oGrid.attach(self.EntryLogin, 1, 4, 2, 1)
+ oGrid.attach(Gtk.Label(_('Password:'), xalign=0, margin_right=5), 0, 5, 1, 1)
+ oGrid.attach(self.EntryPassword, 1, 5, 2, 1)
+ oGrid.attach(Gtk.Label(_('Folders:'), xalign=0, margin_right=5), 0, 6, 1, 1)
+ oGrid.attach(oFrame, 1, 6, 2, 1)
+ oGrid.attach(oLabelLinks, 0, 7, 3, 1)
+ oGrid.attach(Gtk.Label(_('Home:'), xalign=0, margin_right=5), 0, 8, 1, 1)
+ oGrid.attach(self.oEntryHome, 1, 8, 2, 1)
+ oGrid.attach(Gtk.Label(_('Compose:'), xalign=0, margin_right=5), 0, 9, 1, 1)
+ oGrid.attach(self.oEntryCompose, 1, 9, 2, 1)
+ oGrid.attach(Gtk.Label(_('Inbox:'), xalign=0, margin_right=5), 0, 10, 1, 1)
+ oGrid.attach(self.oEntryInbox, 1, 10, 1, 1)
+ oGrid.attach(self.oEntryInboxAppend, 2, 10, 1, 1)
+ oGrid.attach(Gtk.Label(_('Sent:'), xalign=0, margin_right=5), 0, 11, 1, 1)
+ oGrid.attach(self.oEntrySent, 1, 11, 2, 1)
+ page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5, border_width=10, vexpand=True)
+ page.add(acclabel)
+ page.add(accbox)
+ page.add(oGrid)
+ oScrolledWindow = Gtk.ScrolledWindow()
+ oScrolledWindow.add(page)
+
+ nHeight = 721
+ oDisplay = Gdk.Display.get_default()
+
+ if oDisplay:
+
+ oMonitor = None
+
+ # get_primary_monitor is available in >= 3.22
+ try:
+ oMonitor = oDisplay.get_primary_monitor()
+ except Exception as oException:
+ pass
+
+ if oMonitor:
+ nHeight = oMonitor.get_workarea().height
+
+ if nHeight > 720:
+
+ # propagate_natural_height is available in >= 3.22
+ try:
+ oScrolledWindow.props.propagate_natural_height = True
+ except Exception as oException:
+ pass
+
+ return oScrolledWindow
+
+ def pageOptions(self):
+
+ self.oComboMessageAction = Gtk.ComboBoxText()
+ self.oComboMessageAction.append(str(MESSAGEACTION['MARK']), _('Mark message as read'))
+ self.oComboMessageAction.append(str(MESSAGEACTION['OPEN']), _('Open message in browser/Execute command'))
+ self.oComboMessageAction.append(str(MESSAGEACTION['ASK']), _('Ask me what to do'))
+ self.oComboMessageAction.set_active_id(str(self.nMessageAction))
+ self.oSwitchMerge = Gtk.Switch(active=self.bMergeConversation, halign=Gtk.Align.END)
+ self.notifyswitch = Gtk.Switch(active=self.bEnableNotifications, halign=Gtk.Align.END)
+ self.sndswitch = Gtk.Switch(active=self.bPlaySound, halign=Gtk.Align.END)
+ self.sndswitch.connect('notify::active', self.onSoundSwitchActivate)
+ self.hcswitch = Gtk.Switch(active=self.bHideCount, halign=Gtk.Align.END)
+ self.commandchooser = FileChooserButtonEx(self.strCommand)
+ self.sndchooser = FileChooserButtonEx(self.strCustomSound)
+ oGrid = Gtk.Grid(row_spacing=5, column_spacing=10)
+ oGrid.attach(Gtk.Label(_('Enable notifications:'), xalign=0), 0, 0, 1, 1)
+ oGrid.attach(self.notifyswitch, 1, 0, 1, 1)
+ oGrid.attach(Gtk.Label(_('Play sound when a message is received:'), xalign=0), 0, 1, 1, 1)
+ oGrid.attach(self.sndswitch, 1, 1, 1, 1)
+ oGrid.attach(Gtk.Label(_('Merge messages from the same conversation:'), xalign=0), 0, 2, 1, 1)
+ oGrid.attach(self.oSwitchMerge, 1, 2, 1, 1)
+ oGrid.attach(Gtk.Label(_('Hide count when zero:'), xalign=0), 0, 3, 1, 1)
+ oGrid.attach(self.hcswitch, 1, 3, 1, 1)
+ oGrid.attach(Gtk.Label(_('When a message is activated:'), xalign=0), 0, 4, 1, 1)
+ oGrid.attach(self.oComboMessageAction, 1, 4, 1, 1)
+ commandbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
+ commandbox.add(Gtk.Label(_('Execute this command when a message is received:'), xalign=0))
+ commandbox.pack_end(self.commandchooser, True, True, 0)
+
+ if self.commandchooser.get_allocated_width() < 180:
+ self.commandchooser.set_size_request(180, 0)
+
+ self.sndbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10, sensitive=self.bPlaySound)
+ self.sndbox.add(Gtk.Label(_('Custom sound to play:'), xalign=0))
+ self.sndbox.pack_end(self.sndchooser, True, True, 0)
+
+ if self.sndchooser.get_allocated_width() < 180:
+ self.sndchooser.set_size_request(180, 0)
+
+ page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5, border_width=10)
+ page.add(oGrid)
+ page.add(commandbox)
+ page.add(self.sndbox)
+
+ return page
+
+ def pageSupport(self):
+
+ oGrid = Gtk.Grid(border_width=10, row_spacing=2)
+ oGrid.attach(Gtk.Label(_('Report a bug'), xalign=0), 0, 0, 1, 1)
+ oGrid.attach(Gtk.Label('<a href="https://github.com/AyatanaIndicators/ayatana-webmail/issues">https://github.com/AyatanaIndicators/ayatana-webmail/issues</a>', xalign=0, use_markup=True, margin_bottom=10), 0, 1, 1, 1)
+ oGrid.attach(Gtk.Label(_('Request a feature'), xalign=0), 0, 2, 1, 1)
+ oGrid.attach(Gtk.Label('<a href="https://github.com/AyatanaIndicators/ayatana-webmail/issues">https://github.com/AyatanaIndicators/ayatana-webmail/issues</a>', xalign=0, use_markup=True), 0, 3, 1, 1)
+ oGrid.attach(Gtk.Label(_('It\'s a good idea to add the {labelname} label to your issue.').format(labelname='<b>enhancement</b>'), xalign=0, margin_bottom=10, use_markup=True), 0, 4, 1, 1)
+ oGrid.attach(Gtk.Label(_('Ask a question'), xalign=0), 0, 5, 1, 1)
+ oGrid.attach(Gtk.Label('<a href="https://github.com/AyatanaIndicators/ayatana-webmail/issues">https://github.com/AyatanaIndicators/ayatana-webmail/issues</a>', xalign=0, use_markup=True), 0, 6, 1, 1)
+ oGrid.attach(Gtk.Label(_('It\'s a good idea to add the {labelname} label to your issue.').format(labelname='<b>question</b>'), xalign=0, margin_bottom=10, use_markup=True), 0, 7, 1, 1)
+ #oGrid.attach(Gtk.Label(_('Help translate'), xalign=0), 0, 4, 1, 1)
+ #oGrid.attach(Gtk.Label('<a href="https://translations.launchpad.net/ayatana-webmail/trunk">https://translations.launchpad.net/ayatana-webmail/trunk</a>', xalign=0, use_markup=True, margin_bottom=10), 0, 5, 1, 1)
+ oGrid.attach(Gtk.Label(_('Source code'), xalign=0), 0, 8, 1, 1)
+ oGrid.attach(Gtk.Label('<a href="https://github.com/AyatanaIndicators/ayatana-webmail">https://github.com/AyatanaIndicators/ayatana-webmail</a>', xalign=0, use_markup=True, margin_bottom=10), 0, 9, 1, 1)
+ oGrid.attach(Gtk.Label(_('Home page'), xalign=0), 0, 10, 1, 1)
+ oGrid.attach(Gtk.Label('<a href="https://tari.in/www/software/ayatana-webmail/">https://tari.in/www/software/ayatana-webmail/</a>', xalign=0, use_markup=True, margin_bottom=10), 0, 11, 1, 1)
+
+ return oGrid
+
+ def onActivateLinkAbout(self, pAboutDialog, sUrl):
+
+ webbrowser.open_new_tab(sUrl)
+
+ return True
+
+ def pageAbout(self):
+
+ oBox = Gtk.Box()
+ oAboutDialog = Gtk.AboutDialog()
+ oAboutDialog.set_license_type(Gtk.License.GPL_3_0)
+ oAboutDialog.set_program_name(APPTITLE)
+ oAboutDialog.set_copyright(APPAUTHOR + ' ' + (APPYEAR if APPYEAR[-2:] == APPVERSION[:2] else APPYEAR + '-20' + APPVERSION[:2]))
+ oAboutDialog.set_comments(_(APPDESCRIPTION))
+ oAboutDialog.set_authors(['Dmitry Shachnev &lt;mitya57@gmail.com&gt;', 'Robert Tari &lt;robert@tari.in&gt;'])
+ oAboutDialog.set_translator_credits(_('translator-credits'))
+ oAboutDialog.set_version(APPVERSION)
+ oAboutDialog.set_website(APPURL)
+ oAboutDialog.set_website_label(APPURL)
+ oAboutDialog.set_logo(GdkPixbuf.Pixbuf().new_from_file(getDataPath('/usr/share/icons/hicolor/scalable/apps/ayatanawebmail.svg')))
+ oAboutDialog.get_content_area().reparent(oBox)
+ oAboutDialog.get_content_area().set_hexpand(True)
+ oAboutDialog.connect('activate_link', self.onActivateLinkAbout)
+
+ lstChildren = oAboutDialog.action_area.get_children()
+
+ for oWidget in lstChildren:
+
+ if (isinstance(oWidget, Gtk.Button) and not isinstance(oWidget, Gtk.ToggleButton)) or (isinstance(oWidget, Gtk.ToggleButton) and len(lstChildren) == 3 and oWidget == lstChildren[1]):
+
+ oWidget.set_property('no-show-all', True)
+ oWidget.set_property('visible', False)
+
+ return oBox
+
+ def onFolderActivated(self, oView, nRow, oColumn):
+
+ self.oListStore[nRow][2] = not self.oListStore[nRow][2]
+ self.updateUI()
+
+ def updateUI(self):
+
+ bHasFolderSelection = [oRow for oRow in self.oListStore if oRow[2]]
+ bHasAccountData = all([oWidget.get_text() for oWidget in [self.EntryHost, self.EntryPort, self.EntryLogin, self.EntryPassword]])
+ bHasMultipleAccounts = len(self.lstDicts) > 1
+
+ self.oButtonConnect.set_sensitive(bHasAccountData)
+ self.oButtonApply.set_sensitive(bHasFolderSelection and bHasAccountData)
+ self.rmbtn.set_sensitive(bHasMultipleAccounts)
+ self.addbtn.set_sensitive(bHasFolderSelection and bHasAccountData)
+ self.sb.set_sensitive(bHasFolderSelection and bHasAccountData and bHasMultipleAccounts)
+
+ def run(self):
+
+ if not self.lstDicts[0]['Passwd']:
+ self.updateEntries()
+
+ self.updateUI()
+ Gtk.main()
+
+ def saveAllSettings(self):
+
+ g_oSettings.set_int('max-item-count', self.nMaxCount)
+ g_oSettings.set_boolean('enable-notifications', self.notifyswitch.get_active())
+ g_oSettings.set_boolean('enable-sound', self.sndswitch.get_active())
+ g_oSettings.set_boolean('hide-messages-count', self.hcswitch.get_active())
+ g_oSettings.set_string('exec-on-receive', self.commandchooser.getFilename())
+ g_oSettings.set_string('custom-sound', self.sndchooser.getFilename())
+ g_oSettings.set_boolean('merge-messages', self.oSwitchMerge.get_active())
+ g_oSettings.set_enum('message-action', int(self.oComboMessageAction.get_active_id()))
+
+ def onAddAccount(self, btn):
+
+ self.updateAccounts()
+ self.lstDicts.append({'Host': 'imap.gmail.com', 'Port': '993', 'Login': '', 'Passwd': '', 'Folders': 'INBOX', 'InboxAppend': '/$MSG_THREAD'})
+ self.lstDicts[-1].update(g_dctDefaultURLs)
+ self.sb.set_range(1, len(self.lstDicts))
+ self.sb.set_value(len(self.lstDicts))
+ self.updateUI()
+
+ def onRemoveAccount(self, btn):
+
+ self.updateAccounts()
+ index = self.sb.get_value_as_int()-1
+
+ del self.lstDicts[index]
+
+ self.bInit = False
+ self.sb.set_range(1, len(self.lstDicts))
+ self.bInit = True
+ self.updateEntries()
+ self.updateUI()
+
+ if index+1 > len(self.lstDicts):
+ self.sb.set_value(index)
+
+ self.updateUI()
+
+ def setAccounts(self, lstDicts):
+
+ self.bInit = False
+ self.lstDicts = [dct for dct in lstDicts]
+ self.nIndex = 0
+ self.sb.set_range(1, len(lstDicts))
+ self.updateEntries()
+ self.updateUI()
+ self.bInit = True
+
+ def onAccountChanged(self, sb):
+
+ self.updateAccounts()
+ self.nIndex = self.sb.get_value_as_int() - 1
+ self.updateEntries()
+ self.updateUI()
+
+ def onSoundSwitchActivate(self, sndswitch, param):
+
+ self.sndbox.set_sensitive(sndswitch.get_active())
+
+ def updateEntries(self):
+
+ if self.lstDicts:
+
+ nIndex = self.sb.get_value_as_int() - 1
+ self.EntryHost.set_text(self.lstDicts[nIndex]['Host'])
+ self.EntryPort.set_text(str(self.lstDicts[nIndex]['Port']))
+ self.EntryLogin.set_text(self.lstDicts[nIndex]['Login'])
+ self.EntryPassword.set_text(self.lstDicts[nIndex]['Passwd'])
+
+ self.oListStore.clear()
+
+ if self.lstDicts[nIndex]['Passwd']:
+
+ self.getFolderList(False)
+
+ lstFolders = self.lstDicts[nIndex]['Folders'].split('\t')
+
+ for oRow in self.oListStore:
+ oRow[2] = oRow[0] in lstFolders
+
+ self.oEntryHome.setText(self.lstDicts[nIndex]['Home'])
+ self.oEntryCompose.setText(self.lstDicts[nIndex]['Compose'])
+ self.oEntryInbox.setText(self.lstDicts[nIndex]['Inbox'])
+ self.oEntrySent.setText(self.lstDicts[nIndex]['Sent'])
+ self.oEntryInboxAppend.set_text(self.lstDicts[nIndex]['InboxAppend'])
+
+ def updateAccounts(self):
+
+ if self.bInit:
+
+ self.lstDicts[self.nIndex]['Host'] = self.EntryHost.get_text()
+
+ if self.EntryPort.get_text():
+ self.lstDicts[self.nIndex]['Port'] = self.EntryPort.get_text()
+ else:
+ self.lstDicts[self.nIndex]['Port'] = '993'
+
+ self.lstDicts[self.nIndex]['Login'] = self.EntryLogin.get_text()
+ self.lstDicts[self.nIndex]['Passwd'] = self.EntryPassword.get_text()
+ self.lstDicts[self.nIndex]['Folders'] = '\t'.join([oRow[0] for oRow in self.oListStore if oRow[2]])
+ self.lstDicts[self.nIndex]['Home'] = self.oEntryHome.getText()
+ self.lstDicts[self.nIndex]['Compose'] = self.oEntryCompose.getText()
+ self.lstDicts[self.nIndex]['Inbox'] = self.oEntryInbox.getText()
+ self.lstDicts[self.nIndex]['Sent'] = self.oEntrySent.getText()
+ self.lstDicts[self.nIndex]['InboxAppend'] = self.oEntryInboxAppend.get_text()
diff --git a/ayatanawebmail/idler.py b/ayatanawebmail/idler.py
new file mode 100755
index 0000000..8f956ea
--- /dev/null
+++ b/ayatanawebmail/idler.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+import time
+from threading import *
+
+class Idler(object):
+
+ def __init__(self, oConnection, fnCallback, oLogger):
+
+ self.oThread = Thread(target=self.idle)
+ self.oConnection = oConnection
+ self.oEvent = Event()
+ self.fnCallback = fnCallback
+ self.bNeedSync = False
+ self.oLogger = oLogger
+ self.bAborted = False
+
+ def start(self):
+
+ self.oThread.start()
+
+ def stop(self):
+
+ self.oEvent.set()
+
+ def join(self):
+
+ self.oThread.join()
+
+ def idle(self):
+
+ while True:
+
+ if self.oEvent.isSet():
+ break
+
+ self.bNeedSync = False
+ self.bAborted = False
+
+ def callback(lstArgs):
+
+ if (lstArgs[2] != None) and (lstArgs[2][0] is self.oConnection.oImap.abort):
+
+ self.oLogger.info('"{0}:{1}" has been closed by the server.'.format(self.oConnection.strLogin, self.oConnection.strFolder))
+ self.bAborted = True
+
+ else:
+
+ self.bNeedSync = True
+
+ # We may need to skip the condition
+ # if not self.oEvent.isSet():
+ self.oEvent.set()
+
+ while not self.oConnection.isOpen():
+
+ self.oLogger.info('"{0}:{1}" IDLE is waiting for a connection.'.format(self.oConnection.strLogin, self.oConnection.strFolder))
+ time.sleep(10)
+
+ self.oConnection.oImap.idle(callback=callback, timeout=600)
+ self.oEvent.wait()
+
+ if self.bNeedSync:
+
+ self.oEvent.clear()
+ self.fnCallback(self.oConnection, False)
+
+ try:
+
+ if self.oConnection.oImap != None:
+ self.oConnection.oImap.noop()
+
+ except:
+
+ pass
+
+ if self.bAborted:
+ self.fnCallback(self.oConnection, True)
diff --git a/ayatanawebmail/imaplib2.py b/ayatanawebmail/imaplib2.py
new file mode 100755
index 0000000..056acb6
--- /dev/null
+++ b/ayatanawebmail/imaplib2.py
@@ -0,0 +1,2618 @@
+#!/usr/bin/env python
+
+"""Threaded IMAP4 client for Python 3.
+
+Based on RFC 3501 and original imaplib module.
+
+Public classes: IMAP4
+ IMAP4_SSL
+ IMAP4_stream
+
+Public functions: Internaldate2Time
+ ParseFlags
+ Time2Internaldate
+"""
+
+
+__all__ = ("IMAP4", "IMAP4_SSL", "IMAP4_stream",
+ "Internaldate2Time", "ParseFlags", "Time2Internaldate",
+ "Mon2num", "MonthNames", "InternalDate")
+
+__version__ = "3.05"
+__release__ = "3"
+__revision__ = "05"
+__credits__ = """
+Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
+String method conversion by ESR, February 2001.
+GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
+IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
+GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
+PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
+IDLE via threads suggested by Philippe Normand <phil@respyre.org> January 2005.
+GET/SETANNOTATION contributed by Tomas Lindroos <skitta@abo.fi> June 2005.
+COMPRESS/DEFLATE contributed by Bron Gondwana <brong@brong.net> May 2009.
+STARTTLS from Jython's imaplib by Alan Kennedy.
+ID contributed by Dave Baggett <dave@baggett.org> November 2009.
+Improved untagged responses handling suggested by Dave Baggett <dave@baggett.org> November 2009.
+Improved thread naming, and 0 read detection contributed by Grant Edwards <grant.b.edwards@gmail.com> June 2010.
+Improved timeout handling contributed by Ivan Vovnenko <ivovnenko@gmail.com> October 2010.
+Timeout handling further improved by Ethan Glasser-Camp <glasse@cs.rpi.edu> December 2010.
+Time2Internaldate() patch to match RFC2060 specification of English month names from bugs.python.org/issue11024 March 2011.
+starttls() bug fixed with the help of Sebastian Spaeth <sebastian@sspaeth.de> April 2011.
+Threads now set the "daemon" flag (suggested by offlineimap-project) April 2011.
+Single quoting introduced with the help of Vladimir Marek <vladimir.marek@oracle.com> August 2011.
+Support for specifying SSL version by Ryan Kavanagh <rak@debian.org> July 2013.
+Fix for gmail "read 0" error provided by Jim Greenleaf <james.a.greenleaf@gmail.com> August 2013.
+Fix for offlineimap "indexerror: string index out of range" bug provided by Eygene Ryabinkin <rea@codelabs.ru> August 2013.
+Fix for missing idle_lock in _handler() provided by Franklin Brook <franklin@brook.se> August 2014.
+Conversion to Python3 provided by F. Malina <fmalina@gmail.com> February 2015.
+Fix for READ-ONLY error from multiple EXAMINE/SELECT calls by Pierre-Louis Bonicoli <pierre-louis.bonicoli@gmx.fr> March 2015.
+Fix for null strings appended to untagged responses by Pierre-Louis Bonicoli <pierre-louis.bonicoli@gmx.fr> March 2015.
+Fix for correct byte encoding for _CRAM_MD5_AUTH taken from python3.5 imaplib.py June 2015.
+Fix for correct Python 3 exception handling by Tobias Brink <tobias.brink@gmail.com> August 2015.
+Fix to allow interruptible IDLE command by Tim Peoples <dromedary512@users.sf.net> September 2015.
+Add support for TLS levels by Ben Boeckel <mathstuf@gmail.com> September 2015.
+Fix for shutown exception by Sebastien Gross <seb@chezwam.org> November 2015."""
+__author__ = "Piers Lauder <piers@janeelix.com>"
+__URL__ = "http://imaplib2.sourceforge.net"
+__license__ = "Python License"
+
+import binascii, calendar, errno, os, queue, random, re, select, socket, sys, time, threading, zlib
+
+
+select_module = select
+
+# Globals
+
+CRLF = b'\r\n'
+IMAP4_PORT = 143
+IMAP4_SSL_PORT = 993
+
+IDLE_TIMEOUT_RESPONSE = b'* IDLE TIMEOUT\r\n'
+IDLE_TIMEOUT = 60*29 # Don't stay in IDLE state longer
+READ_POLL_TIMEOUT = 30 # Without this timeout interrupted network connections can hang reader
+READ_SIZE = 32768 # Consume all available in socket
+
+DFLT_DEBUG_BUF_LVL = 3 # Level above which the logging output goes directly to stderr
+
+TLS_SECURE = "tls_secure" # Recognised TLS levels
+TLS_NO_SSL = "tls_no_ssl"
+TLS_COMPAT = "tls_compat"
+
+AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
+
+# Commands
+
+CMD_VAL_STATES = 0
+CMD_VAL_ASYNC = 1
+NONAUTH, AUTH, SELECTED, LOGOUT = 'NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'
+
+Commands = {
+ # name valid states asynchronous
+ 'APPEND': ((AUTH, SELECTED), False),
+ 'AUTHENTICATE': ((NONAUTH,), False),
+ 'CAPABILITY': ((NONAUTH, AUTH, SELECTED), True),
+ 'CHECK': ((SELECTED,), True),
+ 'CLOSE': ((SELECTED,), False),
+ 'COMPRESS': ((AUTH,), False),
+ 'COPY': ((SELECTED,), True),
+ 'CREATE': ((AUTH, SELECTED), True),
+ 'DELETE': ((AUTH, SELECTED), True),
+ 'DELETEACL': ((AUTH, SELECTED), True),
+ 'ENABLE': ((AUTH,), False),
+ 'EXAMINE': ((AUTH, SELECTED), False),
+ 'EXPUNGE': ((SELECTED,), True),
+ 'FETCH': ((SELECTED,), True),
+ 'GETACL': ((AUTH, SELECTED), True),
+ 'GETANNOTATION':((AUTH, SELECTED), True),
+ 'GETQUOTA': ((AUTH, SELECTED), True),
+ 'GETQUOTAROOT': ((AUTH, SELECTED), True),
+ 'ID': ((NONAUTH, AUTH, LOGOUT, SELECTED), True),
+ 'IDLE': ((SELECTED,), False),
+ 'LIST': ((AUTH, SELECTED), True),
+ 'LOGIN': ((NONAUTH,), False),
+ 'LOGOUT': ((NONAUTH, AUTH, LOGOUT, SELECTED), False),
+ 'LSUB': ((AUTH, SELECTED), True),
+ 'MYRIGHTS': ((AUTH, SELECTED), True),
+ 'NAMESPACE': ((AUTH, SELECTED), True),
+ 'NOOP': ((NONAUTH, AUTH, SELECTED), True),
+ 'PARTIAL': ((SELECTED,), True),
+ 'PROXYAUTH': ((AUTH,), False),
+ 'RENAME': ((AUTH, SELECTED), True),
+ 'SEARCH': ((SELECTED,), True),
+ 'SELECT': ((AUTH, SELECTED), False),
+ 'SETACL': ((AUTH, SELECTED), False),
+ 'SETANNOTATION':((AUTH, SELECTED), True),
+ 'SETQUOTA': ((AUTH, SELECTED), False),
+ 'SORT': ((SELECTED,), True),
+ 'STARTTLS': ((NONAUTH,), False),
+ 'STATUS': ((AUTH, SELECTED), True),
+ 'STORE': ((SELECTED,), True),
+ 'SUBSCRIBE': ((AUTH, SELECTED), False),
+ 'THREAD': ((SELECTED,), True),
+ 'UID': ((SELECTED,), True),
+ 'UNSUBSCRIBE': ((AUTH, SELECTED), False),
+ }
+
+UID_direct = ('SEARCH', 'SORT', 'THREAD')
+
+
+def Int2AP(num):
+
+ """string = Int2AP(num)
+ Return 'num' converted to bytes using characters from the set 'A'..'P'
+ """
+
+ val = b''; AP = b'ABCDEFGHIJKLMNOP'
+ num = int(abs(num))
+ while num:
+ num, mod = divmod(num, 16)
+ val = AP[mod:mod+1] + val
+ return val
+
+
+
+class Request(object):
+
+ """Private class to represent a request awaiting response."""
+
+ def __init__(self, parent, name=None, callback=None, cb_arg=None, cb_self=False):
+ self.parent = parent
+ self.name = name
+ self.callback = callback # Function called to process result
+ if not cb_self:
+ self.callback_arg = cb_arg # Optional arg passed to "callback"
+ else:
+ self.callback_arg = (self, cb_arg) # Self reference required in callback arg
+
+ self.tag = parent.tagpre + bytes(str(parent.tagnum), 'ASCII')
+ parent.tagnum += 1
+
+ self.ready = threading.Event()
+ self.response = None
+ self.aborted = None
+ self.data = None
+
+
+ def abort(self, typ, val):
+ self.aborted = (typ, val)
+ self.deliver(None)
+
+
+ def get_response(self, exc_fmt=None):
+ self.callback = None
+ if __debug__: self.parent._log(3, '%s:%s.ready.wait' % (self.name, self.tag))
+ self.ready.wait()
+
+ if self.aborted is not None:
+ typ, val = self.aborted
+ if exc_fmt is None:
+ exc_fmt = '%s - %%s' % typ
+ raise typ(exc_fmt % str(val))
+
+ return self.response
+
+
+ def deliver(self, response):
+ if self.callback is not None:
+ self.callback((response, self.callback_arg, self.aborted))
+ return
+
+ self.response = response
+ self.ready.set()
+ if __debug__: self.parent._log(3, '%s:%s.ready.set' % (self.name, self.tag))
+
+
+
+
+class IMAP4(object):
+
+ """Threaded IMAP4 client class.
+
+ Instantiate with:
+ IMAP4(host=None, port=None, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None)
+
+ host - host's name (default: localhost);
+ port - port number (default: standard IMAP4 port);
+ debug - debug level (default: 0 - no debug);
+ debug_file - debug stream (default: sys.stderr);
+ identifier - thread identifier prefix (default: host);
+ timeout - timeout in seconds when expecting a command response (default: no timeout),
+ debug_buf_lvl - debug level at which buffering is turned off.
+
+ All IMAP4rev1 commands are supported by methods of the same name.
+
+ Each command returns a tuple: (type, [data, ...]) where 'type'
+ is usually 'OK' or 'NO', and 'data' is either the text from the
+ tagged response, or untagged results from command. Each 'data' is
+ either a string, or a tuple. If a tuple, then the first part is the
+ header of the response, and the second part contains the data (ie:
+ 'literal' value).
+
+ Errors raise the exception class <instance>.error("<reason>").
+ IMAP4 server errors raise <instance>.abort("<reason>"), which is
+ a sub-class of 'error'. Mailbox status changes from READ-WRITE to
+ READ-ONLY raise the exception class <instance>.readonly("<reason>"),
+ which is a sub-class of 'abort'.
+
+ "error" exceptions imply a program error.
+ "abort" exceptions imply the connection should be reset, and
+ the command re-tried.
+ "readonly" exceptions imply the command should be re-tried.
+
+ All commands take two optional named arguments:
+ 'callback' and 'cb_arg'
+ If 'callback' is provided then the command is asynchronous, so after
+ the command is queued for transmission, the call returns immediately
+ with the tuple (None, None).
+ The result will be posted by invoking "callback" with one arg, a tuple:
+ callback((result, cb_arg, None))
+ or, if there was a problem:
+ callback((None, cb_arg, (exception class, reason)))
+
+ Otherwise the command is synchronous (waits for result). But note
+ that state-changing commands will both block until previous commands
+ have completed, and block subsequent commands until they have finished.
+
+ All (non-callback) string arguments to commands are converted to bytes,
+ except for AUTHENTICATE, and the last argument to APPEND which is
+ passed as an IMAP4 literal. NB: the 'password' argument to the LOGIN
+ command is always quoted.
+
+ There is one instance variable, 'state', that is useful for tracking
+ whether the client needs to login to the server. If it has the
+ value "AUTH" after instantiating the class, then the connection
+ is pre-authenticated (otherwise it will be "NONAUTH"). Selecting a
+ mailbox changes the state to be "SELECTED", closing a mailbox changes
+ back to "AUTH", and once the client has logged out, the state changes
+ to "LOGOUT" and no further commands may be issued.
+
+ Note: to use this module, you must read the RFCs pertaining to the
+ IMAP4 protocol, as the semantics of the arguments to each IMAP4
+ command are left to the invoker, not to mention the results. Also,
+ most IMAP servers implement a sub-set of the commands available here.
+
+ Note also that you must call logout() to shut down threads before
+ discarding an instance.
+ """
+
+ class error(Exception): pass # Logical errors - debug required
+ class abort(error): pass # Service errors - close and retry
+ class readonly(abort): pass # Mailbox status changed to READ-ONLY
+
+ # These must be encoded according to utf8 setting in _mode_xxx():
+ _literal = br'.*{(?P<size>\d+)}$'
+ _untagged_status = br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?'
+
+ continuation_cre = re.compile(br'\+( (?P<data>.*))?')
+ mapCRLF_cre = re.compile(br'\r\n|\r|\n')
+ response_code_cre = re.compile(br'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
+ untagged_response_cre = re.compile(br'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
+
+
+ def __init__(self, host=None, port=None, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None):
+
+ self.state = NONAUTH # IMAP4 protocol state
+ self.literal = None # A literal argument to a command
+ self.tagged_commands = {} # Tagged commands awaiting response
+ self.untagged_responses = [] # [[typ: [data, ...]], ...]
+ self.mailbox = None # Current mailbox selected
+ self.is_readonly = False # READ-ONLY desired state
+ self.idle_rqb = None # Server IDLE Request - see _IdleCont
+ self.idle_timeout = None # Must prod server occasionally
+
+ self._expecting_data = False # Expecting message data
+ self._expecting_data_len = 0 # How many characters we expect
+ self._accumulated_data = [] # Message data accumulated so far
+ self._literal_expected = None # Message data descriptor
+
+ self.compressor = None # COMPRESS/DEFLATE if not None
+ self.decompressor = None
+ self._tls_established = False
+
+ # Create unique tag for this session,
+ # and compile tagged response matcher.
+
+ self.tagnum = 0
+ self.tagpre = Int2AP(random.randint(4096, 65535))
+ self.tagre = re.compile(br'(?P<tag>'
+ + self.tagpre
+ + br'\d+) (?P<type>[A-Z]+) (?P<data>.*)', re.ASCII)
+
+ self._mode_ascii()
+
+ if __debug__: self._init_debug(debug, debug_file, debug_buf_lvl)
+
+ self.resp_timeout = timeout # Timeout waiting for command response
+
+ if timeout is not None and timeout < READ_POLL_TIMEOUT:
+ self.read_poll_timeout = timeout
+ else:
+ self.read_poll_timeout = READ_POLL_TIMEOUT
+ self.read_size = READ_SIZE
+
+ # Open socket to server.
+
+ self.open(host, port)
+
+ if __debug__:
+ if debug:
+ self._mesg('connected to %s on port %s' % (self.host, self.port))
+
+ # Threading
+
+ if identifier is not None:
+ self.identifier = identifier
+ else:
+ self.identifier = self.host
+ if self.identifier:
+ self.identifier += ' '
+
+ self.Terminate = self.TerminateReader = False
+
+ self.state_change_free = threading.Event()
+ self.state_change_pending = threading.Lock()
+ self.commands_lock = threading.Lock()
+ self.idle_lock = threading.Lock()
+
+ self.ouq = queue.Queue(10)
+ self.inq = queue.Queue()
+
+ self.wrth = threading.Thread(target=self._writer)
+ self.wrth.setDaemon(True)
+ self.wrth.start()
+ self.rdth = threading.Thread(target=self._reader)
+ self.rdth.setDaemon(True)
+ self.rdth.start()
+ self.inth = threading.Thread(target=self._handler)
+ self.inth.setDaemon(True)
+ self.inth.start()
+
+ # Get server welcome message,
+ # request and store CAPABILITY response.
+
+ try:
+ self.welcome = self._request_push(name='welcome', tag='continuation').get_response('IMAP4 protocol error: %s')[1]
+
+ if self._get_untagged_response('PREAUTH'):
+ self.state = AUTH
+ if __debug__: self._log(1, 'state => AUTH')
+ elif self._get_untagged_response('OK'):
+ if __debug__: self._log(1, 'state => NONAUTH')
+ else:
+ raise self.error('unrecognised server welcome message: %s' % repr(self.welcome))
+
+ self._get_capabilities()
+ if __debug__: self._log(1, 'CAPABILITY: %r' % (self.capabilities,))
+
+ for version in AllowedVersions:
+ if not version in self.capabilities:
+ continue
+ self.PROTOCOL_VERSION = version
+ break
+ else:
+ raise self.error('server not IMAP4 compliant')
+ except:
+ self._close_threads()
+ raise
+
+
+ def __getattr__(self, attr):
+ # Allow UPPERCASE variants of IMAP4 command methods.
+ if attr in Commands:
+ return getattr(self, attr.lower())
+ raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
+
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ try:
+ self.logout()
+ except OSError:
+ pass
+
+
+ def _mode_ascii(self):
+ self.utf8_enabled = False
+ self._encoding = 'ascii'
+ self.literal_cre = re.compile(self._literal, re.ASCII)
+ self.untagged_status_cre = re.compile(self._untagged_status, re.ASCII)
+
+
+ def _mode_utf8(self):
+ self.utf8_enabled = True
+ self._encoding = 'utf-8'
+ self.literal_cre = re.compile(self._literal)
+ self.untagged_status_cre = re.compile(self._untagged_status)
+
+
+
+ # Overridable methods
+
+
+ def open(self, host=None, port=None):
+ """open(host=None, port=None)
+ Setup connection to remote server on "host:port"
+ (default: localhost:standard IMAP4 port).
+ This connection will be used by the routines:
+ read, send, shutdown, socket."""
+
+ self.host = self._choose_nonull_or_dflt('', host)
+ self.port = self._choose_nonull_or_dflt(IMAP4_PORT, port)
+ self.sock = self.open_socket()
+ self.read_fd = self.sock.fileno()
+
+
+ def open_socket(self):
+ """open_socket()
+ Open socket choosing first address family available."""
+
+ return socket.create_connection((self.host, self.port))
+
+
+ def ssl_wrap_socket(self):
+
+ try:
+ import ssl
+
+ TLS_MAP = {}
+ if hasattr(ssl, "PROTOCOL_TLSv1_2"):
+ TLS_MAP[TLS_SECURE] = {
+ "tls1_2": ssl.PROTOCOL_TLSv1_2,
+ "tls1_1": ssl.PROTOCOL_TLSv1_1,
+ }
+ else:
+ TLS_MAP[TLS_SECURE] = {}
+ TLS_MAP[TLS_NO_SSL] = TLS_MAP[TLS_SECURE].copy()
+ TLS_MAP[TLS_NO_SSL].update({
+ "tls1": ssl.PROTOCOL_TLSv1,
+ })
+ TLS_MAP[TLS_COMPAT] = TLS_MAP[TLS_NO_SSL].copy()
+ TLS_MAP[TLS_COMPAT].update({
+ "ssl23": ssl.PROTOCOL_SSLv23,
+ None: ssl.PROTOCOL_SSLv23,
+ })
+ if hasattr(ssl, "PROTOCOL_SSLv3"): # Might not be available.
+ TLS_MAP[TLS_COMPAT].update({
+ "ssl3": ssl.PROTOCOL_SSLv3
+ })
+
+ if self.ca_certs is not None:
+ cert_reqs = ssl.CERT_REQUIRED
+ else:
+ cert_reqs = ssl.CERT_NONE
+
+ if self.tls_level not in TLS_MAP:
+ raise RuntimeError("unknown tls_level: %s" % self.tls_level)
+
+ if self.ssl_version not in TLS_MAP[self.tls_level]:
+ raise socket.sslerror("Invalid SSL version '%s' requested for tls_version '%s'" % (self.ssl_version, self.tls_level))
+
+ ssl_version = TLS_MAP[self.tls_level][self.ssl_version]
+
+ self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=cert_reqs, ssl_version=ssl_version)
+ ssl_exc = ssl.SSLError
+ self.read_fd = self.sock.fileno()
+ except ImportError:
+ # No ssl module, and socket.ssl has no fileno(), and does not allow certificate verification
+ raise socket.sslerror("imaplib SSL mode does not work without ssl module")
+
+ if self.cert_verify_cb is not None:
+ cert_err = self.cert_verify_cb(self.sock.getpeercert(), self.host)
+ if cert_err:
+ raise ssl_exc(cert_err)
+
+ # Allow sending of keep-alive messages - seems to prevent some servers
+ # from closing SSL, leading to deadlocks.
+ self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+
+
+
+ def start_compressing(self):
+ """start_compressing()
+ Enable deflate compression on the socket (RFC 4978)."""
+
+ # rfc 1951 - pure DEFLATE, so use -15 for both windows
+ self.decompressor = zlib.decompressobj(-15)
+ self.compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
+
+
+ def read(self, size):
+ """data = read(size)
+ Read at most 'size' bytes from remote."""
+
+ if self.decompressor is None:
+ return self.sock.recv(size)
+
+ if self.decompressor.unconsumed_tail:
+ data = self.decompressor.unconsumed_tail
+ else:
+ data = self.sock.recv(READ_SIZE)
+
+ return self.decompressor.decompress(data, size)
+
+
+ def send(self, data):
+ """send(data)
+ Send 'data' to remote."""
+
+ if self.compressor is not None:
+ data = self.compressor.compress(data)
+ data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
+
+ self.sock.sendall(data)
+
+
+ def shutdown(self):
+ """shutdown()
+ Close I/O established in "open"."""
+
+ try:
+ self.sock.shutdown(socket.SHUT_RDWR)
+ except Exception as e:
+ # The server might already have closed the connection
+ if e.errno != errno.ENOTCONN:
+ raise
+ finally:
+ self.sock.close()
+
+
+ def socket(self):
+ """socket = socket()
+ Return socket instance used to connect to IMAP4 server."""
+
+ return self.sock
+
+
+
+ # Utility methods
+
+
+ def enable_compression(self):
+ """enable_compression()
+ Ask the server to start compressing the connection.
+ Should be called from user of this class after instantiation, as in:
+ if 'COMPRESS=DEFLATE' in imapobj.capabilities:
+ imapobj.enable_compression()"""
+
+ try:
+ typ, dat = self._simple_command('COMPRESS', 'DEFLATE')
+ if typ == 'OK':
+ self.start_compressing()
+ if __debug__: self._log(1, 'Enabled COMPRESS=DEFLATE')
+ finally:
+ self._release_state_change()
+
+
+ def pop_untagged_responses(self):
+ """ for typ,data in pop_untagged_responses(): pass
+ Generator for any remaining untagged responses.
+ Returns and removes untagged responses in order of reception.
+ Use at your own risk!"""
+
+ while self.untagged_responses:
+ self.commands_lock.acquire()
+ try:
+ yield self.untagged_responses.pop(0)
+ finally:
+ self.commands_lock.release()
+
+
+ def recent(self, **kw):
+ """(typ, [data]) = recent()
+ Return 'RECENT' responses if any exist,
+ else prompt server for an update using the 'NOOP' command.
+ 'data' is None if no new messages,
+ else list of RECENT responses, most recent last."""
+
+ name = 'RECENT'
+ typ, dat = self._untagged_response(None, [None], name)
+ if dat != [None]:
+ return self._deliver_dat(typ, dat, kw)
+ kw['untagged_response'] = name
+ return self.noop(**kw) # Prod server for response
+
+
+ def response(self, code, **kw):
+ """(code, [data]) = response(code)
+ Return data for response 'code' if received, or None.
+ Old value for response 'code' is cleared."""
+
+ typ, dat = self._untagged_response(code, [None], code.upper())
+ return self._deliver_dat(typ, dat, kw)
+
+
+
+
+ # IMAP4 commands
+
+
+ def append(self, mailbox, flags, date_time, message, **kw):
+ """(typ, [data]) = append(mailbox, flags, date_time, message)
+ Append message to named mailbox.
+ All args except `message' can be None."""
+
+ name = 'APPEND'
+ if not mailbox:
+ mailbox = 'INBOX'
+ if flags:
+ if (flags[0],flags[-1]) != ('(',')'):
+ flags = '(%s)' % flags
+ else:
+ flags = None
+ if date_time:
+ date_time = Time2Internaldate(date_time)
+ else:
+ date_time = None
+ if isinstance(message, str):
+ message = bytes(message, 'ASCII')
+ literal = self.mapCRLF_cre.sub(CRLF, message)
+ if self.utf8_enabled:
+ literal = b'UTF8 (' + literal + b')'
+ self.literal = literal
+ try:
+ return self._simple_command(name, mailbox, flags, date_time, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def authenticate(self, mechanism, authobject, **kw):
+ """(typ, [data]) = authenticate(mechanism, authobject)
+ Authenticate command - requires response processing.
+
+ 'mechanism' specifies which authentication mechanism is to
+ be used - it must appear in <instance>.capabilities in the
+ form AUTH=<mechanism>.
+
+ 'authobject' must be a callable object:
+
+ data = authobject(response)
+
+ It will be called to process server continuation responses,
+ the 'response' argument will be a 'bytes'. It should return
+ bytes that will be encoded and sent to server. It should
+ return None if the client abort response '*' should be sent
+ instead."""
+
+ self.literal = _Authenticator(authobject).process
+ try:
+ typ, dat = self._simple_command('AUTHENTICATE', mechanism.upper())
+ if typ != 'OK':
+ self._deliver_exc(self.error, dat[-1], kw)
+ self.state = AUTH
+ if __debug__: self._log(1, 'state => AUTH')
+ finally:
+ self._release_state_change()
+ return self._deliver_dat(typ, dat, kw)
+
+
+ def capability(self, **kw):
+ """(typ, [data]) = capability()
+ Fetch capabilities list from server."""
+
+ name = 'CAPABILITY'
+ kw['untagged_response'] = name
+ return self._simple_command(name, **kw)
+
+
+ def check(self, **kw):
+ """(typ, [data]) = check()
+ Checkpoint mailbox on server."""
+
+ return self._simple_command('CHECK', **kw)
+
+
+ def close(self, **kw):
+ """(typ, [data]) = close()
+ Close currently selected mailbox.
+
+ Deleted messages are removed from writable mailbox.
+ This is the recommended command before 'LOGOUT'."""
+
+ if self.state != 'SELECTED':
+ raise self.error('No mailbox selected.')
+ try:
+ typ, dat = self._simple_command('CLOSE')
+ finally:
+ self.state = AUTH
+ if __debug__: self._log(1, 'state => AUTH')
+ self._release_state_change()
+ return self._deliver_dat(typ, dat, kw)
+
+
+ def copy(self, message_set, new_mailbox, **kw):
+ """(typ, [data]) = copy(message_set, new_mailbox)
+ Copy 'message_set' messages onto end of 'new_mailbox'."""
+
+ return self._simple_command('COPY', message_set, new_mailbox, **kw)
+
+
+ def create(self, mailbox, **kw):
+ """(typ, [data]) = create(mailbox)
+ Create new mailbox."""
+
+ return self._simple_command('CREATE', mailbox, **kw)
+
+
+ def delete(self, mailbox, **kw):
+ """(typ, [data]) = delete(mailbox)
+ Delete old mailbox."""
+
+ return self._simple_command('DELETE', mailbox, **kw)
+
+
+ def deleteacl(self, mailbox, who, **kw):
+ """(typ, [data]) = deleteacl(mailbox, who)
+ Delete the ACLs (remove any rights) set for who on mailbox."""
+
+ return self._simple_command('DELETEACL', mailbox, who, **kw)
+
+
+ def enable(self, capability):
+ """Send an RFC5161 enable string to the server.
+
+ (typ, [data]) = <intance>.enable(capability)
+ """
+ if 'ENABLE' not in self.capabilities:
+ raise self.error("Server does not support ENABLE")
+ typ, data = self._simple_command('ENABLE', capability)
+ if typ == 'OK' and 'UTF8=ACCEPT' in capability.upper():
+ self._mode_utf8()
+ return typ, data
+
+
+ def examine(self, mailbox='INBOX', **kw):
+ """(typ, [data]) = examine(mailbox='INBOX')
+ Select a mailbox for READ-ONLY access. (Flushes all untagged responses.)
+ 'data' is count of messages in mailbox ('EXISTS' response).
+ Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
+ other responses should be obtained via "response('FLAGS')" etc."""
+
+ return self.select(mailbox=mailbox, readonly=True, **kw)
+
+
+ def expunge(self, **kw):
+ """(typ, [data]) = expunge()
+ Permanently remove deleted items from selected mailbox.
+ Generates 'EXPUNGE' response for each deleted message.
+ 'data' is list of 'EXPUNGE'd message numbers in order received."""
+
+ name = 'EXPUNGE'
+ kw['untagged_response'] = name
+ return self._simple_command(name, **kw)
+
+
+ def fetch(self, message_set, message_parts, **kw):
+ """(typ, [data, ...]) = fetch(message_set, message_parts)
+ Fetch (parts of) messages.
+ 'message_parts' should be a string of selected parts
+ enclosed in parentheses, eg: "(UID BODY[TEXT])".
+ 'data' are tuples of message part envelope and data,
+ followed by a string containing the trailer."""
+
+ name = 'FETCH'
+ kw['untagged_response'] = name
+ return self._simple_command(name, message_set, message_parts, **kw)
+
+
+ def getacl(self, mailbox, **kw):
+ """(typ, [data]) = getacl(mailbox)
+ Get the ACLs for a mailbox."""
+
+ kw['untagged_response'] = 'ACL'
+ return self._simple_command('GETACL', mailbox, **kw)
+
+
+ def getannotation(self, mailbox, entry, attribute, **kw):
+ """(typ, [data]) = getannotation(mailbox, entry, attribute)
+ Retrieve ANNOTATIONs."""
+
+ kw['untagged_response'] = 'ANNOTATION'
+ return self._simple_command('GETANNOTATION', mailbox, entry, attribute, **kw)
+
+
+ def getquota(self, root, **kw):
+ """(typ, [data]) = getquota(root)
+ Get the quota root's resource usage and limits.
+ (Part of the IMAP4 QUOTA extension defined in rfc2087.)"""
+
+ kw['untagged_response'] = 'QUOTA'
+ return self._simple_command('GETQUOTA', root, **kw)
+
+
+ def getquotaroot(self, mailbox, **kw):
+ # Hmmm, this is non-std! Left for backwards-compatibility, sigh.
+ # NB: usage should have been defined as:
+ # (typ, [QUOTAROOT responses...]) = getquotaroot(mailbox)
+ # (typ, [QUOTA responses...]) = response('QUOTA')
+ """(typ, [[QUOTAROOT responses...], [QUOTA responses...]]) = getquotaroot(mailbox)
+ Get the list of quota roots for the named mailbox."""
+
+ typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
+ typ, quota = self._untagged_response(typ, dat, 'QUOTA')
+ typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
+ return self._deliver_dat(typ, [quotaroot, quota], kw)
+
+
+ def id(self, *kv_pairs, **kw):
+ """(typ, [data]) = <instance>.id(kv_pairs)
+ 'kv_pairs' is a possibly empty list of keys and values.
+ 'data' is a list of ID key value pairs or NIL.
+ NB: a single argument is assumed to be correctly formatted and is passed through unchanged
+ (for backward compatibility with earlier version).
+ Exchange information for problem analysis and determination.
+ The ID extension is defined in RFC 2971. """
+
+ name = 'ID'
+ kw['untagged_response'] = name
+
+ if not kv_pairs:
+ data = 'NIL'
+ elif len(kv_pairs) == 1:
+ data = kv_pairs[0] # Assume invoker passing correctly formatted string (back-compat)
+ else:
+ data = '(%s)' % ' '.join([(arg and self._quote(arg) or 'NIL') for arg in kv_pairs])
+
+ return self._simple_command(name, data, **kw)
+
+
+ def idle(self, timeout=None, **kw):
+ """"(typ, [data]) = idle(timeout=None)
+ Put server into IDLE mode until server notifies some change,
+ or 'timeout' (secs) occurs (default: 29 minutes),
+ or another IMAP4 command is scheduled."""
+
+ name = 'IDLE'
+ self.literal = _IdleCont(self, timeout).process
+ try:
+ return self._simple_command(name, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def list(self, directory='""', pattern='*', **kw):
+ """(typ, [data]) = list(directory='""', pattern='*')
+ List mailbox names in directory matching pattern.
+ 'data' is list of LIST responses.
+
+ NB: for 'pattern':
+ % matches all except separator ( so LIST "" "%" returns names at root)
+ * matches all (so LIST "" "*" returns whole directory tree from root)"""
+
+ name = 'LIST'
+ kw['untagged_response'] = name
+ return self._simple_command(name, directory, pattern, **kw)
+
+
+ def login(self, user, password, **kw):
+ """(typ, [data]) = login(user, password)
+ Identify client using plaintext password.
+ NB: 'password' will be quoted."""
+
+ try:
+ typ, dat = self._simple_command('LOGIN', user, self._quote(password))
+ if typ != 'OK':
+ self._deliver_exc(self.error, dat[-1], kw)
+ self.state = AUTH
+ if __debug__: self._log(1, 'state => AUTH')
+ finally:
+ self._release_state_change()
+ return self._deliver_dat(typ, dat, kw)
+
+
+ def login_cram_md5(self, user, password, **kw):
+ """(typ, [data]) = login_cram_md5(user, password)
+ Force use of CRAM-MD5 authentication."""
+
+ self.user, self.password = user, password
+ return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH, **kw)
+
+
+ def _CRAM_MD5_AUTH(self, challenge):
+ """Authobject to use with CRAM-MD5 authentication."""
+ import hmac
+ pwd = (self.password.encode('utf-8') if isinstance(self.password, str)
+ else self.password)
+ return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest()
+
+
+ def logout(self, **kw):
+ """(typ, [data]) = logout()
+ Shutdown connection to server.
+ Returns server 'BYE' response.
+ NB: You must call this to shut down threads before discarding an instance."""
+
+ self.state = LOGOUT
+ if __debug__: self._log(1, 'state => LOGOUT')
+
+ try:
+ try:
+ typ, dat = self._simple_command('LOGOUT')
+ except:
+ typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
+ if __debug__: self._log(1, dat)
+
+ self._close_threads()
+ finally:
+ self._release_state_change()
+
+ if __debug__: self._log(1, 'connection closed')
+
+ bye = self._get_untagged_response('BYE', leave=True)
+ if bye:
+ typ, dat = 'BYE', bye
+ return self._deliver_dat(typ, dat, kw)
+
+
+ def lsub(self, directory='""', pattern='*', **kw):
+ """(typ, [data, ...]) = lsub(directory='""', pattern='*')
+ List 'subscribed' mailbox names in directory matching pattern.
+ 'data' are tuples of message part envelope and data."""
+
+ name = 'LSUB'
+ kw['untagged_response'] = name
+ return self._simple_command(name, directory, pattern, **kw)
+
+
+ def myrights(self, mailbox, **kw):
+ """(typ, [data]) = myrights(mailbox)
+ Show my ACLs for a mailbox (i.e. the rights that I have on mailbox)."""
+
+ name = 'MYRIGHTS'
+ kw['untagged_response'] = name
+ return self._simple_command(name, mailbox, **kw)
+
+
+ def namespace(self, **kw):
+ """(typ, [data, ...]) = namespace()
+ Returns IMAP namespaces ala rfc2342."""
+
+ name = 'NAMESPACE'
+ kw['untagged_response'] = name
+ return self._simple_command(name, **kw)
+
+
+ def noop(self, **kw):
+ """(typ, [data]) = noop()
+ Send NOOP command."""
+
+ if __debug__: self._dump_ur(3)
+ return self._simple_command('NOOP', **kw)
+
+
+ def partial(self, message_num, message_part, start, length, **kw):
+ """(typ, [data, ...]) = partial(message_num, message_part, start, length)
+ Fetch truncated part of a message.
+ 'data' is tuple of message part envelope and data.
+ NB: obsolete."""
+
+ name = 'PARTIAL'
+ kw['untagged_response'] = 'FETCH'
+ return self._simple_command(name, message_num, message_part, start, length, **kw)
+
+
+ def proxyauth(self, user, **kw):
+ """(typ, [data]) = proxyauth(user)
+ Assume authentication as 'user'.
+ (Allows an authorised administrator to proxy into any user's mailbox.)"""
+
+ try:
+ return self._simple_command('PROXYAUTH', user, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def rename(self, oldmailbox, newmailbox, **kw):
+ """(typ, [data]) = rename(oldmailbox, newmailbox)
+ Rename old mailbox name to new."""
+
+ return self._simple_command('RENAME', oldmailbox, newmailbox, **kw)
+
+
+ def search(self, charset, *criteria, **kw):
+ """(typ, [data]) = search(charset, criterion, ...)
+ Search mailbox for matching messages.
+ If UTF8 is enabled, charset MUST be None.
+ 'data' is space separated list of matching message numbers."""
+
+ name = 'SEARCH'
+ kw['untagged_response'] = name
+ if charset:
+ if self.utf8_enabled:
+ raise self.error("Non-None charset not valid in UTF8 mode")
+ return self._simple_command(name, 'CHARSET', charset, *criteria, **kw)
+ return self._simple_command(name, *criteria, **kw)
+
+
+ def select(self, mailbox='INBOX', readonly=False, **kw):
+ """(typ, [data]) = select(mailbox='INBOX', readonly=False)
+ Select a mailbox. (Flushes all untagged responses.)
+ 'data' is count of messages in mailbox ('EXISTS' response).
+ Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
+ other responses should be obtained via "response('FLAGS')" etc."""
+
+ self.mailbox = mailbox
+
+ self.is_readonly = bool(readonly)
+ if readonly:
+ name = 'EXAMINE'
+ else:
+ name = 'SELECT'
+ try:
+ rqb = self._command(name, mailbox)
+ typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
+ if typ != 'OK':
+ if self.state == SELECTED:
+ self.state = AUTH
+ if __debug__: self._log(1, 'state => AUTH')
+ if typ == 'BAD':
+ self._deliver_exc(self.error, '%s command error: %s %s. Data: %.100s' % (name, typ, dat, mailbox), kw)
+ return self._deliver_dat(typ, dat, kw)
+ self.state = SELECTED
+ if __debug__: self._log(1, 'state => SELECTED')
+ finally:
+ self._release_state_change()
+
+ if self._get_untagged_response('READ-ONLY', leave=True) and not readonly:
+ if __debug__: self._dump_ur(1)
+ self._deliver_exc(self.readonly, '%s is not writable' % mailbox, kw)
+ typ, dat = self._untagged_response(typ, [None], 'EXISTS')
+ return self._deliver_dat(typ, dat, kw)
+
+
+ def setacl(self, mailbox, who, what, **kw):
+ """(typ, [data]) = setacl(mailbox, who, what)
+ Set a mailbox acl."""
+
+ try:
+ return self._simple_command('SETACL', mailbox, who, what, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def setannotation(self, *args, **kw):
+ """(typ, [data]) = setannotation(mailbox[, entry, attribute]+)
+ Set ANNOTATIONs."""
+
+ kw['untagged_response'] = 'ANNOTATION'
+ return self._simple_command('SETANNOTATION', *args, **kw)
+
+
+ def setquota(self, root, limits, **kw):
+ """(typ, [data]) = setquota(root, limits)
+ Set the quota root's resource limits."""
+
+ kw['untagged_response'] = 'QUOTA'
+ try:
+ return self._simple_command('SETQUOTA', root, limits, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def sort(self, sort_criteria, charset, *search_criteria, **kw):
+ """(typ, [data]) = sort(sort_criteria, charset, search_criteria, ...)
+ IMAP4rev1 extension SORT command."""
+
+ name = 'SORT'
+ if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
+ sort_criteria = '(%s)' % sort_criteria
+ kw['untagged_response'] = name
+ return self._simple_command(name, sort_criteria, charset, *search_criteria, **kw)
+
+
+ def starttls(self, keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", tls_level=TLS_COMPAT, **kw):
+ """(typ, [data]) = starttls(keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", tls_level="tls_compat")
+ Start TLS negotiation as per RFC 2595."""
+
+ name = 'STARTTLS'
+
+ if name not in self.capabilities:
+ raise self.abort('TLS not supported by server')
+
+ if self._tls_established:
+ raise self.abort('TLS session already established')
+
+ # Must now shutdown reader thread after next response, and restart after changing read_fd
+
+ self.read_size = 1 # Don't consume TLS handshake
+ self.TerminateReader = True
+
+ try:
+ typ, dat = self._simple_command(name)
+ finally:
+ self._release_state_change()
+ self.rdth.join()
+ self.TerminateReader = False
+ self.read_size = READ_SIZE
+
+ if typ != 'OK':
+ # Restart reader thread and error
+ self.rdth = threading.Thread(target=self._reader)
+ self.rdth.setDaemon(True)
+ self.rdth.start()
+ raise self.error("Couldn't establish TLS session: %s" % dat)
+
+ self.keyfile = keyfile
+ self.certfile = certfile
+ self.ca_certs = ca_certs
+ self.cert_verify_cb = cert_verify_cb
+ self.ssl_version = ssl_version
+ self.tls_level = tls_level
+
+ try:
+ self.ssl_wrap_socket()
+ finally:
+ # Restart reader thread
+ self.rdth = threading.Thread(target=self._reader)
+ self.rdth.setDaemon(True)
+ self.rdth.start()
+
+ self._get_capabilities()
+
+ self._tls_established = True
+
+ typ, dat = self._untagged_response(typ, dat, name)
+ return self._deliver_dat(typ, dat, kw)
+
+
+ def status(self, mailbox, names, **kw):
+ """(typ, [data]) = status(mailbox, names)
+ Request named status conditions for mailbox."""
+
+ name = 'STATUS'
+ kw['untagged_response'] = name
+ return self._simple_command(name, mailbox, names, **kw)
+
+
+ def store(self, message_set, command, flags, **kw):
+ """(typ, [data]) = store(message_set, command, flags)
+ Alters flag dispositions for messages in mailbox."""
+
+ if (flags[0],flags[-1]) != ('(',')'):
+ flags = '(%s)' % flags # Avoid quoting the flags
+ kw['untagged_response'] = 'FETCH'
+ return self._simple_command('STORE', message_set, command, flags, **kw)
+
+
+ def subscribe(self, mailbox, **kw):
+ """(typ, [data]) = subscribe(mailbox)
+ Subscribe to new mailbox."""
+
+ try:
+ return self._simple_command('SUBSCRIBE', mailbox, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def thread(self, threading_algorithm, charset, *search_criteria, **kw):
+ """(type, [data]) = thread(threading_alogrithm, charset, search_criteria, ...)
+ IMAPrev1 extension THREAD command."""
+
+ name = 'THREAD'
+ kw['untagged_response'] = name
+ return self._simple_command(name, threading_algorithm, charset, *search_criteria, **kw)
+
+
+ def uid(self, command, *args, **kw):
+ """(typ, [data]) = uid(command, arg, ...)
+ Execute "command arg ..." with messages identified by UID,
+ rather than message number.
+ Assumes 'command' is legal in current state.
+ Returns response appropriate to 'command'."""
+
+ command = command.upper()
+ if command in UID_direct:
+ resp = command
+ else:
+ resp = 'FETCH'
+ kw['untagged_response'] = resp
+ return self._simple_command('UID', command, *args, **kw)
+
+
+ def unsubscribe(self, mailbox, **kw):
+ """(typ, [data]) = unsubscribe(mailbox)
+ Unsubscribe from old mailbox."""
+
+ try:
+ return self._simple_command('UNSUBSCRIBE', mailbox, **kw)
+ finally:
+ self._release_state_change()
+
+
+ def xatom(self, name, *args, **kw):
+ """(typ, [data]) = xatom(name, arg, ...)
+ Allow simple extension commands notified by server in CAPABILITY response.
+ Assumes extension command 'name' is legal in current state.
+ Returns response appropriate to extension command 'name'."""
+
+ name = name.upper()
+ if not name in Commands:
+ Commands[name] = ((self.state,), False)
+ try:
+ return self._simple_command(name, *args, **kw)
+ finally:
+ self._release_state_change()
+
+
+
+ # Internal methods
+
+
+ def _append_untagged(self, typ, dat):
+
+ # Append new 'dat' to end of last untagged response if same 'typ',
+ # else append new response.
+
+ if dat is None: dat = b''
+
+ self.commands_lock.acquire()
+
+ if self.untagged_responses:
+ urn, urd = self.untagged_responses[-1]
+ if urn != typ:
+ urd = None
+ else:
+ urd = None
+
+ if urd is None:
+ urd = []
+ self.untagged_responses.append([typ, urd])
+
+ urd.append(dat)
+
+ self.commands_lock.release()
+
+ if __debug__: self._log(5, 'untagged_responses[%s] %s += ["%.80r"]' % (typ, len(urd)-1, dat))
+
+
+ def _check_bye(self):
+
+ bye = self._get_untagged_response('BYE', leave=True)
+ if bye:
+ raise self.abort(bye[-1].decode('ASCII', 'replace'))
+
+
+ def _choose_nonull_or_dflt(self, dflt, *args):
+ if isinstance(dflt, str):
+ dflttyp = str # Allow any string type
+ else:
+ dflttyp = type(dflt)
+ for arg in args:
+ if arg is not None:
+ if isinstance(arg, dflttyp):
+ return arg
+ if __debug__: self._log(0, 'bad arg is %s, expecting %s' % (type(arg), dflttyp))
+ return dflt
+
+
+ def _command(self, name, *args, **kw):
+
+ if Commands[name][CMD_VAL_ASYNC]:
+ cmdtyp = 'async'
+ else:
+ cmdtyp = 'sync'
+
+ if __debug__: self._log(1, '[%s] %s %s' % (cmdtyp, name, args))
+
+ if __debug__: self._log(3, 'state_change_pending.acquire')
+ self.state_change_pending.acquire()
+
+ self._end_idle()
+
+ if cmdtyp == 'async':
+ self.state_change_pending.release()
+ if __debug__: self._log(3, 'state_change_pending.release')
+ else:
+ # Need to wait for all async commands to complete
+ self._check_bye()
+ self.commands_lock.acquire()
+ if self.tagged_commands:
+ self.state_change_free.clear()
+ need_event = True
+ else:
+ need_event = False
+ self.commands_lock.release()
+ if need_event:
+ if __debug__: self._log(3, 'sync command %s waiting for empty commands Q' % name)
+ self.state_change_free.wait()
+ if __debug__: self._log(3, 'sync command %s proceeding' % name)
+
+ if self.state not in Commands[name][CMD_VAL_STATES]:
+ self.literal = None
+ raise self.error('command %s illegal in state %s'
+ % (name, self.state))
+
+ self._check_bye()
+
+ if name in ('EXAMINE', 'SELECT'):
+ self.commands_lock.acquire()
+ self.untagged_responses = [] # Flush all untagged responses
+ self.commands_lock.release()
+ else:
+ for typ in ('OK', 'NO', 'BAD'):
+ while self._get_untagged_response(typ):
+ continue
+
+ if not self.is_readonly and self._get_untagged_response('READ-ONLY', leave=True):
+ self.literal = None
+ raise self.readonly('mailbox status changed to READ-ONLY')
+
+ if self.Terminate:
+ raise self.abort('connection closed')
+
+ rqb = self._request_push(name=name, **kw)
+
+ name = bytes(name, self._encoding)
+ data = rqb.tag + b' ' + name
+ for arg in args:
+ if arg is None: continue
+ if isinstance(arg, str):
+ arg = bytes(arg, self._encoding)
+ data = data + b' ' + arg
+
+ literal = self.literal
+ if literal is not None:
+ self.literal = None
+ if type(literal) is type(self._command):
+ literator = literal
+ else:
+ literator = None
+ data = data + bytes(' {%s}' % len(literal), self._encoding)
+
+ if __debug__: self._log(4, 'data=%r' % data)
+
+ rqb.data = data + CRLF
+
+ if literal is None:
+ self.ouq.put(rqb)
+ return rqb
+
+ # Must setup continuation expectancy *before* ouq.put
+ crqb = self._request_push(name=name, tag='continuation')
+
+ self.ouq.put(rqb)
+
+ while True:
+ # Wait for continuation response
+
+ ok, data = crqb.get_response('command: %s => %%s' % name)
+ if __debug__: self._log(4, 'continuation => %s, %r' % (ok, data))
+
+ # NO/BAD response?
+
+ if not ok:
+ break
+
+ if data == 'go ahead': # Apparently not uncommon broken IMAP4 server response to AUTHENTICATE command
+ data = ''
+
+ # Send literal
+
+ if literator is not None:
+ literal = literator(data, rqb)
+
+ if literal is None:
+ break
+
+ if literator is not None:
+ # Need new request for next continuation response
+ crqb = self._request_push(name=name, tag='continuation')
+
+ if __debug__: self._log(4, 'write literal size %s' % len(literal))
+ crqb.data = literal + CRLF
+ self.ouq.put(crqb)
+
+ if literator is None:
+ break
+
+ return rqb
+
+
+ def _command_complete(self, rqb, kw):
+
+ # Called for non-callback commands
+
+ self._check_bye()
+ typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
+ if typ == 'BAD':
+ if __debug__: self._print_log()
+ raise self.error('%s command error: %s %s. Data: %.100s' % (rqb.name, typ, dat, rqb.data))
+ if 'untagged_response' in kw:
+ return self._untagged_response(typ, dat, kw['untagged_response'])
+ return typ, dat
+
+
+ def _command_completer(self, cb_arg_list):
+
+ # Called for callback commands
+ response, cb_arg, error = cb_arg_list
+ rqb, kw = cb_arg
+ rqb.callback = kw['callback']
+ rqb.callback_arg = kw.get('cb_arg')
+ if error is not None:
+ if __debug__: self._print_log()
+ typ, val = error
+ rqb.abort(typ, val)
+ return
+ bye = self._get_untagged_response('BYE', leave=True)
+ if bye:
+ rqb.abort(self.abort, bye[-1].decode('ASCII', 'replace'))
+ return
+ typ, dat = response
+ if typ == 'BAD':
+ if __debug__: self._print_log()
+ rqb.abort(self.error, '%s command error: %s %s. Data: %.100s' % (rqb.name, typ, dat, rqb.data))
+ return
+ if __debug__: self._log(4, '_command_completer(%s, %s, None) = %s' % (response, cb_arg, rqb.tag))
+ if 'untagged_response' in kw:
+ response = self._untagged_response(typ, dat, kw['untagged_response'])
+ rqb.deliver(response)
+
+
+ def _deliver_dat(self, typ, dat, kw):
+
+ if 'callback' in kw:
+ kw['callback'](((typ, dat), kw.get('cb_arg'), None))
+ return typ, dat
+
+
+ def _deliver_exc(self, exc, dat, kw):
+
+ if 'callback' in kw:
+ kw['callback']((None, kw.get('cb_arg'), (exc, dat)))
+ raise exc(dat)
+
+
+ def _end_idle(self):
+
+ self.idle_lock.acquire()
+ irqb = self.idle_rqb
+ if irqb is None:
+ self.idle_lock.release()
+ return
+ self.idle_rqb = None
+ self.idle_timeout = None
+ self.idle_lock.release()
+ irqb.data = bytes('DONE', 'ASCII') + CRLF
+ self.ouq.put(irqb)
+ if __debug__: self._log(2, 'server IDLE finished')
+
+
+ def _get_capabilities(self):
+ typ, dat = self.capability()
+ if dat == [None]:
+ raise self.error('no CAPABILITY response from server')
+ dat = str(dat[-1], "ASCII")
+ dat = dat.upper()
+ self.capabilities = tuple(dat.split())
+
+
+ def _get_untagged_response(self, name, leave=False):
+
+ self.commands_lock.acquire()
+
+ for i, (typ, dat) in enumerate(self.untagged_responses):
+ if typ == name:
+ if not leave:
+ del self.untagged_responses[i]
+ self.commands_lock.release()
+ if __debug__: self._log(5, '_get_untagged_response(%s) => %.80r' % (name, dat))
+ return dat
+
+ self.commands_lock.release()
+ return None
+
+
+ def _match(self, cre, s):
+
+ # Run compiled regular expression 'cre' match method on 's'.
+ # Save result, return success.
+
+ self.mo = cre.match(s)
+ return self.mo is not None
+
+
+ def _put_response(self, resp):
+
+ if self._expecting_data:
+ rlen = len(resp)
+ dlen = min(self._expecting_data_len, rlen)
+ if __debug__: self._log(5, '_put_response expecting data len %s, got %s' % (self._expecting_data_len, rlen))
+ self._expecting_data_len -= dlen
+ self._expecting_data = (self._expecting_data_len != 0)
+ if rlen <= dlen:
+ self._accumulated_data.append(resp)
+ return
+ self._accumulated_data.append(resp[:dlen])
+ resp = resp[dlen:]
+
+ if self._accumulated_data:
+ typ, dat = self._literal_expected
+ self._append_untagged(typ, (dat, b''.join(self._accumulated_data)))
+ self._accumulated_data = []
+
+ # Protocol mandates all lines terminated by CRLF
+ resp = resp[:-2]
+ if __debug__: self._log(5, '_put_response(%r)' % resp)
+
+ if 'continuation' in self.tagged_commands:
+ continuation_expected = True
+ else:
+ continuation_expected = False
+
+ if self._literal_expected is not None:
+ dat = resp
+ if self._match(self.literal_cre, dat):
+ self._literal_expected[1] = dat
+ self._expecting_data = True
+ self._expecting_data_len = int(self.mo.group('size'))
+ if __debug__: self._log(4, 'expecting literal size %s' % self._expecting_data_len)
+ return
+ typ = self._literal_expected[0]
+ self._literal_expected = None
+ if dat:
+ self._append_untagged(typ, dat) # Tail
+ if __debug__: self._log(4, 'literal completed')
+ else:
+ # Command completion response?
+ if self._match(self.tagre, resp):
+ tag = self.mo.group('tag')
+ typ = str(self.mo.group('type'), 'ASCII')
+ dat = self.mo.group('data')
+ if typ in ('OK', 'NO', 'BAD') and self._match(self.response_code_cre, dat):
+ self._append_untagged(str(self.mo.group('type'), 'ASCII'), self.mo.group('data'))
+ if not tag in self.tagged_commands:
+ if __debug__: self._log(1, 'unexpected tagged response: %r' % resp)
+ else:
+ self._request_pop(tag, (typ, [dat]))
+ else:
+ dat2 = None
+
+ # '*' (untagged) responses?
+
+ if not self._match(self.untagged_response_cre, resp):
+ if self._match(self.untagged_status_cre, resp):
+ dat2 = self.mo.group('data2')
+
+ if self.mo is None:
+ # Only other possibility is '+' (continuation) response...
+
+ if self._match(self.continuation_cre, resp):
+ if not continuation_expected:
+ if __debug__: self._log(1, "unexpected continuation response: '%r'" % resp)
+ return
+ self._request_pop('continuation', (True, self.mo.group('data')))
+ return
+
+ if __debug__: self._log(1, "unexpected response: '%r'" % resp)
+ return
+
+ typ = str(self.mo.group('type'), 'ASCII')
+ dat = self.mo.group('data')
+ if dat is None: dat = b'' # Null untagged response
+ if dat2: dat = dat + b' ' + dat2
+
+ # Is there a literal to come?
+
+ if self._match(self.literal_cre, dat):
+ self._expecting_data = True
+ self._expecting_data_len = int(self.mo.group('size'))
+ if __debug__: self._log(4, 'read literal size %s' % self._expecting_data_len)
+ self._literal_expected = [typ, dat]
+ return
+
+ self._append_untagged(typ, dat)
+ if typ in ('OK', 'NO', 'BAD') and self._match(self.response_code_cre, dat):
+ self._append_untagged(str(self.mo.group('type'), 'ASCII'), self.mo.group('data'))
+
+ if typ != 'OK': # NO, BYE, IDLE
+ self._end_idle()
+
+ # Command waiting for aborted continuation response?
+
+ if continuation_expected:
+ self._request_pop('continuation', (False, resp))
+
+ # Bad news?
+
+ if typ in ('NO', 'BAD', 'BYE'):
+ if typ == 'BYE':
+ self.Terminate = True
+ if __debug__: self._log(1, '%s response: %r' % (typ, dat))
+
+
+ def _quote(self, arg):
+
+ return '"%s"' % arg.replace('\\', '\\\\').replace('"', '\\"')
+
+
+ def _release_state_change(self):
+
+ if self.state_change_pending.locked():
+ self.state_change_pending.release()
+ if __debug__: self._log(3, 'state_change_pending.release')
+
+
+ def _request_pop(self, name, data):
+
+ self.commands_lock.acquire()
+ rqb = self.tagged_commands.pop(name)
+ if not self.tagged_commands:
+ need_event = True
+ else:
+ need_event = False
+ self.commands_lock.release()
+
+ if __debug__: self._log(4, '_request_pop(%s, %r) [%d] = %s' % (name, data, len(self.tagged_commands), rqb.tag))
+ rqb.deliver(data)
+
+ if need_event:
+ if __debug__: self._log(3, 'state_change_free.set')
+ self.state_change_free.set()
+
+
+ def _request_push(self, tag=None, name=None, **kw):
+
+ self.commands_lock.acquire()
+ rqb = Request(self, name=name, **kw)
+ if tag is None:
+ tag = rqb.tag
+ self.tagged_commands[tag] = rqb
+ self.commands_lock.release()
+ if __debug__: self._log(4, '_request_push(%s, %s, %s) = %s' % (tag, name, repr(kw), rqb.tag))
+ return rqb
+
+
+ def _simple_command(self, name, *args, **kw):
+
+ if 'callback' in kw:
+ # Note: old calling sequence for back-compat with python <2.6
+ self._command(name, callback=self._command_completer, cb_arg=kw, cb_self=True, *args)
+ return (None, None)
+ return self._command_complete(self._command(name, *args), kw)
+
+
+ def _untagged_response(self, typ, dat, name):
+
+ if typ == 'NO':
+ return typ, dat
+ data = self._get_untagged_response(name)
+ if not data:
+ return typ, [None]
+ while True:
+ dat = self._get_untagged_response(name)
+ if not dat:
+ break
+ data += dat
+ if __debug__: self._log(4, '_untagged_response(%s, ?, %s) => %.80r' % (typ, name, data))
+ return typ, data
+
+
+
+ # Threads
+
+
+ def _close_threads(self):
+
+ if __debug__: self._log(1, '_close_threads')
+
+ self.ouq.put(None)
+ self.wrth.join()
+
+ if __debug__: self._log(1, 'call shutdown')
+
+ self.shutdown()
+
+ self.rdth.join()
+ self.inth.join()
+
+
+ def _handler(self):
+
+ resp_timeout = self.resp_timeout
+
+ threading.currentThread().setName(self.identifier + 'handler')
+
+ time.sleep(0.1) # Don't start handling before main thread ready
+
+ if __debug__: self._log(1, 'starting')
+
+ typ, val = self.abort, 'connection terminated'
+
+ while not self.Terminate:
+
+ self.idle_lock.acquire()
+ if self.idle_timeout is not None:
+ timeout = self.idle_timeout - time.time()
+ if timeout <= 0:
+ timeout = 1
+ if __debug__:
+ if self.idle_rqb is not None:
+ self._log(5, 'server IDLING, timeout=%.2f' % timeout)
+ else:
+ timeout = resp_timeout
+ self.idle_lock.release()
+
+ try:
+ line = self.inq.get(True, timeout)
+ except queue.Empty:
+ if self.idle_rqb is None:
+ if resp_timeout is not None and self.tagged_commands:
+ if __debug__: self._log(1, 'response timeout')
+ typ, val = self.abort, 'no response after %s secs' % resp_timeout
+ break
+ continue
+ if self.idle_timeout > time.time():
+ continue
+ if __debug__: self._log(2, 'server IDLE timedout')
+ line = IDLE_TIMEOUT_RESPONSE
+
+ if line is None:
+ if __debug__: self._log(1, 'inq None - terminating')
+ break
+
+ if not isinstance(line, bytes):
+ typ, val = line
+ break
+
+ try:
+ self._put_response(line)
+ except:
+ typ, val = self.error, 'program error: %s - %s' % sys.exc_info()[:2]
+ break
+
+ self.Terminate = True
+
+ if __debug__: self._log(1, 'terminating: %s' % repr(val))
+
+ while not self.ouq.empty():
+ try:
+ qel = self.ouq.get_nowait()
+ if qel is not None:
+ qel.abort(typ, val)
+ except queue.Empty:
+ break
+ self.ouq.put(None)
+
+ self.commands_lock.acquire()
+ for name in list(self.tagged_commands.keys()):
+ rqb = self.tagged_commands.pop(name)
+ rqb.abort(typ, val)
+ self.state_change_free.set()
+ self.commands_lock.release()
+ if __debug__: self._log(3, 'state_change_free.set')
+
+ if __debug__: self._log(1, 'finished')
+
+
+ if hasattr(select_module, "poll"):
+
+ def _reader(self):
+
+ threading.currentThread().setName(self.identifier + 'reader')
+
+ if __debug__: self._log(1, 'starting using poll')
+
+ def poll_error(state):
+ PollErrors = {
+ select.POLLERR: 'Error',
+ select.POLLHUP: 'Hang up',
+ select.POLLNVAL: 'Invalid request: descriptor not open',
+ }
+ return ' '.join([PollErrors[s] for s in PollErrors.keys() if (s & state)])
+
+ line_part = b''
+
+ poll = select.poll()
+
+ poll.register(self.read_fd, select.POLLIN)
+
+ rxzero = 0
+ terminate = False
+ read_poll_timeout = self.read_poll_timeout * 1000 # poll() timeout is in millisecs
+
+ while not (terminate or self.Terminate):
+ if self.state == LOGOUT:
+ timeout = 10
+ else:
+ timeout = read_poll_timeout
+ try:
+ r = poll.poll(timeout)
+ if __debug__: self._log(5, 'poll => %s' % repr(r))
+ if not r:
+ continue # Timeout
+
+ fd,state = r[0]
+
+ if state & select.POLLIN:
+ data = self.read(self.read_size) # Drain ssl buffer if present
+ start = 0
+ dlen = len(data)
+ if __debug__: self._log(5, 'rcvd %s' % dlen)
+ if dlen == 0:
+ rxzero += 1
+ if rxzero > 5:
+ raise IOError("Too many read 0")
+ time.sleep(0.1)
+ continue # Try again
+ rxzero = 0
+
+ while True:
+ stop = data.find(b'\n', start)
+ if stop < 0:
+ line_part += data[start:]
+ break
+ stop += 1
+ line_part, start, line = \
+ b'', stop, line_part + data[start:stop]
+ if __debug__: self._log(4, '< %r' % line)
+ self.inq.put(line)
+ if self.TerminateReader:
+ terminate = True
+
+ if state & ~(select.POLLIN):
+ raise IOError(poll_error(state))
+ except:
+ reason = 'socket error: %s - %s' % sys.exc_info()[:2]
+ if __debug__:
+ if not self.Terminate:
+ self._print_log()
+ if self.debug: self.debug += 4 # Output all
+ self._log(1, reason)
+ self.inq.put((self.abort, reason))
+ break
+
+ poll.unregister(self.read_fd)
+
+ if __debug__: self._log(1, 'finished')
+
+ else:
+
+ # No "poll" - use select()
+
+ def _reader(self):
+
+ threading.currentThread().setName(self.identifier + 'reader')
+
+ if __debug__: self._log(1, 'starting using select')
+
+ line_part = b''
+
+ rxzero = 0
+ terminate = False
+
+ while not (terminate or self.Terminate):
+ if self.state == LOGOUT:
+ timeout = 1
+ else:
+ timeout = self.read_poll_timeout
+ try:
+ r,w,e = select.select([self.read_fd], [], [], timeout)
+ if __debug__: self._log(5, 'select => %s, %s, %s' % (r,w,e))
+ if not r: # Timeout
+ continue
+
+ data = self.read(self.read_size) # Drain ssl buffer if present
+ start = 0
+ dlen = len(data)
+ if __debug__: self._log(5, 'rcvd %s' % dlen)
+ if dlen == 0:
+ rxzero += 1
+ if rxzero > 5:
+ raise IOError("Too many read 0")
+ time.sleep(0.1)
+ continue # Try again
+ rxzero = 0
+
+ while True:
+ stop = data.find(b'\n', start)
+ if stop < 0:
+ line_part += data[start:]
+ break
+ stop += 1
+ line_part, start, line = \
+ b'', stop, (line_part + data[start:stop]).decode(errors='ignore')
+ if __debug__: self._log(4, '< %r' % line)
+ self.inq.put(line)
+ if self.TerminateReader:
+ terminate = True
+ except:
+ reason = 'socket error: %s - %s' % sys.exc_info()[:2]
+ if __debug__:
+ if not self.Terminate:
+ self._print_log()
+ if self.debug: self.debug += 4 # Output all
+ self._log(1, reason)
+ self.inq.put((self.abort, reason))
+ break
+
+ if __debug__: self._log(1, 'finished')
+
+
+ def _writer(self):
+
+ threading.currentThread().setName(self.identifier + 'writer')
+
+ if __debug__: self._log(1, 'starting')
+
+ reason = 'Terminated'
+
+ while not self.Terminate:
+ rqb = self.ouq.get()
+ if rqb is None:
+ break # Outq flushed
+
+ try:
+ self.send(rqb.data)
+ if __debug__: self._log(4, '> %r' % rqb.data)
+ except:
+ reason = 'socket error: %s - %s' % sys.exc_info()[:2]
+ if __debug__:
+ if not self.Terminate:
+ self._print_log()
+ if self.debug: self.debug += 4 # Output all
+ self._log(1, reason)
+ rqb.abort(self.abort, reason)
+ break
+
+ self.inq.put((self.abort, reason))
+
+ if __debug__: self._log(1, 'finished')
+
+
+
+ # Debugging
+
+
+ if __debug__:
+
+ def _init_debug(self, debug=None, debug_file=None, debug_buf_lvl=None):
+ self.debug_lock = threading.Lock()
+
+ self.debug = self._choose_nonull_or_dflt(0, debug)
+ self.debug_file = self._choose_nonull_or_dflt(sys.stderr, debug_file)
+ self.debug_buf_lvl = self._choose_nonull_or_dflt(DFLT_DEBUG_BUF_LVL, debug_buf_lvl)
+
+ self._cmd_log_len = 20
+ self._cmd_log_idx = 0
+ self._cmd_log = {} # Last `_cmd_log_len' interactions
+ if self.debug:
+ self._mesg('imaplib2 version %s' % __version__)
+ self._mesg('imaplib2 debug level %s, buffer level %s' % (self.debug, self.debug_buf_lvl))
+
+
+ def _dump_ur(self, lvl):
+ if lvl > self.debug:
+ return
+
+ l = self.untagged_responses # NB: bytes array
+ if not l:
+ return
+
+ t = '\n\t\t'
+ l = ['%s: "%s"' % (x[0], x[1][0] and b'" "'.join(x[1]) or '') for x in l]
+ self.debug_lock.acquire()
+ self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
+ self.debug_lock.release()
+
+
+ def _log(self, lvl, line):
+ if lvl > self.debug:
+ return
+
+ if line[-2:] == CRLF:
+ line = line[:-2] + '\\r\\n'
+
+ tn = threading.currentThread().getName()
+
+ if lvl <= 1 or self.debug > self.debug_buf_lvl:
+ self.debug_lock.acquire()
+ self._mesg(line, tn)
+ self.debug_lock.release()
+ if lvl != 1:
+ return
+
+ # Keep log of last `_cmd_log_len' interactions for debugging.
+ self.debug_lock.acquire()
+ self._cmd_log[self._cmd_log_idx] = (line, tn, time.time())
+ self._cmd_log_idx += 1
+ if self._cmd_log_idx >= self._cmd_log_len:
+ self._cmd_log_idx = 0
+ self.debug_lock.release()
+
+
+ def _mesg(self, s, tn=None, secs=None):
+ if secs is None:
+ secs = time.time()
+ if tn is None:
+ tn = threading.currentThread().getName()
+ tm = time.strftime('%M:%S', time.localtime(secs))
+ try:
+ self.debug_file.write(' %s.%02d %s %s\n' % (tm, (secs*100)%100, tn, s))
+ self.debug_file.flush()
+ finally:
+ pass
+
+
+ def _print_log(self):
+ self.debug_lock.acquire()
+ i, n = self._cmd_log_idx, self._cmd_log_len
+ if n: self._mesg('last %d log messages:' % n)
+ while n:
+ try:
+ self._mesg(*self._cmd_log[i])
+ except:
+ pass
+ i += 1
+ if i >= self._cmd_log_len:
+ i = 0
+ n -= 1
+ self.debug_lock.release()
+
+
+
+class IMAP4_SSL(IMAP4):
+
+ """IMAP4 client class over SSL connection
+
+ Instantiate with:
+ IMAP4_SSL(host=None, port=None, keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None, tls_level="tls_compat")
+
+ host - host's name (default: localhost);
+ port - port number (default: standard IMAP4 SSL port);
+ keyfile - PEM formatted file that contains your private key (default: None);
+ certfile - PEM formatted certificate chain file (default: None);
+ ca_certs - PEM formatted certificate chain file used to validate server certificates (default: None);
+ cert_verify_cb - function to verify authenticity of server certificates (default: None);
+ ssl_version - SSL version to use (default: "ssl23", choose from: "tls1","ssl3","ssl23");
+ debug - debug level (default: 0 - no debug);
+ debug_file - debug stream (default: sys.stderr);
+ identifier - thread identifier prefix (default: host);
+ timeout - timeout in seconds when expecting a command response.
+ debug_buf_lvl - debug level at which buffering is turned off.
+ tls_level - TLS security level (default: "tls_compat").
+
+ The recognized values for tls_level are:
+ tls_secure: accept only TLS protocols recognized as "secure"
+ tls_no_ssl: disable SSLv2 and SSLv3 support
+ tls_compat: accept all SSL/TLS versions
+
+ For more documentation see the docstring of the parent class IMAP4.
+ """
+
+
+ def __init__(self, host=None, port=None, keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None, tls_level=TLS_COMPAT):
+ self.keyfile = keyfile
+ self.certfile = certfile
+ self.ca_certs = ca_certs
+ self.cert_verify_cb = cert_verify_cb
+ self.ssl_version = ssl_version
+ self.tls_level = tls_level
+ IMAP4.__init__(self, host, port, debug, debug_file, identifier, timeout, debug_buf_lvl)
+
+
+ def open(self, host=None, port=None):
+ """open(host=None, port=None)
+ Setup secure connection to remote server on "host:port"
+ (default: localhost:standard IMAP4 SSL port).
+ This connection will be used by the routines:
+ read, send, shutdown, socket, ssl."""
+
+ self.host = self._choose_nonull_or_dflt('', host)
+ self.port = self._choose_nonull_or_dflt(IMAP4_SSL_PORT, port)
+ self.sock = self.open_socket()
+ self.ssl_wrap_socket()
+
+
+ def read(self, size):
+ """data = read(size)
+ Read at most 'size' bytes from remote."""
+
+ if self.decompressor is None:
+ return self.sock.read(size)
+
+ if self.decompressor.unconsumed_tail:
+ data = self.decompressor.unconsumed_tail
+ else:
+ data = self.sock.read(READ_SIZE)
+
+ return self.decompressor.decompress(data, size)
+
+
+ def send(self, data):
+ """send(data)
+ Send 'data' to remote."""
+
+ if self.compressor is not None:
+ data = self.compressor.compress(data)
+ data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
+
+ if hasattr(self.sock, "sendall"):
+ self.sock.sendall(data)
+ else:
+ dlen = len(data)
+ while dlen > 0:
+ sent = self.sock.write(data)
+ if sent == dlen:
+ break # avoid copy
+ data = data[sent:]
+ dlen = dlen - sent
+
+
+ def ssl(self):
+ """ssl = ssl()
+ Return ssl instance used to communicate with the IMAP4 server."""
+
+ return self.sock
+
+
+
+class IMAP4_stream(IMAP4):
+
+ """IMAP4 client class over a stream
+
+ Instantiate with:
+ IMAP4_stream(command, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None)
+
+ command - string that can be passed to subprocess.Popen();
+ debug - debug level (default: 0 - no debug);
+ debug_file - debug stream (default: sys.stderr);
+ identifier - thread identifier prefix (default: host);
+ timeout - timeout in seconds when expecting a command response.
+ debug_buf_lvl - debug level at which buffering is turned off.
+
+ For more documentation see the docstring of the parent class IMAP4.
+ """
+
+
+ def __init__(self, command, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None):
+ self.command = command
+ self.host = command
+ self.port = None
+ self.sock = None
+ self.writefile, self.readfile = None, None
+ self.read_fd = None
+ IMAP4.__init__(self, None, None, debug, debug_file, identifier, timeout, debug_buf_lvl)
+
+
+ def open(self, host=None, port=None):
+ """open(host=None, port=None)
+ Setup a stream connection via 'self.command'.
+ This connection will be used by the routines:
+ read, send, shutdown, socket."""
+
+ from subprocess import Popen, PIPE
+ from io import DEFAULT_BUFFER_SIZE
+
+ if __debug__: self._log(0, 'opening stream from command "%s"' % self.command)
+ self._P = Popen(self.command, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True, bufsize=DEFAULT_BUFFER_SIZE)
+ self.writefile, self.readfile = self._P.stdin, self._P.stdout
+ self.read_fd = self.readfile.fileno()
+
+
+ def read(self, size):
+ """Read 'size' bytes from remote."""
+
+ if self.decompressor is None:
+ return os.read(self.read_fd, size)
+
+ if self.decompressor.unconsumed_tail:
+ data = self.decompressor.unconsumed_tail
+ else:
+ data = os.read(self.read_fd, READ_SIZE)
+
+ return self.decompressor.decompress(data, size)
+
+
+ def send(self, data):
+ """Send data to remote."""
+
+ if self.compressor is not None:
+ data = self.compressor.compress(data)
+ data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
+
+ self.writefile.write(data)
+ self.writefile.flush()
+
+
+ def shutdown(self):
+ """Close I/O established in "open"."""
+
+ self.readfile.close()
+ self.writefile.close()
+ self._P.wait()
+
+
+class _Authenticator(object):
+
+ """Private class to provide en/de-coding
+ for base64 authentication conversation."""
+
+ def __init__(self, mechinst):
+ self.mech = mechinst # Callable object to provide/process data
+
+ def process(self, data, rqb):
+ ret = self.mech(self.decode(data))
+ if ret is None:
+ return b'*' # Abort conversation
+ return self.encode(ret)
+
+ def encode(self, inp):
+ #
+ # Invoke binascii.b2a_base64 iteratively with
+ # short even length buffers, strip the trailing
+ # line feed from the result and append. "Even"
+ # means a number that factors to both 6 and 8,
+ # so when it gets to the end of the 8-bit input
+ # there's no partial 6-bit output.
+ #
+ oup = b''
+ if isinstance(inp, str):
+ inp = inp.encode('utf-8')
+ while inp:
+ if len(inp) > 48:
+ t = inp[:48]
+ inp = inp[48:]
+ else:
+ t = inp
+ inp = b''
+ e = binascii.b2a_base64(t)
+ if e:
+ oup = oup + e[:-1]
+ return oup
+
+ def decode(self, inp):
+ if not inp:
+ return b''
+ return binascii.a2b_base64(inp)
+
+
+
+
+class _IdleCont(object):
+
+ """When process is called, server is in IDLE state
+ and will send asynchronous changes."""
+
+ def __init__(self, parent, timeout):
+ self.parent = parent
+ self.timeout = parent._choose_nonull_or_dflt(IDLE_TIMEOUT, timeout)
+ self.parent.idle_timeout = self.timeout + time.time()
+
+ def process(self, data, rqb):
+ self.parent.idle_lock.acquire()
+ self.parent.idle_rqb = rqb
+ self.parent.idle_timeout = self.timeout + time.time()
+ self.parent.idle_lock.release()
+ if __debug__: self.parent._log(2, 'server IDLE started, timeout in %.2f secs' % self.timeout)
+ return None
+
+
+
+MonthNames = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+
+Mon2num = {s.encode():n+1 for n, s in enumerate(MonthNames[1:])}
+
+InternalDate = re.compile(br'.*INTERNALDATE "'
+ br'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
+ br' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
+ br' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
+ br'"')
+
+
+def Internaldate2Time(resp):
+
+ """time_tuple = Internaldate2Time(resp)
+
+ Parse an IMAP4 INTERNALDATE string.
+
+ Return corresponding local time. The return value is a
+ time.struct_time instance or None if the string has wrong format."""
+
+ mo = InternalDate.match(resp)
+ if not mo:
+ return None
+
+ mon = Mon2num[mo.group('mon')]
+ zonen = mo.group('zonen')
+
+ day = int(mo.group('day'))
+ year = int(mo.group('year'))
+ hour = int(mo.group('hour'))
+ min = int(mo.group('min'))
+ sec = int(mo.group('sec'))
+ zoneh = int(mo.group('zoneh'))
+ zonem = int(mo.group('zonem'))
+
+ # INTERNALDATE timezone must be subtracted to get UT
+
+ zone = (zoneh*60 + zonem)*60
+ if zonen == b'-':
+ zone = -zone
+
+ tt = (year, mon, day, hour, min, sec, -1, -1, -1)
+ return time.localtime(calendar.timegm(tt) - zone)
+
+Internaldate2tuple = Internaldate2Time # (Backward compatible)
+
+
+
+def Time2Internaldate(date_time):
+
+ """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time)
+
+ Convert 'date_time' to IMAP4 INTERNALDATE representation.
+
+ The date_time argument can be a number (int or float) representing
+ seconds since epoch (as returned by time.time()), a 9-tuple
+ representing local time, an instance of time.struct_time (as
+ returned by time.localtime()), an aware datetime instance or a
+ double-quoted string. In the last case, it is assumed to already
+ be in the correct format."""
+
+ from datetime import datetime, timezone, timedelta
+
+ if isinstance(date_time, (int, float)):
+ tt = time.localtime(date_time)
+ elif isinstance(date_time, tuple):
+ try:
+ gmtoff = date_time.tm_gmtoff
+ except AttributeError:
+ if time.daylight:
+ dst = date_time[8]
+ if dst == -1:
+ dst = time.localtime(time.mktime(date_time))[8]
+ gmtoff = -(time.timezone, time.altzone)[dst]
+ else:
+ gmtoff = -time.timezone
+ delta = timedelta(seconds=gmtoff)
+ dt = datetime(*date_time[:6], tzinfo=timezone(delta))
+ elif isinstance(date_time, datetime):
+ if date_time.tzinfo is None:
+ raise ValueError("date_time must be aware")
+ dt = date_time
+ elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
+ return date_time # Assume in correct format
+ else:
+ raise ValueError("date_time not of a known type")
+
+ fmt = '"%d-{}-%Y %H:%M:%S %z"'.format(MonthNames[dt.month])
+ return dt.strftime(fmt)
+
+
+
+FLAGS_cre = re.compile(br'.*FLAGS \((?P<flags>[^\)]*)\)')
+
+def ParseFlags(resp):
+
+ """('flag', ...) = ParseFlags(line)
+ Convert IMAP4 flags response to python tuple."""
+
+ mo = FLAGS_cre.match(resp)
+ if not mo:
+ return ()
+
+ return tuple(mo.group('flags').split())
+
+
+
+if __name__ == '__main__':
+
+ # To test: invoke either as 'python imaplib2.py [IMAP4_server_hostname]',
+ # or as 'python imaplib2.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
+ # or as 'python imaplib2.py -l keyfile[:certfile]|: [IMAP4_SSL_server_hostname]'
+ #
+ # Option "-d <level>" turns on debugging (use "-d 5" for everything)
+ # Option "-i" tests that IDLE is interruptible
+ # Option "-p <port>" allows alternate ports
+
+ if not __debug__:
+ raise ValueError('Please run without -O')
+
+ import getopt, getpass
+
+ try:
+ optlist, args = getopt.getopt(sys.argv[1:], 'd:il:s:p:')
+ except getopt.error as val:
+ optlist, args = (), ()
+
+ debug, debug_buf_lvl, port, stream_command, keyfile, certfile, idle_intr = (None,)*7
+ for opt,val in optlist:
+ if opt == '-d':
+ debug = int(val)
+ debug_buf_lvl = debug - 1
+ elif opt == '-i':
+ idle_intr = 1
+ elif opt == '-l':
+ try:
+ keyfile,certfile = val.split(':')
+ except ValueError:
+ keyfile,certfile = val,val
+ elif opt == '-p':
+ port = int(val)
+ elif opt == '-s':
+ stream_command = val
+ if not args: args = (stream_command,)
+
+ if not args: args = ('',)
+ if not port: port = (keyfile is not None) and IMAP4_SSL_PORT or IMAP4_PORT
+
+ host = args[0]
+
+ USER = getpass.getuser()
+
+ data = open(os.path.exists("test.data") and "test.data" or __file__).read(1000)
+ test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)s%(data)s' \
+ % {'user':USER, 'lf':'\n', 'data':data}
+
+ test_seq1 = [
+ ('list', ('""', '""')),
+ ('list', ('""', '"%"')),
+ ('create', ('imaplib2_test0',)),
+ ('rename', ('imaplib2_test0', 'imaplib2_test1')),
+ ('CREATE', ('imaplib2_test2',)),
+ ('append', ('imaplib2_test2', None, None, test_mesg)),
+ ('list', ('""', '"imaplib2_test%"')),
+ ('select', ('imaplib2_test2',)),
+ ('search', (None, 'SUBJECT', '"IMAP4 test"')),
+ ('fetch', ('1:*', '(FLAGS INTERNALDATE RFC822)')),
+ ('store', ('1', 'FLAGS', '(\Deleted)')),
+ ('namespace', ()),
+ ('expunge', ()),
+ ('recent', ()),
+ ('close', ()),
+ ]
+
+ test_seq2 = (
+ ('select', ()),
+ ('response', ('UIDVALIDITY',)),
+ ('response', ('EXISTS',)),
+ ('append', (None, None, None, test_mesg)),
+ ('examine', ()),
+ ('select', ()),
+ ('fetch', ('1:*', '(FLAGS UID)')),
+ ('examine', ()),
+ ('select', ()),
+ ('uid', ('SEARCH', 'SUBJECT', '"IMAP4 test"')),
+ ('uid', ('SEARCH', 'ALL')),
+ ('uid', ('THREAD', 'references', 'UTF-8', '(SEEN)')),
+ ('recent', ()),
+ )
+
+
+ AsyncError, M = None, None
+
+ def responder(cb_arg_list):
+ response, cb_arg, error = cb_arg_list
+ global AsyncError
+ cmd, args = cb_arg
+ if error is not None:
+ AsyncError = error
+ M._log(0, '[cb] ERROR %s %.100s => %s' % (cmd, args, error))
+ return
+ typ, dat = response
+ M._log(0, '[cb] %s %.100s => %s %.100s' % (cmd, args, typ, dat))
+ if typ == 'NO':
+ AsyncError = (Exception, dat[0])
+
+ def run(cmd, args, cb=True):
+ if AsyncError:
+ M._log(1, 'AsyncError %s' % repr(AsyncError))
+ M.logout()
+ typ, val = AsyncError
+ raise typ(val)
+ if not M.debug: M._log(0, '%s %.100s' % (cmd, args))
+ try:
+ if cb:
+ typ, dat = getattr(M, cmd)(callback=responder, cb_arg=(cmd, args), *args)
+ M._log(1, '%s %.100s => %s %.100s' % (cmd, args, typ, dat))
+ else:
+ typ, dat = getattr(M, cmd)(*args)
+ M._log(1, '%s %.100s => %s %.100s' % (cmd, args, typ, dat))
+ except:
+ M._log(1, '%s - %s' % sys.exc_info()[:2])
+ M.logout()
+ raise
+ if typ == 'NO':
+ M._log(1, 'NO')
+ M.logout()
+ raise Exception(dat[0])
+ return dat
+
+ try:
+ threading.currentThread().setName('main')
+
+ if keyfile is not None:
+ if not keyfile: keyfile = None
+ if not certfile: certfile = None
+ M = IMAP4_SSL(host=host, port=port, keyfile=keyfile, certfile=certfile, ssl_version="tls1", debug=debug, identifier='', timeout=10, debug_buf_lvl=debug_buf_lvl, tls_level="tls_no_ssl")
+ elif stream_command:
+ M = IMAP4_stream(stream_command, debug=debug, identifier='', timeout=10, debug_buf_lvl=debug_buf_lvl)
+ else:
+ M = IMAP4(host=host, port=port, debug=debug, identifier='', timeout=10, debug_buf_lvl=debug_buf_lvl)
+ if M.state != 'AUTH': # Login needed
+ PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
+ test_seq1.insert(0, ('login', (USER, PASSWD)))
+ M._log(0, 'PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
+ if 'COMPRESS=DEFLATE' in M.capabilities:
+ M.enable_compression()
+
+ for cmd,args in test_seq1:
+ run(cmd, args)
+
+ for ml in run('list', ('""', '"imaplib2_test%"'), cb=False):
+ mo = re.match(br'.*"([^"]+)"$', ml)
+ if mo: path = mo.group(1)
+ else: path = ml.split()[-1]
+ run('delete', (path,))
+
+ if 'ID' in M.capabilities:
+ run('id', ())
+ run('id', ("(name imaplib2)",))
+ run('id', ("version", __version__, "os", os.uname()[0]))
+
+ for cmd,args in test_seq2:
+ if (cmd,args) != ('uid', ('SEARCH', 'SUBJECT', 'IMAP4 test')):
+ run(cmd, args)
+ continue
+
+ dat = run(cmd, args, cb=False)
+ uid = dat[-1].split()
+ if not uid: continue
+ run('uid', ('FETCH', uid[-1],
+ '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
+ run('uid', ('STORE', uid[-1], 'FLAGS', '(\Deleted)'))
+ run('expunge', ())
+
+ if 'IDLE' in M.capabilities:
+ run('idle', (2,), cb=False)
+ run('idle', (99,)) # Asynchronous, to test interruption of 'idle' by 'noop'
+ time.sleep(1)
+ run('noop', (), cb=False)
+
+ run('append', (None, None, None, test_mesg), cb=False)
+ num = run('search', (None, 'ALL'), cb=False)[0].split()[0]
+ dat = run('fetch', (num, '(FLAGS INTERNALDATE RFC822)'), cb=False)
+ M._mesg('fetch %s => %s' % (num, repr(dat)))
+ run('idle', (2,))
+ run('store', (num, '-FLAGS', '(\Seen)'), cb=False),
+ dat = run('fetch', (num, '(FLAGS INTERNALDATE RFC822)'), cb=False)
+ M._mesg('fetch %s => %s' % (num, repr(dat)))
+ run('uid', ('STORE', num, 'FLAGS', '(\Deleted)'))
+ run('expunge', ())
+ if idle_intr:
+ M._mesg('HIT CTRL-C to interrupt IDLE')
+ try:
+ run('idle', (99,), cb=False) # Synchronous, to test interruption of 'idle' by INTR
+ except KeyboardInterrupt:
+ M._mesg('Thanks!')
+ M._mesg('')
+ raise
+ elif idle_intr:
+ M._mesg('chosen server does not report IDLE capability')
+
+ run('logout', (), cb=False)
+
+ if debug:
+ M._mesg('')
+ M._print_log()
+ M._mesg('')
+ M._mesg('unused untagged responses in order, most recent last:')
+ for typ,dat in M.pop_untagged_responses(): M._mesg('\t%s %s' % (typ, dat))
+
+ print('All tests OK.')
+
+ except:
+ if not idle_intr or M is None or not 'IDLE' in M.capabilities:
+ print('Tests failed.')
+
+ if not debug:
+ print('''
+If you would like to see debugging output,
+try: %s -d5
+''' % sys.argv[0])
+
+ raise