~sircmpwn/meta.sr.ht

ref: 0.56.23 meta.sr.ht/metasrht/webhooks.py -rw-r--r-- 2.5 KiB
699f8ae5 — Peter Sanchez go.mod: core-go version bump 7 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
from srht.config import cfg
from srht.database import DbSession, db
if not hasattr(db, "session"):
    # Initialize the database if not already configured (for running daemon)
    db = DbSession(cfg("meta.sr.ht", "connection-string"))
    import metasrht.types
    db.init()
from srht.webhook import Event
from srht.webhook.celery import CeleryWebhook, make_worker

worker = make_worker(broker=cfg("meta.sr.ht", "webhooks", "redis://"))

class UserWebhook(CeleryWebhook):
    events = [
        Event("profile:update", "profile:read"),
        Event("ssh-key:add", "keys:read"),
        Event("ssh-key:remove", "keys:read"),
        Event("pgp-key:add", "keys:read"),
        Event("pgp-key:remove", "keys:read"),
    ]

def deliver_profile_update(user):
    """
    Delivers a profile update to subscribers, accounting for first-party
    clients receiving more details.
    """
    from metasrht.types import OAuthClient, OAuthToken
    event = UserWebhook.Events.profile_update
    third_party_subs = (UserWebhook.Subscription.query
        .join(OAuthToken, UserWebhook.Subscription.token_id == OAuthToken.id)
        .join(OAuthClient, OAuthToken.client_id == OAuthClient.id)
        .filter(UserWebhook.Subscription.user_id == user.id)
        .filter(not OAuthClient.preauthorized)
        .filter(UserWebhook.Subscription._events.ilike('%' + event.value + '%'))
    ).all()
    for sub in third_party_subs:
        if event in sub.events:
            UserWebhook.notify(sub, event, user.to_dict(first_party=False))

    # God this is a mess
    first_party_subs = (UserWebhook.Subscription.query
        .join(OAuthToken, UserWebhook.Subscription.token_id == OAuthToken.id)
        .filter(OAuthToken.client_id == None)
        .filter(UserWebhook.Subscription.user_id == user.id)
        .filter(UserWebhook.Subscription._events.ilike('%' + event.value + '%'))
    ).all()
    for sub in first_party_subs:
        if event in sub.events:
            UserWebhook.notify(sub, event, user.to_dict(first_party=True))

    legacy_first_party_subs = (UserWebhook.Subscription.query
        .join(OAuthToken, UserWebhook.Subscription.token_id == OAuthToken.id)
        .join(OAuthClient, OAuthToken.client_id == OAuthClient.id)
        .filter(UserWebhook.Subscription.user_id == user.id)
        .filter(OAuthClient.preauthorized)
        .filter(UserWebhook.Subscription._events.ilike('%' + event.value + '%'))
    ).all()
    for sub in legacy_first_party_subs:
        if event in sub.events:
            UserWebhook.notify(sub, event, user.to_dict(first_party=True))