~reedwade/wee-matter

ref: 147cedc7e0153b020e077a302e67b33a9e0f4f46 wee-matter/wee_matter/server.py -rw-r--r-- 11.9 KiB
147cedc7Stacy Harper Rehydrate team channels on reconnection too 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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import weechat
import wee_matter
import json
import re
from typing import NamedTuple

servers = {}

Server = NamedTuple(
    "Server",
    [
        ("name", str),
        ("host", str),
        ("port", str),
        ("protocol", str),
        ("path", str),
        ("username", str),
        ("password", str),
        ("user", any),
        ("user_token", str),
        ("users", dict),
        ("teams", dict),
        ("buffer", any),
        ("buffers", list),
        ("worker", any),
        ("reconnection_loop_hook", str),
    ],
)

User = NamedTuple(
    "User",
    [
        ("id", str),
        ("username", str),
        ("color", str),
    ]
)

Team = NamedTuple(
    "Team",
    [
        ("id", str),
        ("name", str),
        ("display_name", str),
        ("buffer", any),
        ("buffers", list),
    ]
)

def server_root_url(server: Server):
    root_url = server.protocol + "://" + server.host

    if (server.protocol == "https" and server.port != "443") or (server.protocol == "http" and server.port != "80"):
        root_url += ":" + server.port
    if server.path:
        root_url += server.path

    return root_url

def has_server(server_name):
    return server_name in servers

def get_server(server_name):
    return servers[server_name]

def get_servers():
    return servers

def update_server_worker(server, worker):
    server = server._replace(worker=worker)
    servers[server.name] = server
    return server

def get_server_from_buffer(buffer):
    server_name = weechat.buffer_get_string(buffer, "localvar_server_name")
    return get_server(server_name)

def is_connected(server: Server):
    return server.worker

def unload_team(team):
    for buffer in team.buffers:
        weechat.buffer_close(buffer)
    weechat.buffer_close(team.buffer)


def create_team_from_team_data(team_data, server):
    server_number = weechat.buffer_get_integer(server.buffer, "number")

    buffer = weechat.buffer_new("weematter." + team_data["display_name"], "", "", "", "")
    weechat.buffer_set(buffer, "number", str(server_number+1))

    weechat.buffer_set(buffer, "short_name", team_data["display_name"])
    weechat.buffer_set(buffer, "localvar_set_server_name", server.name)
    weechat.buffer_set(buffer, "localvar_set_server", team_data["display_name"])
    weechat.buffer_set(buffer, "localvar_set_type", "server")

    return Team(
        id= team_data["id"],
        name= team_data["name"],
        display_name= team_data["display_name"],
         buffer= buffer,
         buffers= [],
    )

def color_for_username(username):
    nick_colors = weechat.config_string(
         weechat.config_get("weechat.color.chat_nick_colors")
    ).split(",")

    nick_color_count = len(nick_colors)
    color_id = hash(username) % nick_color_count

    return nick_colors[color_id]

def create_user_from_user_data(user_data, server):
    return User(
        id= user_data["id"],
        username= user_data["username"],
        color= color_for_username(user_data["username"]),
    )

def server_completion_cb(data, completion_item, current_buffer, completion):
    servers = get_servers()
    for server_name in servers:
        weechat.hook_completion_list_add(completion, server_name, 0, weechat.WEECHAT_LIST_POS_SORT)
    return weechat.WEECHAT_RC_OK

def load_server(server_name):
    user = User(
        id = "",
        username = "",
        color = "",
    )
    servers[server_name] = Server(
        name= server_name,
        host= wee_matter.config.get_server_config(server_name, "address"),
        port= wee_matter.config.get_server_config(server_name, "port"),
        protocol= wee_matter.config.get_server_config(server_name, "protocol"),
        path= "",
        username= wee_matter.config.get_server_config(server_name, "username"),
        password= wee_matter.config.get_server_config(server_name, "password"),
        user= user,
        user_token= "",
        users= {},
        teams= {},
        buffer= None,
        buffers= [],
        worker= None,
        reconnection_loop_hook= "",
    )

    return servers[server_name]

def unload_server(server_name):
    if server_name not in servers:
        weechat.prnt("", "Server is not loaded")
        return

    weechat.prnt("", "Unloading server")
    server = servers.pop(server_name)

    if server.worker:
        wee_matter.websocket.close_worker(server.worker)
    if server.reconnection_loop_hook:
        weechat.unhook(server.reconnection_loop_hook)

    for buffer in server.buffers:
        weechat.buffer_close(buffer)
    for team in server.teams.values():
        unload_team(team)

    weechat.buffer_close(server.buffer)

def connect_server_team_channel(channel_id, server):
    wee_matter.room.register_buffer_hydratating(channel_id)
    wee_matter.http.enqueue_request(
        "run_get_channel",
        channel_id, server, "connect_server_team_channel_cb", server.name
    )

def connect_server_team_channel_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while connecting team channel")
        return weechat.WEECHAT_RC_ERROR

    server = get_server(server_name)

    channel_data = json.loads(out)
    wee_matter.room.remove_buffer_hydratating(channel_data["id"])
    wee_matter.room.create_room_from_channel_data(channel_data, server)

    return weechat.WEECHAT_RC_OK

def connect_server_team_channels_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while connecting team channels")
        return weechat.WEECHAT_RC_ERROR

    server = get_server(server_name)

    response = json.loads(out)
    for channel_data in response:
        if wee_matter.room.already_loaded_buffer(channel_data["id"]):
            continue
        wee_matter.room.create_room_from_channel_data(channel_data, server)

    return weechat.WEECHAT_RC_OK

