aboutsummaryrefslogtreecommitdiff
path: root/mu4web/mu.py
blob: 8efbd383aaec10c0f4611be95b365a98af2cad41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""
Wrapper for the `mu` command line.
"""

import email.message
import email.policy
from email.parser import BytesParser
import subprocess
from subprocess import PIPE
import xml.dom.minidom
import xml.dom
from xdg.BaseDirectory import xdg_cache_home
import os.path
from . import xapian
from datetime import datetime
from os import PathLike
from pathlib import Path

from typing import (
    Optional,
    TypedDict,
)

parser = BytesParser(policy=email.policy.default)


def find_file(id: str) -> Optional[PathLike]:
    cmd = subprocess.run(['mu', 'find', '-u', f'i:{id}',
                          '--fields', 'l'],
                         stdout=PIPE)
    filename = cmd.stdout.decode('UTF-8').strip()

    if cmd.returncode == 4:
        return None
    if cmd.returncode != 0:
        raise MuError(cmd.returncode)
    return Path(filename)


def get_mail(id: str) -> email.message.Message:
    """
    Lookup email by Message-ID.

    [Raises]
        MuError
    """
    filename = find_file(id)
    if not filename:
        # TODO better error here
        raise MuError(1)
    with open(filename, "rb") as f:
        mail = parser.parse(f)
    return mail


class MuError(Exception):
    codes = {
        1: 'General Error',
        2: 'No Matches',
        4: 'Database is corrupted'
    }

    def __init__(self, returncode: int):
        self.returncode: int = returncode
        self.msg: str = MuError.codes.get(returncode, 'Unknown Error')

    def __repr__(self) -> str:
        return f'MuError({self.returncode}, "{self.msg}")'

    def __str__(self) -> str:
        return repr(self)


def search(query: str,
           sortfield: Optional[str] = 'subject',
           reverse: bool = False) -> list[dict[str, str]]:
    """
    [Parameters]
        query     - Search query as per mu-find(1).
        sortfield - Field to sort the values by
        reverse   - If the sort should be reversed

    [Returns]
    >>> {'from': 'Hugo Hörnquist <hugo@example.com>',
         'date': '1585678375',
         'size': '377',
         'msgid': 'SAMPLE-ID@localhost',
         'path': '/home/hugo/.local/var/mail/INBOX/cur/filename',
         'maildir': '/INBOX'
         }
    """

    if not query:
        raise ValueError('Query required for mu_search')
    cmdline = ['mu', 'find',
               '--format=xml',
               query]
    if sortfield:
        cmdline.extend(['--sortfield', sortfield])
    if reverse:
        cmdline.append('--reverse')
    cmd = subprocess.run(cmdline, capture_output=True)
    if cmd.returncode == 1:
        raise MuError(cmd.returncode)
    if cmd.returncode == 4:
        # no matches
        return []
    if cmd.returncode != 0:
        raise MuError(cmd.returncode)
    dom = xml.dom.minidom.parseString(cmd.stdout.decode('UTF-8'))

    message_list = []
    messages = dom.childNodes[0]
    assert messages.localName == 'messages'
    for message in messages.childNodes:
        msg_dict = {}
        if message.nodeType != xml.dom.Node.ELEMENT_NODE:
            continue
        for kv in message.childNodes:
            if kv.nodeType != xml.dom.Node.ELEMENT_NODE:
                continue
            msg_dict[kv.localName] = kv.childNodes[0].data
        message_list.append(msg_dict)

    return message_list


def base_directory() -> PathLike:
    """
    Returns where where mu stores its files.

    Defaults to $XDG_CACHE_HOME/mu, but can be changed through the
    environment variable MUHOME.

    TODO make this configurable.
    """
    return Path(os.getenv('MUHOME') or os.path.join(xdg_cache_home, 'mu'))


class MuInfo(TypedDict):
    database_path: str
    changed: datetime
    created: datetime
    indexed: datetime
    maildir: str
    schema_version: str
    messages_in_store: int


def info() -> MuInfo:

    db = os.path.join(base_directory(), "xapian")

    def f(key: str) -> datetime:
        return datetime.fromtimestamp(int(xapian.metadata_get(db, key), 16))

    changed = f('changed')
    created = f('created')
    indexed = f('indexed')

    maildir = xapian.metadata_get(db, 'maildir')
    schema_version = xapian.metadata_get(db, 'schema-version')

    cmd = subprocess.Popen(['xapian-delve', '-V3', '-1', db],
                           stdout=subprocess.PIPE)
    # Start at minus one to ignore header
    count = -1
    if cmd.stdout:
        for line in cmd.stdout:
            count += 1

    return {
        'database_path': db,
        'messages_in_store': count,
        'changed': changed,
        'created': created,
        'indexed': indexed,
        'maildir': maildir,
        'schema_version': schema_version,
    }