~sircmpwn/lists.sr.ht

ref: efa0c307a1b592acfa9b92eae18ca2409d502f4d lists.sr.ht/listssrht/blueprints/archives.py -rw-r--r-- 11.6 KiB View raw
efa0c307Siva Mahadevan Add is:thread & is:reply filters 8 months ago
                                                                                
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
from datetime import datetime
from flask import Blueprint, render_template, abort, request, redirect, url_for
from flask import Response, session
from flask_login import current_user
from sqlalchemy import String, cast, or_
from srht.config import cfg
from srht.database import db
from srht.search import search
from srht.flask import paginate_query, loginrequired
from srht.validation import Validation
from listssrht.filters import post_address
from listssrht.types import List, User, Email, Subscription, ListAccess, Access
from listssrht.types import Patchset, PatchsetStatus
from listssrht.webhooks import ListWebhook, UserWebhook
from urllib.parse import quote, urlencode
import email
import email.policy
import email.utils

archives = Blueprint("archives", __name__)

msgauth_server = cfg("lists.sr.ht", "msgauth-server", default=None)

def get_list(owner_name, list_name, current_user=current_user):
    if owner_name and owner_name.startswith('~'):
        owner_name = owner_name[1:]
        owner = User.query.filter(User.username == owner_name).one_or_none()
        if not owner:
            return None, None, None
    else:
        # TODO: orgs
        return None, None, None
    ml = (List.query
            .filter(List.name == list_name)
            .filter(List.owner_id == owner.id)
        )
    if current_user:
        ml = ml.outerjoin(Access, Access.list_id == List.id)
    ml = ml.one_or_none()
    if not ml:
        return None, None, None
    if current_user:
        acl = next((acl for acl in ml.acls
            if acl.user_id == current_user.id), None)
        if current_user.id == ml.owner_id:
            access = ListAccess.all
        elif acl:
            access = acl.permissions
        elif (Subscription.query
                .filter(Subscription.user_id == current_user.id)).count():
            access = ml.subscriber_permissions | ml.account_permissions
        else:
            access = ml.account_permissions
    else:
        access = ml.nonsubscriber_permissions
    return owner, ml, access

def apply_search(query, terms=None):
    if not terms:
        terms = request.args.get("search")
    if not terms:
        return query.filter(Email.parent_id == None), None
    def canonicalize(header):
        return "-".join(h[0].upper() + h[1:] for h in header.split("-"))
    def me_alias(header, q, v):
        return (q.filter(cast(Email.headers[header], String).ilike(
                "%" + current_user.email + "%"))
            if current_user and v == "me" else
            q.filter(cast(Email.headers[header], String).ilike("%" + v + "%")))
    def patchset_status(q, v):
        try:
            return (q.join(Patchset, Email.patchset_id == Patchset.id)
                    .filter(Patchset.status == PatchsetStatus(v)))
        except ValueError:
            return q.filter(False)
    return search(query, terms, [Email.body, Email.subject], {
        "is": lambda q, v: q.filter({
            "patch": Email.is_patch,
            "reply": Email.parent_id != None,
            "request-pull": Email.is_request_pull,
            "thread": Email.nreplies > 0,
        }.get(v, False)),
        "from": lambda q, v: me_alias("From", q, v),
        "to": lambda q, v: me_alias("To", q, v),
        "cc": lambda q, v: me_alias("Cc", q, v),
        "status": patchset_status,
        "prefix": lambda q, v: (q
            .join(Patchset, Email.patchset_id == Patchset.id)
            .filter(Patchset.prefix == v)),
        "sender-timestamp": lambda q, v: (q
            .filter(Email.message_date == datetime.utcfromtimestamp(int(v)))),
        None: lambda q, p, v: query.filter(cast(
            Email.headers[canonicalize(p)], String).ilike("%" + v + "%")),
    }), terms

def _dkim_explain(status, domain):
    return {
        "pass": f"Valid DKIM signature for {domain}",
        "fail": f"Invalid DKIM signature for {domain}. The message may have" +
            f" been tampered with, or the mail server at {domain} is" +
            " misconfigured.",
        "policy": "This email has a DKIM signature, but is for some reason" +
            " unsuitable for the policy of the recipient.",
        "neutral": "This email has a DKIM signature, but it has syntax errors" +
            " or other problems rendering it meaningless. This is generally" +
            f" a configuration error with the mail server at {domain}.",
        "temperror": "A temporary error occured while validating this DKIM" +
            " signature.",
        "permerror": "A permanent error occured while validating this DKIM" +
            " signature, such as a missing or invalid header. This is" +
            f" generally a configuration error with the mail server at {domain}."
    }.get(status)

def parse_auth_result(mail, method):
    address = email.utils.parseaddr(mail["From"])[1]
    mailboxhost = address.split("@", 2)
    if len(mailboxhost) < 2:
        return None, None
    domain = mailboxhost[1].lower()
    if msgauth_server is None:
        return None, None
    fields = mail.get_all("Authentication-Results", failobj=[])
    for field in fields:
        parts = field.lower().replace(';', ' ').split()
        host = parts.pop(0)
        if host != msgauth_server:
            continue
        if parts[0].isalnum():
            version = parts.pop(0)
            if version != "1":
                continue
        [meth, result] = parts.pop(0).split('=', 2)
        if meth != method.lower():
            continue
        if not "header.d=" + domain in parts:
            continue
        return result, _dkim_explain(result, domain)
    return None, _dkim_explain("none", domain)

