aboutsummaryrefslogtreecommitdiff
path: root/main.py
blob: a8b5205e570564e62f66cbd02bc35323575859ad (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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
from email.message import EmailMessage
from email.headerregistry import Address
from urllib.parse import urlparse, urlencode, parse_qs
from http.cookies import BaseCookie
import http.cookies
import password
from password import Passwords
from uuid import uuid4
import os
from typing import (
    Optional,
    cast,
)
from mu import mu_search, get_mail
from html_render import HTML, render_document

from http.server import HTTPServer, BaseHTTPRequestHandler


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


style: HTML = lambda: """
    nav {
        display: block;
        width: 100%;
        height: 4em;
        color: white;
        background-color: darkgrey;
    }

    dl {
        display: grid;
        grid-template-columns: 10ch auto;
    }
    dt {
        font-weight: bold;
    }
    dd {
        font-family: mono;
        font-size: 80%;
    }
    dd > * {
        margin: 0;
    }

    """


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'},
            ('input', {'name': 'username', 'placeholder': 'Username'}),
            ('input', {'type': 'password',
                       'placeholder': 'Password',
                       'name': 'password'}),
            ('input', {'type': 'hidden',
                       'name': 'returnto',
                       'value': returnto})
            if returnto else [],
            ('input', {'type': 'submit'}),
            )


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 page_base(title: Optional[str] = None,
              body: HTML = [],
              username: Optional[str] = None) -> HTML:
    return ('html',
            ('head',
             ('meta', {'charset': 'utf-8'}),
             ('title', title),
             ('style', style),
             ),
            ('body',
             ('nav',
              user_info(username) if username else login_prompt()
              ),
             body))


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,
                                         username=username))

    return html_str


def search_field(q: str) -> HTML:
    return ('form', {'action': '/search', 'method': 'GET'},
            ('label', {'for': 'search'},
             'Mu Search Query'),
            ('textarea', {'id': 'search', 'name': 'q'},
             q),
            ('input', {'type': 'Submit'}))


def search_result(q, by, reverse):

    keys = ['From', 'To', 'Subject', 'Date', 'Size', 'Maildir', 'Msgid']

    rows = mu_search(q, by, reverse)
    body = []
    for row in rows:
        rowdata = ['tr']
        for key in keys:
            rowdata.append(row[key])
        body.append(rowdata)

    return ('table',
            ('thead',
             ('tr',
              [('th', m) for m in keys])),
            ('tbody',
             body
             ))


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

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

    return render_document(page_base(title='Serach',
                                     body=main_body,
                                     username=username))


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

    body = [('h1', "Sample ID's"),
            ('ul',
             [('li', ('a', {'href': '?' + urlencode({'id': id})}, id))
              for id in ids]
             ),
            ]

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


valid_session_cookies: dict[str, str] = {}


def validate_session_cookie(cookie: http.cookies.Morsel) -> Optional[str]:
    return valid_session_cookies.get(cookie.value)


def remove_session_cookie(cookie: http.cookies.Morsel) -> http.cookies.Morsel:
    if valid_session_cookies.get(cookie.value):
        del valid_session_cookies[cookie.value]
    cookie.set(cookie.key, '', '')
    # TODO how to expire cookie
    # cookie.expires = 0
    return cookie


passwords: Passwords = password.Passwords(cast(os.PathLike, 'passwords.json'))


def new_session_cookie(username: str) -> http.cookies.Morsel:
    global valid_session_cookies
    m: http.cookies.Morsel = http.cookies.Morsel()
    unique = str(uuid4())
    valid_session_cookies[unique] = username
    m.set('session', unique, unique)
    return m


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        url = urlparse(self.path)
        query = parse_qs(url.query)
        # print(type(self.headers))

        cookies = BaseCookie(self.headers.get('Cookie'))
        logged_in = None
        if c := cookies.get('session'):
            logged_in = validate_session_cookie(c)

        if url.path == '/':
            if not logged_in:
                self.send_response(307)
                q = urlencode({'returnto': self.path})
                self.send_header('location', '/login?' + q)
                self.end_headers()
            else:
                if id := query.get('id'):
                    print("id =", id)
                    response = response_for(''.join(id).replace(' ', '+'),
                                            logged_in)
                    self.send_response(200)
                else:
                    response = index_page(logged_in)
                    self.send_response(200)

                response = response.encode('UTF-8')
                self.send_header('Content-Type', 'text/html; charset=UTF-8')
                self.send_header('Content-Length', len(response))
                self.end_headers()
                self.wfile.write(response)

        elif url.path == '/search':
            if not logged_in:
                self.send_response(307)
                q = urlencode({'returnto': self.path})
                self.send_header('location', '/login?' + q)
                self.end_headers()
            else:
                response = search_page(query.get('q'),
                                       query.get('by'),
                                       logged_in)
                self.send_response(200)
                response = response.encode('UTF-8')
                self.send_header('Content-Type', 'text/html; charset=UTF-8')
                self.send_header('Content-Length', len(response))
                self.end_headers()
                self.wfile.write(response)

        elif url.path == '/login':
            if not logged_in:
                body = login_page(''.join(query.get('returnto')))
                self.send_response(200)
                content = render_document(page_base(title='Login', body=body))
                content = content.encode('UTF-8')
                self.send_header('Content-Type', 'text/html; charset=UTF-8')
                self.send_header('Content-Length', len(content))
                self.end_headers()
                self.wfile.write(content)
            else:
                # TODO do something sensible here
                pass

    def do_POST(self):
        url = urlparse(self.path)
        # query = parse_qs(url.query)
        cookies = BaseCookie(self.headers.get('Cookie'))
        logged_in = None
        if c := cookies.get('session'):
            logged_in = validate_session_cookie(c)
        print(cookies)
        print(valid_session_cookies)

        if url.path == '/login':
            # cl = content_length = self.headers.get('content-length')
            cl = self.headers.get('content-length')
            data = parse_qs(self.rfile.read(int(cl)))
            username = b''.join(data[b'username']).decode('UTF-8')
            password = b''.join(data[b'password']).decode('UTF-8')
            if passwords.validate(username, password):
                cookie = new_session_cookie(username)
                self.send_response(302)
                self.send_header('set-cookie', cookie.OutputString())
                if ret := data.get(b'returnto'):
                    returnto = b''.join(ret).decode('UTF-8')
                    self.send_header('location', returnto)
                else:
                    self.send_header('location', '/')
            else:
                self.send_response(302)
                self.send_header('location', '/')

            self.end_headers()

        if url.path == '/logout':
            if not logged_in:
                self.send_response(302)
                self.send_header('Location', '/')
                self.end_headers()
                return
            cookie = remove_session_cookie(cookies.get('session'))
            self.send_response(302)
            self.send_header('set-cookie', cookie)
            # TODO use the referer header?
            self.send_header('Location', '/')
            self.end_headers()


if __name__ == '__main__':
    server = HTTPServer(('0', 8090), Handler)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass

    server.server_close()