aboutsummaryrefslogtreecommitdiffhomepage
path: root/apioforum/webhooks.py
blob: 554368761552b36ead0dfdf2764254e3f16b85bd (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
import urllib
import abc
import json
from .db import get_db
from flask import url_for, flash


def abridge(text,maxlen=20):
    if len(text) > maxlen+3:
        return text[:maxlen]+"..."
    else:
        return text

webhook_types = {}
def webhook_type(t):
    def inner(cls):
        webhook_types[t] = cls
        return cls
    return inner

class WebhookType(abc.ABC):
    def __init__(self, url, wh_id):
        self.url = url
        self.wh_id = wh_id

    @abc.abstractmethod
    def on_new_thread(self,thread):
        pass
    @abc.abstractmethod
    def on_new_post(self,post):
        pass

def get_webhooks(forum_id):
    db = get_db()
    # todo inheritance (if needed)
    webhooks = db.execute("select * from webhooks where webhooks.forum = ?;",(forum_id,)).fetchall()

    for wh in webhooks:
        wh_type = wh['type']
        if wh_type not in webhook_types:
            print(f"unknown webhook type {wh_type}")
            continue
        wh_url = wh['url']
        wo = webhook_types[wh_type](wh_url, wh['id'])
        yield wo

def do_webhooks_thread(forum_id,thread):
    for wh in get_webhooks(forum_id):
        try:
            wh.on_new_thread(thread)
        except Exception as e:
            #raise e
            flash(f"error executing webhook with id {wh.wh_id}")

def do_webhooks_post(forum_id,post):
    for wh in get_webhooks(forum_id):
        try:
            wh.on_new_post(post)
        except Exception as e:
            #raise e
            flash(f"error executing webhook with id {wh.wh_id}")


@webhook_type("fake")
class FakeWebhook(WebhookType):
    def on_new_post(self, post):
        print(f'fake wh {self.url} post {post["id"]}')
    def on_new_thread(self, thread):
        print(f'fake wh {self.url} thread {thread["id"]}')

@webhook_type("discord")
class DiscordWebhook(WebhookType):
    def send(self,payload):
        headers = {
            "User-Agent":"apioforum (https://g.gh0.pw/apioforum, v0.0)",
            "Content-Type":"application/json",
        }
        req = urllib.request.Request(
            self.url,
            json.dumps(payload).encode("utf-8"),
            headers
        )
        # todo: read response and things
        urllib.request.urlopen(req)
        #try:
        #    res = urllib.request.urlopen(req)
        #except urllib.error.HTTPError as e:
        #    print(f"error {e.code} {e.read()}")
        #else:
        #    print(f"succ {res.read()}")

    @staticmethod
    def field(name,value):
        return {"name":name,"value":value,"inline":True}

    def on_new_thread(self,thread):
        f = self.field
        db = get_db()
        forum = db.execute("select * from forums where id = ?",(thread['forum'],)).fetchone()
        username = thread['creator']
        userpage = url_for('user.view_user',username=username,_external=True)

        forumpage = url_for('forum.view_forum',forum_id=forum['id'],_external=True)

        post = db.execute("select * from posts where thread = ? order by id asc limit 1",(thread['id'],)).fetchone()

        payload = {
            "username":"apioforum",
            "avatar_url":"https://d.gh0.pw/lib/exe/fetch.php?media=wiki:logo.png",
            "embeds":[
                {
                    "title":"new thread: "+thread['title'],
                    "description":abridge(post['content']),
                    "url": url_for('thread.view_thread',thread_id=thread['id'],_external=True),
                    "color": 0xff00ff,
                    "fields":[
                        f('author',f"[{username}]({userpage})"),
                        f('forum',f"[{forum['name']}]({forumpage})"),
                    ],
                    "footer":{
                        "text":thread['created'].isoformat(' '),
                    },
                },
            ],
        }
        self.send(payload)

    def on_new_post(self,post):
        from .thread import post_jump
        f = self.field
        db = get_db()

        thread = db.execute("select * from threads where id = ?",(post['thread'],)).fetchone()
        threadpage = url_for('thread.view_thread',thread_id=thread['id'],_external=True)

        forum = db.execute("select * from forums where id = ?",(thread['forum'],)).fetchone()
        forumpage = url_for('forum.view_forum',forum_id=forum['id'],_external=True)

        username = post['author']
        userpage = url_for('user.view_user',username=username,_external=True)

        payload = {
            "username":"apioforum",
            "avatar_url":"https://d.gh0.pw/lib/exe/fetch.php?media=wiki:logo.png",
            "embeds":[
                {
                    "title":"re: "+thread['title'],
                    "description":abridge(post['content']),
                    "url": post_jump(post['id'],external=True),
                    "color": 0x00ffff,
                    "fields":[
                        f('author',f"[{username}]({userpage})"),
                        f('thread',f"[{thread['title']}]({threadpage})"),
                        f('forum',f"[{forum['name']}]({forumpage})"),
                    ],
                    "footer":{
                        "text":post['created'].isoformat(' '),
                    },
                },
            ],
        }
        self.send(payload)


@webhook_type("apionet")
class ApionetWebhook(WebhookType):
    # this is generally quite awful

    sockpath = "/srv/apiobot/bees.sock"
    #sockpath = "/home/rebecca/programming/apiobot/bees.sock"
    MAXMSGLEN = 420

    # doesn't use url or anything
    def send(self,payload):
        # this is possibly terrible
        import socket
        s = socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM)
        s.sendto(payload.encode("utf-8"),self.sockpath)
        s.close()

    def append_url(self,rest,url):
        ub = url.encode("utf-8")
        max_rlen = self.MAXMSGLEN - len(ub) - 1
        
        while len(rest.encode("utf-8")) > max_rlen:
            # chop off characters until short enough
            rest = rest[:-1]

        return rest + " " + url

    def on_new_thread(self,thread):
        # copy paste from above. the great refactor will fix this all
        db = get_db()
        forum = db.execute("select * from forums where id = ?",(thread['forum'],)).fetchone()
        username = thread['creator'][:30]
        post = db.execute("select * from posts where thread = ? order by id asc limit 1",(thread['id'],)).fetchone()
        url = url_for('thread.view_thread',thread_id=thread['id'],_external=True)


        p = ""
        if forum['id'] != 1:
            p = f" in {forum['name']}"
        payload = f"new thread{p}: \"{abridge(thread['title'],100)}\" - \"{abridge(post['content'],100)}\" (author: {username}) ->"
        self.send(self.append_url(payload,url))

    def on_new_post(self,post):
        from .thread import post_jump
        db = get_db()

        thread = db.execute("select * from threads where id = ?",(post['thread'],)).fetchone()
        forum = db.execute("select * from forums where id = ?",(thread['forum'],)).fetchone()
        username = post['author'][:30]

        url = post_jump(post['id'],external=True)


        payload = f"re: \"{abridge(thread['title'],100)}\" - \"{abridge(post['content'],100)}\" (author: {username}) ->"
        self.send(self.append_url(payload,url))