@archives.route("/<owner_name>/<list_name>")
def archive(owner_name, list_name):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    if access.value == 0:
        abort(403)
    threads = (Email.query
            .filter(Email.list_id == ml.id)
        ).order_by(Email.updated.desc())
    threads, search = apply_search(threads)
    threads, pagination = paginate_query(threads)

    subscription = None
    if current_user:
        subscription = (Subscription.query
                .filter(Subscription.list_id == ml.id)
                .filter(Subscription.user_id == current_user.id)).one_or_none()

    message = session.pop("message", None)
    return render_template("archive.html",
            view="archives", owner=owner, ml=ml, threads=threads,
            access=access, ListAccess=ListAccess,
            search=search, subscription=subscription,
            parseaddr=email.utils.parseaddr,
            message=message, **pagination)

@archives.route("/<owner_name>/<list_name>/<message_id>")
def thread(owner_name, list_name, message_id):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    if ListAccess.browse not in access:
        abort(403)
    thread = (Email.query
            .filter(Email.message_id == message_id)
            .filter(Email.list_id == ml.id)
        ).one_or_none()
    if not thread:
        abort(404)
    if thread.thread_id != None:
        return redirect(url_for("archives.thread",
            owner_name=owner_name,
            list_name=list_name,
            message_id=thread.thread.message_id) + "#" + thread.message_id)
    # TODO: multi-order sort by patch version and index, for emails which
    # arrive out of order

    messages = (Email.query
            .filter(Email.thread_id == thread.id)
            .order_by(Email.created)).all()

    def reply_to(msg):
        params = {
            "cc": msg.parsed()['From'],
            "in-reply-to": msg.message_id,
            "subject": (f"Re: {msg.subject}"
                if not msg.subject.lower().startswith("re:")
                else msg.subject),
        }
        return f"mailto:{post_address(msg.list)}?{urlencode(params, quote_via=quote)}"

    return render_template("thread.html", view="archives", owner=owner,
            ml=ml, thread=thread, messages=messages,
            parseaddr=email.utils.parseaddr,
            parse_auth_result=parse_auth_result,
            reply_to=reply_to)

@archives.route("/<owner_name>/<list_name>/<message_id>/raw")
def raw(owner_name, list_name, message_id):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    if ListAccess.browse not in access:
        abort(403)
    message = (Email.query
            .filter(Email.message_id == message_id)
            .filter(Email.list_id == ml.id)
        ).one_or_none()
    if not message:
        abort(404)
    return Response(message.envelope, mimetype='text/plain')

def format_mbox(msg):
    parsed = msg.parsed()
    b = parsed.as_bytes(unixfrom=True, policy=email.policy.SMTPUTF8) + b'\r\n'
    for reply in msg.replies:
        b += format_mbox(reply)
    return b

@archives.route("/<owner_name>/<list_name>/<message_id>/mbox")
def mbox(owner_name, list_name, message_id):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    if ListAccess.browse not in access:
        abort(403)
    thread = (Email.query
            .filter(Email.message_id == message_id)
            .filter(Email.list_id == ml.id)
        ).one_or_none()
    if not thread or thread.thread_id != None:
        abort(404)
    mbox = format_mbox(thread)
    return Response(mbox, mimetype='application/mbox')

@archives.route("/<owner_name>/<list_name>/<message_id>/remove", methods=["POST"])
@loginrequired
def remove_message(owner_name, list_name, message_id):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    if ml.owner_id != current_user.id:
        abort(401)
    message = (Email.query
            .filter(Email.message_id == message_id)
            .filter(Email.list_id == ml.id)
        ).one_or_none()
    if not message:
        abort(404)
    redir = url_for("archives.archive",
            owner_name=owner_name, list_name=list_name)
    if message.thread != None:
        redir = url_for("archives.thread",
            owner_name=owner_name, list_name=list_name,
            message_id=message.thread.message_id)
    db.session.delete(message)
    db.session.commit()
    return redirect(redir)

@archives.route("/<owner_name>/<list_name>/subscribe", methods=["POST"])
@loginrequired
def subscribe(owner_name, list_name):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    if ListAccess.browse not in access:
        abort(403)
    sub = (Subscription.query
        .filter(Subscription.list_id == ml.id)
        .filter(Subscription.user_id == current_user.id)).one_or_none()
    if sub:
        return redirect(url_for("archives.archive",
            owner_name=owner_name, list_name=list_name))
    sub = Subscription()
    sub.user_id = current_user.id
    sub.user = current_user
    sub.list_id = ml.id
    sub.list = ml
    db.session.add(sub)
    UserWebhook.deliver(UserWebhook.Events.subscription_create,
            sub.to_dict(), UserWebhook.Subscription.user_id == sub.user_id)
    db.session.commit()
    return redirect(url_for("archives.archive",
        owner_name=owner_name, list_name=list_name))

@archives.route("/<owner_name>/<list_name>/unsubscribe", methods=["POST"])
@loginrequired
def unsubscribe(owner_name, list_name):
    owner, ml, access = get_list(owner_name, list_name)
    if not ml:
        abort(404)
    sub = (Subscription.query
        .filter(Subscription.list_id == ml.id)
        .filter(Subscription.user_id == current_user.id)).one_or_none()
    if sub:
        db.session.delete(sub)
        UserWebhook.deliver(UserWebhook.Events.subscription_remove,
                { "id": sub.id },
                UserWebhook.Subscription.user_id == sub.user_id)
        db.session.commit()
    return redirect(url_for("archives.archive",
        owner_name=owner_name, list_name=list_name))