Skip to content

Commit

Permalink
export_search: Add ability to limit by date sent.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmv authored and timabbott committed Nov 11, 2022
1 parent 2d5366f commit f3135eb
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions zerver/management/commands/export_search.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from argparse import ArgumentParser
from datetime import datetime
from datetime import datetime, timezone
from email.headerregistry import Address
from functools import lru_cache, reduce
from operator import or_
Expand Down Expand Up @@ -51,6 +51,18 @@ def add_arguments(self, parser: ArgumentParser) -> None:
metavar="<search term>",
help="Terms to search for in message body or topic",
)
parser.add_argument(
"--after",
metavar="<datetime>",
help="Limit to messages on or after this ISO datetime, treated as UTC",
type=lambda s: datetime.fromisoformat(s).astimezone(timezone.utc),
)
parser.add_argument(
"--before",
metavar="<datetime>",
help="Limit to messages on or before this ISO datetime, treated as UTC",
type=lambda s: datetime.fromisoformat(s).astimezone(timezone.utc),
)

def handle(self, *args: Any, **options: Any) -> None:
terms = set()
Expand All @@ -59,21 +71,28 @@ def handle(self, *args: Any, **options: Any) -> None:
terms.update(f.read().splitlines())
terms.update(options["search_terms"])

if not terms:
raise CommandError("One or more search terms are required!")
if not terms and not options["before"] and not options["after"]:
raise CommandError("One or more limits are required!")

if os.path.exists(options["output"]) and not options["force"]:
raise CommandError(
f"Output path '{options['output']}' already exists; use --force to overwrite"
)

realm = self.get_realm(options)
limits = Q()

limits = reduce(
or_,
[Q(content__icontains=term) | Q(subject__icontains=term) for term in terms],
Q(),
limits,
)

if options["after"]:
limits &= Q(date_sent__gt=options["after"])
if options["before"]:
limits &= Q(date_sent__lt=options["before"])

messages_query = Message.objects.filter(limits, realm=realm).order_by("date_sent")

def format_sender(full_name: str, delivery_email: str) -> str:
Expand Down

0 comments on commit f3135eb

Please sign in to comment.