Skip to content

Commit

Permalink
Remove old code. Use the new rule parser everywhere.
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomi Richards committed Jul 5, 2015
1 parent 32231f2 commit cbcb79f
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 126 deletions.
25 changes: 4 additions & 21 deletions gmailfilter/_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,10 @@ def run():
args = configure_argument_parser()
log_level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(level=log_level, stream=sys.stdout)
if not args.dev:
run_old_filter()
else:
run_new_filter()


def run_old_filter():
"""Run the old, pre v1 filter agent. This will get deleted soon."""
rules_path = get_filter_file_or_raise()

with open(rules_path) as f:
code = compile(f.read(), rules_path, 'exec')
exec(code, get_rule_globals_dict())
if args.dev:
# run_old_filter()
print("The --dev option is deprecated. The New hotness is everywhere now.")
run_new_filter()


def run_new_filter():
Expand Down Expand Up @@ -75,14 +66,6 @@ def configure_argument_parser():
return parser.parse_args()


def get_filter_file_or_raise():
path = os.path.expanduser('~/.config/gmailfilter/rules')
if not os.path.exists(path):
raise IOError("Rules file %r does not exist" % path)
# TODO: Check for readability?
return path


def get_rule_globals_dict():
rule_globals = {
'IMAPServer': IMAPServer
Expand Down
105 changes: 0 additions & 105 deletions gmailfilter/_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,108 +12,6 @@
from gmailfilter._message import EmailMessage as Message


# TODO: Accept config from command line, encapsulate in a dict and pass
# in to the connection class.

class IMAPServer(object):

"""The old, pre v1 server object. Some of this can be re-used, but most
will be deleted."""

def __init__(self, server=None, username=None, password=None, port=993, ssl=True):
if (
server is None or
username is None or
password is None
):
raise ValueError("server and username and password cannot be None")


self._client = IMAPClient(
host=server,
port=port,
use_uid=False,
ssl=ssl
)
# self._client.debug = True
self._client.login(
username,
password,
)

def get_messages(self):
"""A generator that yields Message instances, one for every message
in the users inbox.
"""
# TODO - perahps the user wants to filter a different folder?
mbox_details = self._client.select_folder("INBOX")
total_messages = mbox_details['EXISTS']
logging.info("Scanning inbox, found %d messages" % total_messages)
# TODO: Research best chunk size - maybe let user tweak this from
# config file?:
i = 0
with self.use_sequence():
for chunk in sequence_chunk(total_messages, optimal_chunk_size(1000)):
logging.info("Fetching: " + chunk)
data = self._client.fetch(
chunk,
['UID', 'BODY.PEEK[HEADER]', 'INTERNALDATE', 'FLAGS']
)
for msg_seq in data:
logging.debug("Processing %d / %d", i, total_messages)
proxy = MessageConnectionProxy(self, data[msg_seq])
yield Message(proxy)
i += 1
self._do_chunk_cleanup()

def move_message(self, message, folder):
"""Move a message to a folder, creating the folder if it doesn't exist.
:param message: An instance of gmailfilter.Message
:param folder: A string descriving the folder.
"""
# TODO: optimise this by trying the copy, and if we get 'NO' with
# 'TRYCREATE' then, and only then try and create the folder. Removes the
# overhead of the existance check for every message,
if not self._client.folder_exists(folder):
status = self._client.create_folder(folder)
assert status.lower() == "success", "Unable to create folder %s" % folder
with self.use_uid():
self._client.copy(str(message.uid()), folder)
self.delete_message(message)

def delete_message(self, message):
with self.use_uid():
uid_string = str(message.uid())
logging.info("Deleting %s" % uid_string)
self._client.delete_messages(uid_string)

def _do_chunk_cleanup(self):
# self._client.expunge()
pass


@contextmanager
def use_uid(self):
old = self._client.use_uid
self._client.use_uid = True
try:
yield
finally:
self._client.use_uid = old

@contextmanager
def use_sequence(self):
old = self._client.use_uid
self._client.use_uid = False
try:
yield
finally:
self._client.use_uid = old


def sequence_chunk(num_messages, chunk_size):
assert chunk_size >= 1
start = 1
Expand Down Expand Up @@ -174,9 +72,6 @@ def get_message_part(self, part_name):
return self._data[retrieve_key]


##############################################################################
# v2 code below here:

class IMAPConnection(object):

def __init__(self, server_info):
Expand Down
2 changes: 2 additions & 0 deletions gmailfilter/tests/test_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,5 @@ class MessageAgeTests(TestCase, TestFactoryMixin):

def test_newer_message(self):
now = datetime.datetime(2015, 7, 5)
# TODO: Figure out how best to mock datetime.now() in the actual test
# and then complete this test.

0 comments on commit cbcb79f

Please sign in to comment.