def connect_server_users_cb(data, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while connecting users")
        return weechat.WEECHAT_RC_ERROR

    server_name, page = data.split("|")
    page = int(page)
    server = get_server(server_name)

    response = json.loads(out)
    for user in response:
        if user["id"] == server.user.id:
            server.users[user["id"]] = server.user
        else:
            server.users[user["id"]] = create_user_from_user_data(user, server)

    if len(response) == 60:
        wee_matter.http.enqueue_request(
            "run_get_users",
            server, page+1, "connect_server_users_cb", "{}|{}".format(server.name, page+1)
        )
    else:
        wee_matter.http.enqueue_request(
            "run_get_user_teams",
            server.user.id, server, "connect_server_teams_cb", server.name
        )

    return weechat.WEECHAT_RC_OK

def connect_server_teams_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while connecting teams")
        return weechat.WEECHAT_RC_ERROR

    server = get_server(server_name)

    response = json.loads(out)

    for team_data in response:
        server.teams[team_data["id"]] = create_team_from_team_data(team_data, server)

    for team_data in response:
        wee_matter.http.enqueue_request(
            "run_get_user_team_channels",
            server.user.id, team_data["id"], server, "connect_server_team_channels_cb", server.name
        )

    return weechat.WEECHAT_RC_OK

def connect_server_team_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while connecting team")
        return weechat.WEECHAT_RC_ERROR

    server = get_server(server_name)

    team_data = json.loads(out)

    server.teams[team_data["id"]] = create_team_from_team_data(team_data, server)
    wee_matter.http.enqueue_request(
        "run_get_user_team_channels",
        server.user.id, team_data["id"], server, "connect_server_team_channels_cb", server.name
    )

    return weechat.WEECHAT_RC_OK

def new_user_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while adding a new user")
        return weechat.WEECHAT_RC_ERROR

    server = get_server(server_name)

    response = json.loads(out)
    server.users[response["id"]] = create_user_from_user_data(response, server)

    return weechat.WEECHAT_RC_OK

def connect_server_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while connecting")
        return weechat.WEECHAT_RC_ERROR

    token_search = re.search('[tT]oken: (\w*)', out)

    out = out.splitlines()[-1] # we remove the headers line
    response = json.loads(out)

    server = get_server(server_name)

    user = User(
        id= response["id"],
        username= response["username"],
        color= weechat.config_string(weechat.config_get("weechat.color.chat_nick_self")),
    )

    server = server._replace(
        user_token=token_search.group(1),
        user= user,
    )

    worker = wee_matter.websocket.create_worker(server)
    if not worker:
        weechat.prnt("", "An error occurred while creating the websocket worker")
        return weechat.WEECHAT_RC_ERROR
    reconnection_loop_hook = weechat.hook_timer(5 * 1000, 0, 0, "reconnection_loop_cb", server.name)

    server = server._replace(
        worker= worker,
        reconnection_loop_hook= reconnection_loop_hook,
    )
    servers[server_name] = server

    weechat.prnt("", "Connected to " + server_name)

    wee_matter.http.enqueue_request(
        "run_get_users",
        server, 0, "connect_server_users_cb", "{}|0".format(server.name)
    )

    return weechat.WEECHAT_RC_OK

def create_server_buffer(server_name):
    buffer = weechat.buffer_new("weematter." + server_name, "", "", "", "")
    weechat.buffer_set(buffer, "short_name", server_name)
    weechat.buffer_set(buffer, "localvar_set_server_name", server_name)
    weechat.buffer_set(buffer, "localvar_set_type", "server")
    weechat.buffer_set(buffer, "localvar_set_server", server_name)

    return buffer

def connect_server(server_name):
    if has_server(server_name):
        server = get_server(server_name)

        if server != None and is_connected(server):
            weechat.prnt("", "Already connected")
            return weechat.WEECHAT_RC_ERROR

        if server != None:
            unload_server(server_name)

    server = load_server(server_name)

    weechat.prnt("", "Connecting to " + server_name)

    buffer = create_server_buffer(server_name)

    server = get_server(server_name)._replace(
        buffer= buffer
    )
    servers[server_name] = server

    wee_matter.http.enqueue_request(
        "run_user_login",
        server, "connect_server_cb", server.name
    )

    return weechat.WEECHAT_RC_OK

def disconnect_server_cb(server_name, command, rc, out, err):
    if rc != 0:
        weechat.prnt("", "An error occurred while disconnecting")
        return weechat.WEECHAT_RC_ERROR

    unload_server(server_name)

    weechat.prnt("", "Disconnected")

    return weechat.WEECHAT_RC_OK

def disconnect_server(server_name):
    server = get_server(server_name)

    if not is_connected(server):
        weechat.prnt("", "Not connected")
        return weechat.WEECHAT_RC_ERROR

    wee_matter.http.run_user_logout(server, "disconnect_server_cb", server.name)

    return weechat.WEECHAT_RC_OK

def reconnect_server(server_name):
    server = get_server(server_name)

    if not is_connected(server):
        weechat.prnt("", "Not connected")
        return weechat.WEECHAT_RC_ERROR

    wee_matter.websocket.close_worker(server.worker)

    return weechat.WEECHAT_RC_OK

def auto_connect_servers():
    if not weechat.config_is_set_plugin("autoconnect"):
        weechat.config_set_plugin("autoconnect", "")

    auto_connect = weechat.config_get_plugin("autoconnect")
    return list(filter(bool, auto_connect.split(",")))

def auto_connect():
    for server_name in auto_connect_servers():
        connect_server(server_name)

def disconnect_all():
    for server_name, server in servers.items():
        disconnect_server(server_name)