diff --git a/gui/resources.py b/gui/resources.py new file mode 100644 index 0000000..96b92a1 --- /dev/null +++ b/gui/resources.py @@ -0,0 +1,40 @@ +# Copyright (C) 2013 Luis Pedro Coelho +# This file is part of rbit mail. +from __future__ import print_function + +from contextlib import contextmanager + +class imap_manager(object): + def __init__(self): + from gevent.coros import Semaphore + self.client = None + self.sem = Semaphore(1) + self.count = 0 + + def close(self, current): + import gevent + gevent.sleep(360) + self.sem.acquire() + if self.count == current: + self.client.close() + self.client = None + imap_sem.release() + + @contextmanager + def get(self): + import gevent + self.count += 1 + self.sem.acquire() + self.count += 1 + if self.client is None: + from rbit import config + from rbit import backend + from rbit import imap + cfg = config.Config('config', backend.create_session) + self.client = imap.IMAPClient.from_config(cfg) + yield self.client + self.sem.release() + gevent.spawn(lambda : self.close(self.count)) + + + diff --git a/gui/tasks.py b/gui/tasks.py index f4b64a4..74d1bef 100644 --- a/gui/tasks.py +++ b/gui/tasks.py @@ -1,4 +1,4 @@ -# Copyright (C) 2012 Luis Pedro Coelho +# Copyright (C) 2012-2013 Luis Pedro Coelho # This file is part of rbit mail. from __future__ import print_function @@ -7,6 +7,17 @@ from rbit import signals +_imap_manager = None +def get_imap(): + # By importing only inside the function, we avoid having to import at + # programme start up + from resources import imap_manager + global _imap_manager + if _imap_manager is None: + _imap_manager = imap_manager() + return _imap_manager.get() + + def run_from_queue(group, q): from gevent import monkey # thread needs to be left alone as Qt handles those @@ -121,15 +132,10 @@ def __init__(self, parent, message, target): self.target = target def _perform(self): - from rbit import config - from rbit import backend - from rbit import imap - cfg = config.Config('config', backend.create_session) - client = imap.IMAPClient.from_config(cfg) - client.select_folder(self.folder) - client.move_messages([self.uid], self.target) - client.expunge() - client.close() + with get_imap() as client: + client.select_folder(self.folder) + client.move_messages([self.uid], self.target) + client.expunge() class TrashMessage(MoveMessage): def __init__(self, parent, message):