Preview external IMAP imports before copying mail

This commit is contained in:
parkel committed 2026-12-04 14:00:21 +01:00
1 parent 63efb9f204
commit f0665b2028
8 files changed
+618 -8

No files matched your search

+10
View File
@@ -2481,6 +2481,16 @@ password or app password. The source must resolve only to public addresses
and support implicit TLS on port 993 with a trusted certificate. OAuth-only and support implicit TLS on port 993 with a trusted certificate. OAuth-only
accounts are not supported. accounts are not supported.
Choose **Preview import** to check the source and destination and view a
read-only count of source folders and messages before copying. The size
is shown only when the source reports it for every folder. Partial
inventories identify how many folders were counted. Counts describe the
source at the time of the check and include mail already copied on prior
passes. Confirmation starts a new copy pass with the same source
credentials and uses the existing checkpoints. The preview expires after
30 minutes. Use **Import without preview** if you do not need an
inventory or your provider does not supply usable folder counts.
Start once and leave the page if needed. The worker continues from saved Start once and leave the page if needed. The worker continues from saved
checkpoints in batches and retries interrupted connections. Progress updates checkpoints in batches and retries interrupted connections. Progress updates
without a page reload and shows copied messages, previously copied messages, without a page reload and shows copied messages, previously copied messages,
@@ -0,0 +1,246 @@
"""Inspect a source and destination without copying any mailbox data."""
import imaplib
import json
import re
from contextlib import ExitStack
from datetime import timedelta
from time import monotonic
from cryptography.fernet import InvalidToken
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone
from django.views.decorators.debug import sensitive_variables
from coulobre import imap_import as imap
from coulobre.mail_import_receiver import SOCKET, open_destination
from . import mailbox_imports as imports
from .models import HostingMailbox, MailboxImport, MailboxImportPreview
from .node_client import NodeReplyError, require_matching_receiver
from .panel_roles import assigned_roles, scoped_user
from .resource_requests import lock_hosting_account
LIFETIME = timedelta(minutes=30)
INSPECT_SECONDS = 70
MAX_FOLDERS = 1000
STAT = re.compile(rb"\b(MESSAGES|SIZE) ([0-9]{1,18})(?=[ )])")
EXPIRED = "The preview expired. Enter the source password to check again."
UNAVAILABLE = "This mailbox is no longer available for preview."
def actor_role(actor):
return getattr(actor, "panel_role", "") or ""
def previews(mailbox, actor):
return MailboxImportPreview.objects.filter(
mailbox=mailbox, actor=actor, actor_role=actor_role(actor)
)
def identity(preview):
return ["preview-v1", preview.pk, *imports.job_identity(preview)]
@sensitive_variables()
@transaction.atomic
def queue_preview(mailbox, actor, data):
account = lock_hosting_account(mailbox.mail_domain.account_id, None)
current = HostingMailbox.objects.select_related(
"mail_domain__account", "provisioning", "removal"
).get(pk=mailbox.pk, mail_domain__account=account)
if not imports.available() or not imports.can_import(actor, current):
raise ValidationError(UNAVAILABLE)
imports.ready(current)
if MailboxImport.objects.filter(
mailbox=current, finished_at__isnull=True
).exists():
raise ValidationError("An import is already queued or running.")
source = imap.source_hostname(data["source_host"])
target = imap.source_hostname(settings.MAIL_IMAP_HOST)
if source == target:
raise ValidationError(
"Choose a different source server from this mailbox's server."
)
previous = MailboxImportPreview.objects.filter(
mailbox=current, actor=actor
)
if previous.filter(finished_at__isnull=True).exists():
raise ValidationError("A preview is already queued or running.")
previous.delete()
preview = MailboxImportPreview.objects.create(
mailbox=current,
actor=actor,
actor_role=actor_role(actor),
source_host=source,
source_user=data["source_user"],
target_host=target,
target_user=str(current),
)
preview.sealed_credentials = (
imports.encryption()
.encrypt(
json.dumps([identity(preview), data["source_password"]]).encode()
)
.decode("ascii")
)
preview.save(update_fields=["sealed_credentials"])
return preview
@sensitive_variables()
def password_for(preview):
try:
stored, secret = json.loads(
imports.encryption().decrypt(
preview.sealed_credentials.encode("ascii"),
ttl=int(LIFETIME.total_seconds()),
)
)
if stored == identity(preview):
return secret
except (InvalidToken, ValueError, UnicodeError, TypeError):
pass
raise imap.MailboxImportError(EXPIRED)
@sensitive_variables()
@transaction.atomic
def confirm_preview(mailbox, actor, pk):
# Match the lock order of both queue functions.
lock_hosting_account(mailbox.mail_domain.account_id, None)
preview = (
previews(mailbox, actor)
.select_for_update()
.filter(
pk=pk,
finished_at__isnull=False,
problem="",
requested_at__gt=timezone.now() - LIFETIME,
)
.first()
)
if preview is None or not preview.report.get("readable"):
raise ValidationError("Run a new preview before importing.")
if (
str(mailbox) != preview.target_user
or imap.source_hostname(settings.MAIL_IMAP_HOST) != preview.target_host
):
raise ValidationError("Run a new preview for the current destination.")
job = imports.queue_import(
mailbox,
actor,
{
"source_host": preview.source_host,
"source_user": preview.source_user,
"source_password": password_for(preview),
},
)
preview.delete()
return job
def authorized_mailbox(preview):
actor = preview.actor
if preview.actor_role:
if preview.actor_role not in assigned_roles(actor):
raise imap.MailboxImportError(UNAVAILABLE)
actor = scoped_user(actor, preview.actor_role)
mailbox = preview.mailbox
if (
not imports.available()
or not imports.can_import(actor, mailbox)
or str(mailbox) != preview.target_user
or imap.source_hostname(settings.MAIL_IMAP_HOST) != preview.target_host
):
raise imap.MailboxImportError(UNAVAILABLE)
imports.ready(mailbox)
return mailbox
def folder_status(client, name, include_size):
attributes = "(MESSAGES SIZE)" if include_size else "(MESSAGES)"
try:
result, rows = client.status(imap.quote(name), attributes)
except imaplib.IMAP4.abort:
raise
except imaplib.IMAP4.error:
result, rows = "NO", []
if result != "OK" and include_size:
return folder_status(client, name, False)
if result != "OK" or not rows or not isinstance(rows[0], bytes):
return None, None
# Match attributes after the folder name, which may contain spaces.
fields = rows[0].rsplit(b"(", 1)[-1]
values = {key: int(count) for key, count in STAT.findall(fields)}
return values.get(b"MESSAGES"), values.get(b"SIZE")
def inventory(client, mapping):
deadline = monotonic() + INSPECT_SECONDS
caps = {cap.upper() for cap in client.capabilities}
include_size = bool({"STATUS=SIZE", "IMAP4REV2"} & caps)
folders = []
for source_name, _ in mapping[:MAX_FOLDERS]:
if monotonic() >= deadline:
break
count, size = folder_status(client, source_name, include_size)
folders.append(
{
"name": imports.display_name(source_name),
"count": count,
"bytes": size,
}
)
readable = [folder for folder in folders if folder["count"] is not None]
complete = len(readable) == len(mapping)
return {
"folders": folders,
"total_folders": len(mapping),
"readable": len(readable),
"messages": sum(folder["count"] for folder in readable),
"bytes": sum(folder["bytes"] for folder in readable)
if complete and all(folder["bytes"] is not None for folder in readable)
else None,
"complete": complete,
}
@sensitive_variables()
def run_preview(preview):
mailbox = authorized_mailbox(preview)
source_ips = imap.resolve(preview.source_host, public_only=True)
target_ips = imap.resolve(preview.target_host, public_only=False)
if set(source_ips).intersection(target_ips):
raise imap.MailboxImportError(
"The source and destination resolve to the same server."
)
try:
require_matching_receiver(SOCKET)
except NodeReplyError as exc:
raise imap.MailboxImportError(str(exc)) from None
with ExitStack() as stack:
source = imports.connect(
preview.source_host, source_ips, "source", stack
)
imap.login(
source, preview.source_user, password_for(preview), "source"
)
target = stack.enter_context(open_destination(mailbox.spec))
target.select(b"INBOX", readonly=True)
roots = target.list_folders(root=True)
if len(roots) != 1:
raise imap.MailboxImportError(
"The destination did not identify its folder separator."
)
mapping = imap.map_folders(
imap.list_folders(source), roots[0].separator
)
if not mapping:
raise imap.MailboxImportError(
"The source has no selectable folders to copy."
)
return inventory(source, mapping)
+88 -2
View File
@@ -5,7 +5,7 @@ from datetime import timedelta
from billiard.exceptions import SoftTimeLimitExceeded from billiard.exceptions import SoftTimeLimitExceeded
from celery import shared_task from celery import shared_task
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models import F, Q from django.db.models import F, Q
from django.db.models.functions import Coalesce from django.db.models.functions import Coalesce
from django.utils import timezone from django.utils import timezone
@@ -13,8 +13,9 @@ from django.views.decorators.debug import sensitive_variables
from coulobre.imap_import import MailboxImportError from coulobre.imap_import import MailboxImportError
from . import mailbox_import_preview as preview
from . import mailbox_imports as imports from . import mailbox_imports as imports
from .models import MailboxImport from .models import MailboxImport, MailboxImportPreview
EXPIRED = "The source password expired. Enter it again to resume." EXPIRED = "The source password expired. Enter it again to resume."
CONNECTION_LOST = ( CONNECTION_LOST = (
@@ -50,6 +51,7 @@ def yield_batch(owned, now, *, retry=False):
) )
def dispatch_mailbox_imports(): def dispatch_mailbox_imports():
now = timezone.now() now = timezone.now()
dispatch_previews(now)
unfinished = MailboxImport.objects.filter(finished_at__isnull=True) unfinished = MailboxImport.objects.filter(finished_at__isnull=True)
waiting = unfinished.filter(started_at__isnull=True) waiting = unfinished.filter(started_at__isnull=True)
expired = Q( expired = Q(
@@ -148,3 +150,87 @@ def run_mailbox_import(pk, requested_at=None):
finish(owned, timezone.now(), imports.INTERRUPTED) finish(owned, timezone.now(), imports.INTERRUPTED)
else: else:
finish(owned, timezone.now()) finish(owned, timezone.now())
def dispatch_previews(now):
previews = MailboxImportPreview.objects.all()
cutoff = now - preview.LIFETIME
previews.filter(requested_at__lt=now - timedelta(days=1)).delete()
previews.filter(requested_at__lte=cutoff).exclude(
sealed_credentials=""
).update(sealed_credentials="")
unfinished = previews.filter(finished_at__isnull=True)
unfinished.filter(requested_at__lte=cutoff).update(
finished_at=now, problem=preview.EXPIRED
)
unfinished.filter(
started_at__lt=now - timedelta(seconds=imports.STALE_SECONDS)
).update(
finished_at=now, problem=imports.INTERRUPTED, sealed_credentials=""
)
if not imports.available():
return
waiting = (
unfinished.filter(started_at__isnull=True, requested_at__gt=cutoff)
.filter(
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lt=now - timedelta(seconds=90))
)
.order_by("requested_at")
)
for pk in list(waiting.values_list("pk", flat=True)[:3]):
if waiting.filter(pk=pk).update(last_dispatched_at=now):
run_mailbox_import_preview.apply_async(
args=[pk], queue=imports.QUEUE, expires=60, retry=False
)
@shared_task(
name="coulobre.hosting.tasks.run_mailbox_import_preview",
ignore_result=True,
soft_time_limit=100,
time_limit=115,
)
@sensitive_variables()
def run_mailbox_import_preview(pk):
started = timezone.now()
waiting = MailboxImportPreview.objects.filter(
pk=pk,
finished_at__isnull=True,
started_at__isnull=True,
requested_at__gt=started - preview.LIFETIME,
)
if not waiting.update(started_at=started):
return
owned = MailboxImportPreview.objects.filter(
pk=pk, started_at=started, finished_at__isnull=True
)
item = owned.select_related(
"actor",
"mailbox__mail_domain__account",
"mailbox__provisioning",
"mailbox__removal",
).first()
if item is None:
return
problem = ""
report = {}
try:
report = preview.run_preview(item)
if not report["readable"]:
problem = "No source folder could be counted."
except MailboxImportError as exc:
problem = str(exc)
except (ValidationError, ObjectDoesNotExist):
problem = preview.UNAVAILABLE
except (SoftTimeLimitExceeded, imaplib.IMAP4.error, OSError):
problem = (
"The IMAP preview did not finish. Check the source settings "
"or start the import without a preview."
)
owned.update(
finished_at=timezone.now(),
problem=problem,
report=report,
**({"sealed_credentials": ""} if problem else {}),
)
+46 -3
View File
@@ -16,6 +16,7 @@ from django.views.generic import FormView
from coulobre.imap_import import MailboxImportError, source_hostname from coulobre.imap_import import MailboxImportError, source_hostname
from . import mailbox_import_preview as preview
from .access import can_manage_hosting, customer_for_user from .access import can_manage_hosting, customer_for_user
from .mailbox_imports import PERMISSIONS, available, display_name, queue_import from .mailbox_imports import PERMISSIONS, available, display_name, queue_import
from .models import HostingMailbox, MailboxImport from .models import HostingMailbox, MailboxImport
@@ -80,12 +81,45 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
def job(self): def job(self):
return MailboxImport.objects.filter(mailbox=self.mailbox).first() return MailboxImport.objects.filter(mailbox=self.mailbox).first()
@cached_property
def preview(self):
return (
preview.previews(self.mailbox, self.request.user)
.filter(requested_at__gt=timezone.now() - preview.LIFETIME)
.first()
)
def post(self, request, *args, **kwargs):
if request.POST.get("action") != "confirm-preview":
return super().post(request, *args, **kwargs)
pk = request.POST.get("preview_id", "")
try:
if not pk.isascii() or not pk.isdecimal() or len(pk) > 18:
raise ValidationError("Run a new preview before importing.")
preview.confirm_preview(self.mailbox, request.user, int(pk))
except (ValidationError, MailboxImportError) as exc:
messages.error(
request,
exc.messages[0]
if isinstance(exc, ValidationError)
else str(exc),
)
except ObjectDoesNotExist:
messages.error(request, preview.UNAVAILABLE)
else:
messages.success(
request,
"Mailbox import queued. No DNS records will be changed.",
)
return redirect("panel:mailbox_import", pk=self.mailbox.pk)
def get_initial(self): def get_initial(self):
if not self.job: item = self.preview or self.job
if not item:
return {} return {}
return { return {
"source_host": self.job.source_host, "source_host": item.source_host,
"source_user": self.job.source_user, "source_user": item.source_user,
} }
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
@@ -122,6 +156,7 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
return super().get_context_data( return super().get_context_data(
mailbox=self.mailbox, mailbox=self.mailbox,
job=self.job, job=self.job,
preview=self.preview,
folders=items, folders=items,
report=report, report=report,
return_url=reverse( return_url=reverse(
@@ -137,6 +172,14 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
@sensitive_variables() @sensitive_variables()
def form_valid(self, form): def form_valid(self, form):
try: try:
if self.request.POST.get("action") == "preview":
preview.queue_preview(
self.mailbox, self.request.user, form.cleaned_data
)
messages.success(
self.request, "Preview queued. No messages will be copied."
)
return redirect("panel:mailbox_import", pk=self.mailbox.pk)
queue_import(self.mailbox, self.request.user, form.cleaned_data) queue_import(self.mailbox, self.request.user, form.cleaned_data)
except ValidationError as exc: except ValidationError as exc:
form.add_error(None, exc) form.add_error(None, exc)
@@ -0,0 +1,70 @@
# Generated by Django 5.2.19 on 2026-12-04 12:58
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0097_panel_mail_relay"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="MailboxImportPreview",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("actor_role", models.CharField(blank=True, max_length=16)),
("source_host", models.CharField(max_length=253)),
("source_user", models.CharField(max_length=254)),
("target_host", models.CharField(max_length=253)),
("target_user", models.CharField(max_length=254)),
("sealed_credentials", models.TextField(editable=False)),
("report", models.JSONField(blank=True, default=dict)),
(
"actor",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
(
"mailbox",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="hosting.hostingmailbox",
),
),
],
options={
"constraints": [
models.UniqueConstraint(
fields=("mailbox", "actor"),
name="one_imap_preview_per_mailbox_actor",
)
],
},
),
]
+22
View File
@@ -1672,6 +1672,28 @@ class MailboxImport(ProvisioningJob):
consecutive_retries = models.PositiveSmallIntegerField(default=0) consecutive_retries = models.PositiveSmallIntegerField(default=0)
class MailboxImportPreview(ProvisioningJob):
mailbox = models.ForeignKey(HostingMailbox, on_delete=models.CASCADE)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
actor_role = models.CharField(max_length=16, blank=True)
source_host = models.CharField(max_length=253)
source_user = models.CharField(max_length=254)
target_host = models.CharField(max_length=253)
target_user = models.CharField(max_length=254)
sealed_credentials = models.TextField(editable=False)
report = models.JSONField(default=dict, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=("mailbox", "actor"),
name="one_imap_preview_per_mailbox_actor",
)
]
class MailboxImportFolder(models.Model): class MailboxImportFolder(models.Model):
job = models.ForeignKey( job = models.ForeignKey(
MailboxImport, on_delete=models.CASCADE, related_name="folders" MailboxImport, on_delete=models.CASCADE, related_name="folders"
@@ -70,6 +70,47 @@
</section> </section>
{% endif %} {% endif %}
{% if preview and not job or preview and job.finished_at %}
<section class="surface" id="import-preview" aria-labelledby="preview-heading" data-live-status="mailbox-import-preview">
<header class="section-heading"><h2 id="preview-heading">Import preview</h2></header>
{% if not preview.finished_at %}
<p class="section-text" role="status" data-live-pending>Checking the source and destination. Nothing is being copied.</p>
<noscript><p class="section-text"><a href="{% url 'panel:mailbox_import' mailbox.pk %}">Refresh preview</a></p></noscript>
{% elif preview.problem %}
<p class="section-text" role="status">{{ preview.problem }}</p>
{% else %}
<p class="section-text">Source snapshot. These counts include previously copied messages. The import skips messages recorded at its checkpoints.</p>
<dl class="details section-text">
<div><dt>Folders counted</dt><dd>{{ preview.report.readable }} of {{ preview.report.total_folders }}</dd></div>
<div><dt>Messages in counted folders</dt><dd>{{ preview.report.messages }}</dd></div>
<div><dt>Source size</dt><dd>{% if preview.report.bytes is not None %}{{ preview.report.bytes|filesizeformat }}{% else %}Not available{% endif %}</dd></div>
</dl>
{% if not preview.report.complete %}
<p class="section-text">This preview is partial. Unchecked or unreadable folders are not included in the totals.</p>
{% endif %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Source folder</th><th scope="col">Messages</th><th scope="col">Source size</th></tr></thead>
<tbody>
{% for folder in preview.report.folders %}
<tr>
<th scope="row">{{ folder.name }}</th>
<td>{{ folder.count|default_if_none:"Not available" }}</td>
<td>{% if folder.bytes is not None %}{{ folder.bytes|filesizeformat }}{% else %}Not available{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<form class="editor" method="post">
{% csrf_token %}
<input type="hidden" name="preview_id" value="{{ preview.pk }}">
<div class="form-actions"><button class="button primary" name="action" value="confirm-preview">Start import</button></div>
</form>
{% endif %}
</section>
{% endif %}
{% if not job or job.finished_at %} {% if not job or job.finished_at %}
<section id="import-source" class="surface editor-surface"> <section id="import-source" class="surface editor-surface">
<form class="editor" method="post"> <form class="editor" method="post">
@@ -77,7 +118,10 @@
<p class="muted">Coulobre reads the source over TLS on port 993. It does not delete mail or change DNS. Use an app password if your provider requires one.</p> <p class="muted">Coulobre reads the source over TLS on port 993. It does not delete mail or change DNS. Use an app password if your provider requires one.</p>
{% if job %}<p>Enter the source password to resume a stopped import or copy new messages. Previously copied messages are not copied again.</p>{% endif %} {% if job %}<p>Enter the source password to resume a stopped import or copy new messages. Previously copied messages are not copied again.</p>{% endif %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"><button class="button primary" type="submit">{% if job %}Check and continue{% else %}Check and import{% endif %}</button></div> <div class="form-actions">
<button class="button primary" type="submit" name="action" value="preview">Preview import</button>
<button class="button secondary" type="submit" name="action" value="direct">{% if job %}Continue without preview{% else %}Import without preview{% endif %}</button>
</div>
</form> </form>
</section> </section>
{% endif %} {% endif %}
+91 -2
View File
@@ -11,14 +11,20 @@ from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre import imap_import as imap from coulobre import imap_import as imap
from . import mailbox_import_preview as preview
from . import mailbox_imports as imports from . import mailbox_imports as imports
from .mailbox_import_tasks import dispatch_mailbox_imports, run_mailbox_import from .mailbox_import_tasks import (
dispatch_mailbox_imports,
run_mailbox_import,
run_mailbox_import_preview,
)
from .models import ( from .models import (
Customer, Customer,
HostingAccount, HostingAccount,
HostingMailbox, HostingMailbox,
HostingMailDomain, HostingMailDomain,
MailboxImport, MailboxImport,
MailboxImportPreview,
MailboxProvisioning, MailboxProvisioning,
) )
from .panel_roles import scoped_user from .panel_roles import scoped_user
@@ -150,7 +156,7 @@ class MailboxImportTests(TestCase):
self.assertFalse(MailboxImport.objects.exists()) self.assertFalse(MailboxImport.objects.exists())
self.sign_in(self.customer) self.sign_in(self.customer)
response = self.client.get(self.url()) response = self.client.get(self.url())
self.assertContains(response, "Check and import") self.assertContains(response, "Preview import")
self.assertIn("no-store", response.headers["Cache-Control"]) self.assertIn("no-store", response.headers["Cache-Control"])
self.assertRedirects( self.assertRedirects(
self.client.post(self.url(), self.data()), self.url() self.client.post(self.url(), self.data()), self.url()
@@ -163,6 +169,89 @@ class MailboxImportTests(TestCase):
self.assertNotContains(response, self.data()["source_password"]) self.assertNotContains(response, self.data()["source_password"])
self.assertNotContains(response, "Destination mailbox password") self.assertNotContains(response, "Destination mailbox password")
def test_preview_requires_separate_confirmation_and_discards_secret(self):
self.sign_in(self.customer)
self.assertRedirects(
self.client.post(self.url(), self.data(action="preview")),
self.url(),
)
item = MailboxImportPreview.objects.get()
self.assertNotIn(
self.data()["source_password"], item.sealed_credentials
)
self.assertContains(
self.client.get(self.url()), "Nothing is being copied"
)
self.assertFalse(MailboxImport.objects.exists())
report = {
"folders": [{"name": "INBOX", "count": 35, "bytes": None}],
"total_folders": 1,
"readable": 1,
"messages": 35,
"bytes": None,
"complete": True,
}
with patch.object(preview, "run_preview", return_value=report) as run:
run_mailbox_import_preview(item.pk)
run_mailbox_import_preview(item.pk)
run.assert_called_once()
page = self.client.get(self.url())
self.assertContains(page, "Start import")
self.assertContains(page, "Not available")
events = {"action": "confirm-preview", "preview_id": item.pk}
self.sign_in(self.operator)
self.client.post(self.url(), events)
self.assertFalse(MailboxImport.objects.exists())
self.sign_in(self.customer)
self.client.post(self.url(), events)
self.client.post(self.url(), events)
self.assertFalse(MailboxImportPreview.objects.exists())
job = MailboxImport.objects.get()
self.assertEqual(
imports.open_credentials(job), self.data()["source_password"]
)
def test_preview_reports_partial_counts_without_inventing_a_size(self):
source = Mock(capabilities=("IMAP4REV1", "STATUS=SIZE"))
source.status.side_effect = [
("OK", [b'"INBOX" (MESSAGES 0 SIZE 0)']),
("NO", []),
("OK", [b'"Archive.2020" (MESSAGES 13)']),
("NO", []),
("NO", []),
]
report = preview.inventory(
source,
[(name, name) for name in (b"INBOX", b"Archive.2020", b"Lost")],
)
self.assertEqual(report["messages"], 13)
self.assertEqual(report["readable"], 2)
self.assertEqual(report["total_folders"], 3)
self.assertIsNone(report["bytes"])
self.assertFalse(report["complete"])
self.assertEqual(report["folders"][0]["count"], 0)
source.select.assert_not_called()
source.fetch.assert_not_called()
source.append.assert_not_called()
def test_preview_expires_without_queuing_an_import(self):
self.sign_in(self.customer)
self.client.post(self.url(), self.data(action="preview"))
item = MailboxImportPreview.objects.get()
MailboxImportPreview.objects.update(
requested_at=timezone.now()
- preview.LIFETIME
- timedelta(seconds=1)
)
dispatch_mailbox_imports()
item.refresh_from_db()
self.assertIn("expired", item.problem)
self.assertFalse(item.sealed_credentials)
self.client.post(
self.url(), {"action": "confirm-preview", "preview_id": item.pk}
)
self.assertFalse(MailboxImport.objects.exists())
def test_disabled_feature_does_not_accept_credentials(self): def test_disabled_feature_does_not_accept_credentials(self):
self.sign_in(self.customer) self.sign_in(self.customer)
with override_settings(MAILBOX_IMAP_IMPORT=False): with override_settings(MAILBOX_IMAP_IMPORT=False):