2015-12-26 13:21:33 +00:00
|
|
|
import datetime
|
2015-12-20 19:23:33 +00:00
|
|
|
import os
|
2015-12-21 02:44:24 +00:00
|
|
|
import time
|
2015-12-20 19:23:33 +00:00
|
|
|
|
|
|
|
|
from django.conf import settings
|
2016-01-14 19:47:57 +00:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
2015-12-20 19:23:33 +00:00
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
from ...consumer import Consumer, ConsumerError
|
|
|
|
|
from ...mail import MailFetcher, MailFetcherError
|
2016-01-23 02:33:29 +00:00
|
|
|
|
|
|
|
|
|
2016-02-14 16:09:52 +00:00
|
|
|
class Command(BaseCommand):
|
2015-12-20 19:23:33 +00:00
|
|
|
"""
|
2016-02-06 17:05:36 +00:00
|
|
|
On every iteration of an infinite loop, consume what we can from the
|
|
|
|
|
consumption directory, and fetch any mail available.
|
2015-12-20 19:23:33 +00:00
|
|
|
"""
|
|
|
|
|
|
2015-12-26 13:21:33 +00:00
|
|
|
LOOP_TIME = 10 # Seconds
|
2016-01-30 01:18:52 +00:00
|
|
|
MAIL_DELTA = datetime.timedelta(minutes=10)
|
2015-12-26 13:21:33 +00:00
|
|
|
|
2016-01-29 23:18:03 +00:00
|
|
|
MEDIA_DOCS = os.path.join(settings.MEDIA_ROOT, "documents")
|
2015-12-20 19:23:33 +00:00
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2016-01-21 12:50:22 -05:00
|
|
|
|
2015-12-20 19:23:33 +00:00
|
|
|
self.verbosity = 0
|
2016-01-30 01:18:52 +00:00
|
|
|
|
|
|
|
|
self.file_consumer = None
|
2016-02-06 17:05:36 +00:00
|
|
|
self.mail_fetcher = None
|
2016-01-21 12:50:22 -05:00
|
|
|
|
2015-12-20 19:23:33 +00:00
|
|
|
BaseCommand.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
|
|
|
|
|
|
|
|
|
self.verbosity = options["verbosity"]
|
|
|
|
|
|
2016-01-30 01:18:52 +00:00
|
|
|
try:
|
2016-02-28 00:39:40 +00:00
|
|
|
self.file_consumer = Consumer()
|
2016-02-06 17:05:36 +00:00
|
|
|
self.mail_fetcher = MailFetcher()
|
|
|
|
|
except (ConsumerError, MailFetcherError) as e:
|
2016-01-30 01:18:52 +00:00
|
|
|
raise CommandError(e)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
os.makedirs(self.MEDIA_DOCS)
|
|
|
|
|
except FileExistsError:
|
|
|
|
|
pass
|
2015-12-20 19:23:33 +00:00
|
|
|
|
2015-12-21 02:44:24 +00:00
|
|
|
try:
|
|
|
|
|
while True:
|
|
|
|
|
self.loop()
|
2015-12-26 13:21:33 +00:00
|
|
|
time.sleep(self.LOOP_TIME)
|
|
|
|
|
if self.verbosity > 1:
|
|
|
|
|
print(".")
|
2015-12-21 02:44:24 +00:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
|
print("Exiting")
|
|
|
|
|
|
|
|
|
|
def loop(self):
|
|
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
# Consume whatever files we can
|
2016-01-30 01:18:52 +00:00
|
|
|
self.file_consumer.consume()
|
2016-01-01 16:13:59 +00:00
|
|
|
|
2016-02-06 17:05:36 +00:00
|
|
|
# Occasionally fetch mail and store it to be consumed on the next loop
|
|
|
|
|
delta = self.mail_fetcher.last_checked + self.MAIL_DELTA
|
2016-02-14 01:32:25 +00:00
|
|
|
if delta < datetime.datetime.now():
|
2016-02-06 17:05:36 +00:00
|
|
|
self.mail_fetcher.pull()
|