aboutsummaryrefslogtreecommitdiff
path: root/mu4web/main.py
blob: de2bbd415e4d83431989fd546d8c516538e9fe63 (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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
from email.message import EmailMessage
from email.headerregistry import Address
from urllib.parse import urlencode
import password
from password import Passwords
import os
from datetime import datetime
from flask_login import (
    LoginManager,
    login_required,
    login_user,
    current_user,
    logout_user,
)
from typing import (
    Optional,
    cast,
)
from mu import get_mail
import mu
from html_render import HTML, render_document
from user.local import LocalUser
from user.pam import PamUser

import subprocess

from flask import (
    Flask,
    session,
    request,
    redirect,
    url_for,
    flash,
    get_flashed_messages
)

login_manager = LoginManager()


def mailto(addr: str) -> HTML:
    return ('a', {'href': f'mailto:{addr}'}, addr)


def format_email(addr: Address) -> list[HTML]:
    mail_addr = f'{addr.username}@{addr.domain}'
    return [addr.display_name, ' <', mailto(mail_addr), '>']


def header_format(key: str, value) -> HTML:
    if key in ['to', 'cc', 'bcc']:
        return ('ul', *[('li', *format_email(addr))
                        for addr in value.addresses])
    elif key == 'from':
        return format_email(value.addresses[0])
    elif key == 'in-reply-to':
        # type(value) == email.headerregistry._UnstructuredHeader
        id = str(value).strip("<>")
        return ['<', ('a', {'href': '?' + urlencode({'id': id})}, id), '>']
    else:
        return value


def attachement_tree(mail: EmailMessage) -> HTML:
    ct = mail.get_content_type()
    fn = mail.get_filename()

    children = []
    for child in mail.iter_parts():
        children.append(attachement_tree(cast(EmailMessage, child)))

    content: HTML
    if children:
        content = ('ul', *children)
    else:
        content = []

    if fn:
        body = f'{ct} {fn}'
    else:
        body = str(ct)
    return ('li', body, content)

# --------------------------------------------------


def login_page(returnto: Optional[str] = None) -> HTML:
    return ('form', {'action': '/login', 'method': 'POST', 'class': 'loginform'},
            ('label', {'for': 'username'}, 'Användarnamn'),
            ('input', {'id': 'username', 'name': 'username', 'placeholder': 'Användarnamn'}),
            ('label', {'for': 'password'}, 'Lösenord'),
            ('input', {'type': 'password',
                       'placeholder': 'Lösenord',
                       'name': 'password'}),
            ('input', {'type': 'hidden',
                       'name': 'returnto',
                       'value': returnto})
            if returnto else [],
            ('input', {'type': 'submit', 'value': 'Logga in'}),
            )


def user_info(username: str) -> HTML:
    return [('span', username),
            ('form', {'action': '/logout', 'method': 'POST'},
                ('input', {'type': 'submit', 'value': 'Logga ut'}))]


def login_prompt() -> HTML:
    return ('a', {'href': '/login'}, 'Logga in')


def flashed_messages() -> HTML:
    return ('ul', {'class': 'flashes'},
            *[('li', msg) for msg in get_flashed_messages()])


def include_stylesheet(path):
    return ('link', {'type': 'text/css',
                     'rel': 'stylesheet',
                     'href': path})


def page_base(title: Optional[str] = None,
              body: HTML = []) -> HTML:
    return ('html',
            ('head',
             ('meta', {'charset': 'utf-8'}),
             ('title', title),
             include_stylesheet('/static/style.css'),
             ),
            ('body',
             ('nav',
              ('menu',
               ('li',
                ('h1', ('a', {'href': '/'}, 'Mu4Web')),
                ('li',
                 user_info(current_user.get_id())
                 if current_user.is_authenticated else login_prompt())
                ))),
             ('main',
              flashed_messages(),
              body),
             ('footer',
              ('menu',
               ('li', ('a', {'href': 'https://www.djcbsoftware.nl/code/mu/'}, 'mu')),
               ('li', ('a', {'href': 'https://git.hornquist.se/mu4web'}, 'Source')),
              ))))


def response_for(id: str, username: Optional[str] = None) -> str:

    mail = cast(EmailMessage, get_mail(id))

    headers = {}
    for (key, value) in mail.items():
        headers[key.lower()] = value

    head = []
    for h in ['date', 'from', 'to', 'cc', 'bcc', 'subject', 'x-original-to',
              'in-reply-to']:
        if x := headers.get(h.lower()):
            head += [('dt', h.title()),
                     ('dd', header_format(h.lower(), x))]

    body_part = mail.get_body(preferencelist=('html', 'plain'))
    if not body_part:
        raise ValueError("No suitable body in email")
    ct = body_part.get_content_type()
    body: HTML
    if ct == 'text/html':
        body = lambda: cast(EmailMessage, body_part).get_content()
    else:
        body = ('pre', cast(EmailMessage, body_part).get_content())

    if t := headers.get('subject'):
        title = f'Mail — {t}'
    else:
        title = 'Mail'

    main_body = [('dl', *head),
                 ('hr',),
                 ('main', body),
                 ('hr',),
                 ('ul', attachement_tree(mail)),
                 ]
    html_str = render_document(page_base(title=title,
                                         body=main_body))

    return html_str


def search_field(q: str) -> HTML:
    return ('form', {'id': 'searchform',
                     'action': '/search',
                     'method': 'GET'},
            ('label', {'for': 'search'},
             'Mu Search Query'),
            ('input', {'id': 'search',
                       'type': 'text',
                       'placeholder': 'Sök...',
                       'name': 'q',
                       'value': q}),
            ('input', {'type': 'Submit', 'value': 'Sök'}))


def search_result(q, by, reverse) -> HTML:

    # keys = ['from', 'to', 'subject', 'date', 'size', 'maildir', 'msgid']
    keys = ['from', 'to', 'subject', 'date']

    rows = mu.search(q, by, reverse)
    body: list[tuple] = []
    for row in rows:
        rowdata = []
        for key in keys:
            data = row.get(key, None)
            if data and key == 'date':
                dt = datetime.fromtimestamp(int(data))
                data = dt.strftime('%Y-%m-%d %H:%M')
            rowdata.append(('td', ('a', {'href': '/?id=' + row['msgid']}, data)))
        body.append(('tr', rowdata))


    if len(rows) == 0:
        return "No results"
    else:
        return ('div',
                ('p', f"{len(rows)} träffar"),
                ('table',
                 ('thead',
                  ('tr',
                   [('th', m.title()) for m in keys])),
                 ('tbody', body)))


def search_page(q, by):
    main_body = [search_field(q)]

    if q:
        main_body.append(search_result(q, by, False))

    return render_document(page_base(title='Search',
                                     body=main_body))


def mu_info():
    d = mu.info()
    rows = []
    for key, value in d.items():
        rows.append(('tr',
                     ('td', key),
                     ('td', value)))
    return ('table', ('tbody', rows))


def find_maildirs(basedir) -> dict[str, list[str]]:
    cmd = subprocess.run(['find', basedir,
                          '-type', 'd',
                          '-name', 'cur',
                          '-print0'],
                         capture_output=True)
    groups = {}
    # Group by first component
    for entry in cmd.stdout.split(b'\0'):
        dir = os.path.split(entry)[0][len(basedir) + 1:].decode('UTF-8')
        if not dir:
            continue
        parts = dir.split(os.path.sep)
        groups.setdefault(parts[0], []).append(parts[1:])
    return groups

def index_page():
    ids = [
        'CAEzixGsw-4zJ8_ejK_vDgmcQ9s-MbBc-ho+HL4arV4a+ghOOPg@mail.gmail.com',
        'CA+pcBt-gLb0GtbFOjJ5_7Q_WXtqApVPQ9w-3O7GH=VqCEQat6g@mail.gmail.com',
    ]

    data = mu.info()
    groups = find_maildirs(data['maildir'])

    entries = []

    for key, values in sorted(groups.items(), key=lambda p: p[0]):
        entries.append(('li',
                        ('details',
                         ('summary', key),
                         ('ul',
                          [('li',
                            ('a', {'href': 'search?' + urlencode({'q': f'maildir:"/{key}/{v}"'})}, v))
                           for v in sorted(os.path.sep.join(value) for value in values)]))))


    body = [('div', mu_info()),
            ('din', ('ul', entries)),
            ]

    return render_document(page_base(title='Mail index',
                                     body=body))


app = Flask(__name__)
login_manager.init_app(app)
app.secret_key = 'THIS IS A RANDOM STRING'


@login_manager.user_loader
def load_user(user_id):
    # return User.get(user_id)
    return LocalUser(user_id)


@app.route('/')
def index():
    if not current_user.is_authenticated:
        return redirect(url_for('login_page_', returnto=request.path))
    if id := request.args.get('id'):
        print("id =", id)
        response = response_for(''.join(id).replace(' ', '+'))
    else:
        response = index_page()
    return response


@app.route('/search')
@login_required
def search_page_():
    return search_page(request.args.get('q'),
                       request.args.get('by', None))


# TODO this page is really weird if you are already logged in
@app.route('/login', methods=['GET'])
def login_page_():
    body = login_page(request.args.get('returnto'))
    return render_document(page_base(title='Login', body=body))


@app.route('/login', methods=['POST'])
def login_form():
    resp = redirect(request.args.get('returnto', url_for('index')))

    username = request.form['username']
    password = request.form['password']
    user = PamUser(username)
    if user.validate(password):
        login_user(user)
    else:
        flash('Invalid username or password')
    return resp


@app.route('/logout', methods=['POST'])
@login_required
def logout_form():
    logout_user()
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(debug=True, port=8090)