slidge 0.1.0rc1__py3-none-any.whl → 0.1.2__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- slidge/__init__.py +54 -31
- slidge/__main__.py +51 -5
- slidge/command/__init__.py +28 -0
- slidge/command/adhoc.py +258 -0
- slidge/command/admin.py +193 -0
- slidge/command/base.py +441 -0
- slidge/command/categories.py +3 -0
- slidge/command/chat_command.py +288 -0
- slidge/command/register.py +179 -0
- slidge/command/user.py +250 -0
- slidge/contact/__init__.py +8 -0
- slidge/contact/contact.py +452 -0
- slidge/contact/roster.py +192 -0
- slidge/core/__init__.py +2 -0
- slidge/core/cache.py +121 -39
- slidge/core/config.py +116 -11
- slidge/core/gateway/__init__.py +3 -0
- slidge/core/gateway/base.py +895 -0
- slidge/core/gateway/caps.py +63 -0
- slidge/core/gateway/delivery_receipt.py +52 -0
- slidge/core/gateway/disco.py +80 -0
- slidge/core/gateway/mam.py +75 -0
- slidge/core/gateway/muc_admin.py +35 -0
- slidge/core/gateway/ping.py +66 -0
- slidge/core/gateway/presence.py +95 -0
- slidge/core/gateway/registration.py +53 -0
- slidge/core/gateway/search.py +102 -0
- slidge/core/gateway/session_dispatcher.py +795 -0
- slidge/core/gateway/vcard_temp.py +130 -0
- slidge/core/mixins/__init__.py +9 -1
- slidge/core/mixins/attachment.py +506 -0
- slidge/core/mixins/avatar.py +167 -0
- slidge/core/mixins/base.py +6 -19
- slidge/core/mixins/disco.py +66 -15
- slidge/core/mixins/lock.py +31 -0
- slidge/core/mixins/message.py +254 -252
- slidge/core/mixins/message_maker.py +154 -0
- slidge/core/mixins/presence.py +128 -31
- slidge/core/mixins/recipient.py +43 -0
- slidge/core/pubsub.py +275 -116
- slidge/core/session.py +586 -518
- slidge/group/__init__.py +10 -0
- slidge/group/archive.py +125 -0
- slidge/group/bookmarks.py +163 -0
- slidge/group/participant.py +458 -0
- slidge/group/room.py +1103 -0
- slidge/migration.py +18 -0
- slidge/slixfix/__init__.py +68 -0
- slidge/{util/xep_0050 → slixfix/link_preview}/__init__.py +4 -5
- slidge/slixfix/link_preview/link_preview.py +17 -0
- slidge/slixfix/link_preview/stanza.py +99 -0
- slidge/slixfix/roster.py +60 -0
- slidge/{util → slixfix}/xep_0077/register.py +1 -2
- slidge/slixfix/xep_0077/stanza.py +104 -0
- slidge/{util → slixfix}/xep_0100/gateway.py +17 -12
- slidge/slixfix/xep_0153/__init__.py +10 -0
- slidge/slixfix/xep_0153/stanza.py +25 -0
- slidge/slixfix/xep_0153/vcard_avatar.py +23 -0
- slidge/slixfix/xep_0264/__init__.py +5 -0
- slidge/slixfix/xep_0264/stanza.py +36 -0
- slidge/slixfix/xep_0264/thumbnail.py +23 -0
- slidge/slixfix/xep_0292/__init__.py +5 -0
- slidge/slixfix/xep_0292/vcard4.py +100 -0
- slidge/slixfix/xep_0313/__init__.py +12 -0
- slidge/slixfix/xep_0313/mam.py +262 -0
- slidge/slixfix/xep_0313/stanza.py +359 -0
- slidge/slixfix/xep_0317/__init__.py +5 -0
- slidge/slixfix/xep_0317/hats.py +17 -0
- slidge/slixfix/xep_0317/stanza.py +28 -0
- slidge/{util → slixfix}/xep_0356_old/privilege.py +9 -7
- slidge/slixfix/xep_0424/__init__.py +9 -0
- slidge/slixfix/xep_0424/retraction.py +77 -0
- slidge/slixfix/xep_0424/stanza.py +28 -0
- slidge/slixfix/xep_0490/__init__.py +8 -0
- slidge/slixfix/xep_0490/mds.py +47 -0
- slidge/slixfix/xep_0490/stanza.py +17 -0
- slidge/util/__init__.py +4 -6
- slidge/util/archive_msg.py +61 -0
- slidge/util/conf.py +25 -4
- slidge/util/db.py +23 -69
- slidge/util/schema.sql +126 -0
- slidge/util/sql.py +508 -0
- slidge/util/test.py +136 -86
- slidge/util/types.py +155 -14
- slidge/util/util.py +225 -51
- slidge-0.1.2.dist-info/METADATA +111 -0
- slidge-0.1.2.dist-info/RECORD +96 -0
- {slidge-0.1.0rc1.dist-info → slidge-0.1.2.dist-info}/WHEEL +1 -1
- slidge/core/adhoc.py +0 -492
- slidge/core/chat_command.py +0 -197
- slidge/core/contact.py +0 -441
- slidge/core/disco.py +0 -59
- slidge/core/gateway.py +0 -899
- slidge/core/muc/__init__.py +0 -3
- slidge/core/muc/bookmarks.py +0 -74
- slidge/core/muc/participant.py +0 -152
- slidge/core/muc/room.py +0 -348
- slidge/plugins/discord/__init__.py +0 -121
- slidge/plugins/discord/client.py +0 -121
- slidge/plugins/discord/session.py +0 -172
- slidge/plugins/dummy.py +0 -334
- slidge/plugins/facebook.py +0 -591
- slidge/plugins/hackernews.py +0 -209
- slidge/plugins/mattermost/__init__.py +0 -1
- slidge/plugins/mattermost/api.py +0 -288
- slidge/plugins/mattermost/gateway.py +0 -417
- slidge/plugins/mattermost/websocket.py +0 -248
- slidge/plugins/signal/__init__.py +0 -4
- slidge/plugins/signal/config.py +0 -4
- slidge/plugins/signal/contact.py +0 -104
- slidge/plugins/signal/gateway.py +0 -379
- slidge/plugins/signal/group.py +0 -76
- slidge/plugins/signal/session.py +0 -515
- slidge/plugins/signal/txt.py +0 -13
- slidge/plugins/signal/util.py +0 -32
- slidge/plugins/skype.py +0 -310
- slidge/plugins/steam.py +0 -400
- slidge/plugins/telegram/__init__.py +0 -6
- slidge/plugins/telegram/client.py +0 -325
- slidge/plugins/telegram/config.py +0 -21
- slidge/plugins/telegram/contact.py +0 -154
- slidge/plugins/telegram/gateway.py +0 -182
- slidge/plugins/telegram/group.py +0 -184
- slidge/plugins/telegram/session.py +0 -275
- slidge/plugins/telegram/util.py +0 -153
- slidge/plugins/whatsapp/__init__.py +0 -6
- slidge/plugins/whatsapp/config.py +0 -17
- slidge/plugins/whatsapp/contact.py +0 -33
- slidge/plugins/whatsapp/event.go +0 -455
- slidge/plugins/whatsapp/gateway.go +0 -156
- slidge/plugins/whatsapp/gateway.py +0 -69
- slidge/plugins/whatsapp/go.mod +0 -17
- slidge/plugins/whatsapp/go.sum +0 -22
- slidge/plugins/whatsapp/session.go +0 -371
- slidge/plugins/whatsapp/session.py +0 -370
- slidge/util/xep_0030/__init__.py +0 -13
- slidge/util/xep_0030/disco.py +0 -811
- slidge/util/xep_0030/stanza/__init__.py +0 -7
- slidge/util/xep_0030/stanza/info.py +0 -270
- slidge/util/xep_0030/stanza/items.py +0 -147
- slidge/util/xep_0030/static.py +0 -467
- slidge/util/xep_0050/adhoc.py +0 -631
- slidge/util/xep_0050/stanza.py +0 -180
- slidge/util/xep_0077/stanza.py +0 -71
- slidge/util/xep_0292/__init__.py +0 -1
- slidge/util/xep_0292/stanza.py +0 -167
- slidge/util/xep_0292/vcard4.py +0 -74
- slidge/util/xep_0356/__init__.py +0 -7
- slidge/util/xep_0356/permissions.py +0 -35
- slidge/util/xep_0356/privilege.py +0 -160
- slidge/util/xep_0356/stanza.py +0 -44
- slidge/util/xep_0461/__init__.py +0 -6
- slidge/util/xep_0461/reply.py +0 -48
- slidge/util/xep_0461/stanza.py +0 -80
- slidge-0.1.0rc1.dist-info/METADATA +0 -171
- slidge-0.1.0rc1.dist-info/RECORD +0 -99
- /slidge/{plugins/__init__.py → py.typed} +0 -0
- /slidge/{util → slixfix}/xep_0077/__init__.py +0 -0
- /slidge/{util → slixfix}/xep_0100/__init__.py +0 -0
- /slidge/{util → slixfix}/xep_0100/stanza.py +0 -0
- /slidge/{util → slixfix}/xep_0356_old/__init__.py +0 -0
- /slidge/{util → slixfix}/xep_0356_old/stanza.py +0 -0
- {slidge-0.1.0rc1.dist-info → slidge-0.1.2.dist-info}/LICENSE +0 -0
- {slidge-0.1.0rc1.dist-info → slidge-0.1.2.dist-info}/entry_points.txt +0 -0
slidge/__init__.py
CHANGED
@@ -1,38 +1,61 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
1
|
+
"""
|
2
|
+
The main slidge package.
|
3
|
+
|
4
|
+
Contains importable classes for a minimal function :term:`Legacy Module`.
|
5
|
+
"""
|
6
|
+
|
7
|
+
import sys
|
8
|
+
import warnings
|
9
|
+
|
10
|
+
from . import slixfix # noqa: F401
|
11
|
+
from .command import FormField, SearchResult # noqa: F401
|
12
|
+
from .contact import LegacyContact, LegacyRoster # noqa: F401
|
13
|
+
from .core import config as global_config # noqa: F401
|
14
|
+
from .core.gateway import BaseGateway # noqa: F401
|
15
|
+
from .core.session import BaseSession # noqa: F401
|
16
|
+
from .group import LegacyBookmarks, LegacyMUC, LegacyParticipant # noqa: F401
|
17
|
+
from .util.db import GatewayUser, user_store # noqa: F401
|
18
|
+
from .util.types import MucType # noqa: F401
|
19
|
+
from .util.util import addLoggingLevel
|
20
|
+
|
21
|
+
from .__main__ import main # isort: skip
|
22
|
+
|
23
|
+
|
24
|
+
def entrypoint(module_name: str) -> None:
|
25
|
+
"""
|
26
|
+
Entrypoint to be used in ``__main__.py`` of
|
27
|
+
:term:`legacy modules <Legacy Module>`.
|
28
|
+
|
29
|
+
:param module_name: An importable :term:`Legacy Module`.
|
30
|
+
"""
|
31
|
+
sys.argv.extend(["--legacy", module_name])
|
32
|
+
main()
|
33
|
+
|
34
|
+
|
35
|
+
def formatwarning(message, category, filename, lineno, line=""):
|
36
|
+
return f"{filename}:{lineno}:{category.__name__}:{message}\n"
|
37
|
+
|
38
|
+
|
39
|
+
warnings.formatwarning = formatwarning
|
40
|
+
|
23
41
|
|
24
42
|
__all__ = [
|
25
43
|
"BaseGateway",
|
26
44
|
"BaseSession",
|
27
|
-
|
28
|
-
|
29
|
-
"
|
30
|
-
"
|
31
|
-
"
|
32
|
-
"
|
33
|
-
"
|
34
|
-
"
|
35
|
-
"
|
45
|
+
# For backwards compatibility, these names are still importable from the
|
46
|
+
# top-level slidge module, but this is deprecated.
|
47
|
+
# "GatewayUser",
|
48
|
+
# "LegacyBookmarks",
|
49
|
+
# "LegacyMUC",
|
50
|
+
# "LegacyContact",
|
51
|
+
# "LegacyParticipant",
|
52
|
+
# "LegacyRoster",
|
53
|
+
# "MucType",
|
54
|
+
# "FormField",
|
55
|
+
# "SearchResult",
|
56
|
+
"entrypoint",
|
36
57
|
"user_store",
|
37
58
|
"global_config",
|
38
59
|
]
|
60
|
+
|
61
|
+
addLoggingLevel()
|
slidge/__main__.py
CHANGED
@@ -1,9 +1,22 @@
|
|
1
1
|
"""
|
2
2
|
Slidge can be configured via CLI args, environment variables and/or INI files.
|
3
|
+
|
3
4
|
To use env vars, use this convention: ``--home-dir`` becomes ``HOME_DIR``.
|
5
|
+
|
6
|
+
Everything in ``/etc/slidge/conf.d/*`` is automatically used.
|
7
|
+
To use a plugin-specific INI file, put it in another dir,
|
8
|
+
and launch slidge with ``-c /path/to/plugin-specific.conf``.
|
9
|
+
Use the long version of the CLI arg without the double dash prefix inside this
|
10
|
+
INI file, eg ``debug=true``.
|
11
|
+
|
12
|
+
An example configuration file is available at
|
13
|
+
https://git.sr.ht/~nicoco/slidge/tree/master/item/dev/confs/slidge-example.ini
|
4
14
|
"""
|
15
|
+
|
16
|
+
import asyncio
|
5
17
|
import importlib
|
6
18
|
import logging
|
19
|
+
import os
|
7
20
|
import signal
|
8
21
|
from pathlib import Path
|
9
22
|
|
@@ -12,13 +25,22 @@ import configargparse
|
|
12
25
|
from slidge import BaseGateway
|
13
26
|
from slidge.core import config
|
14
27
|
from slidge.core.cache import avatar_cache
|
28
|
+
from slidge.migration import migrate
|
15
29
|
from slidge.util.conf import ConfigModule
|
16
30
|
from slidge.util.db import user_store
|
31
|
+
from slidge.util.util import get_version # noqa: F401
|
17
32
|
|
18
33
|
|
19
34
|
class MainConfig(ConfigModule):
|
20
35
|
def update_dynamic_defaults(self, args):
|
21
|
-
|
36
|
+
# force=True is needed in case we call a logger before this is reached,
|
37
|
+
# or basicConfig has no effect
|
38
|
+
logging.basicConfig(
|
39
|
+
level=args.loglevel,
|
40
|
+
filename=args.log_file,
|
41
|
+
force=True,
|
42
|
+
format=args.log_format,
|
43
|
+
)
|
22
44
|
|
23
45
|
if args.home_dir is None:
|
24
46
|
args.home_dir = Path("/var/lib/slidge") / str(args.jid)
|
@@ -33,7 +55,10 @@ class SigTermInterrupt(Exception):
|
|
33
55
|
|
34
56
|
def get_configurator():
|
35
57
|
p = configargparse.ArgumentParser(
|
36
|
-
default_config_files=
|
58
|
+
default_config_files=os.getenv(
|
59
|
+
"SLIDGE_CONF_DIR", "/etc/slidge/conf.d/*.conf"
|
60
|
+
).split(":"),
|
61
|
+
description=__doc__,
|
37
62
|
)
|
38
63
|
p.add_argument(
|
39
64
|
"-c",
|
@@ -61,6 +86,11 @@ def get_configurator():
|
|
61
86
|
const=logging.DEBUG,
|
62
87
|
env_var="SLIDGE_DEBUG",
|
63
88
|
)
|
89
|
+
p.add_argument(
|
90
|
+
"--version",
|
91
|
+
action="version",
|
92
|
+
version=f"%(prog)s {__version__}",
|
93
|
+
)
|
64
94
|
configurator = MainConfig(config, p)
|
65
95
|
return configurator
|
66
96
|
|
@@ -80,7 +110,7 @@ def configure():
|
|
80
110
|
db_file = config.HOME_DIR / "slidge.db"
|
81
111
|
user_store.set_file(db_file, args.secret_key)
|
82
112
|
|
83
|
-
avatar_cache.set_dir(h / "
|
113
|
+
avatar_cache.set_dir(h / "slidge_avatars_v2")
|
84
114
|
|
85
115
|
config.UPLOAD_REQUESTER = config.UPLOAD_REQUESTER or config.JID.bare
|
86
116
|
|
@@ -96,8 +126,15 @@ def main():
|
|
96
126
|
signal.signal(signal.SIGTERM, handle_sigterm)
|
97
127
|
|
98
128
|
unknown_argv = configure()
|
129
|
+
logging.info("Starting slidge version %s", __version__)
|
99
130
|
|
100
131
|
legacy_module = importlib.import_module(config.LEGACY_MODULE)
|
132
|
+
logging.debug("Legacy module: %s", dir(legacy_module))
|
133
|
+
logging.info(
|
134
|
+
"Starting legacy module: '%s' version %s",
|
135
|
+
config.LEGACY_MODULE,
|
136
|
+
getattr(legacy_module, "__version__", "No version"),
|
137
|
+
)
|
101
138
|
|
102
139
|
if plugin_config_obj := getattr(
|
103
140
|
legacy_module, "config", getattr(legacy_module, "Config", None)
|
@@ -112,7 +149,10 @@ def main():
|
|
112
149
|
if unknown_argv:
|
113
150
|
raise RuntimeError("Some arguments have not been recognized", unknown_argv)
|
114
151
|
|
115
|
-
|
152
|
+
migrate()
|
153
|
+
|
154
|
+
gateway: BaseGateway = BaseGateway.get_unique_subclass()()
|
155
|
+
avatar_cache.http = gateway.http
|
116
156
|
gateway.connect()
|
117
157
|
|
118
158
|
return_code = 0
|
@@ -136,17 +176,23 @@ def main():
|
|
136
176
|
return_code = 3
|
137
177
|
if gateway.is_connected():
|
138
178
|
logging.debug("Gateway is connected, cleaning up")
|
139
|
-
gateway.shutdown()
|
179
|
+
gateway.loop.run_until_complete(asyncio.gather(*gateway.shutdown()))
|
140
180
|
gateway.disconnect()
|
141
181
|
gateway.loop.run_until_complete(gateway.disconnected)
|
142
182
|
else:
|
143
183
|
logging.debug("Gateway is not connected, no need to clean up")
|
144
184
|
user_store.close()
|
145
185
|
avatar_cache.close()
|
186
|
+
gateway.loop.run_until_complete(gateway.http.close())
|
146
187
|
logging.info("Successful clean shut down")
|
147
188
|
logging.debug("Exiting with code %s", return_code)
|
148
189
|
exit(return_code)
|
149
190
|
|
150
191
|
|
192
|
+
# this should be modified before publish, but if someone cloned from the repo,
|
193
|
+
# it can help
|
194
|
+
__version__ = get_version()
|
195
|
+
|
196
|
+
|
151
197
|
if __name__ == "__main__":
|
152
198
|
main()
|
@@ -0,0 +1,28 @@
|
|
1
|
+
"""
|
2
|
+
This module implements an unified API to define :term:`adhoc <Ad-hoc Command>`
|
3
|
+
or :term:`chatbot <Chatbot Command>` commands. Just subclass a :class:`Command`,
|
4
|
+
and make sures it is imported in your legacy module's ``__init__.py``.
|
5
|
+
"""
|
6
|
+
|
7
|
+
from . import admin, register, user # noqa: F401
|
8
|
+
from .base import (
|
9
|
+
Command,
|
10
|
+
CommandAccess,
|
11
|
+
CommandResponseType,
|
12
|
+
Confirmation,
|
13
|
+
Form,
|
14
|
+
FormField,
|
15
|
+
SearchResult,
|
16
|
+
TableResult,
|
17
|
+
)
|
18
|
+
|
19
|
+
__all__ = (
|
20
|
+
"Command",
|
21
|
+
"CommandAccess",
|
22
|
+
"CommandResponseType",
|
23
|
+
"Confirmation",
|
24
|
+
"Form",
|
25
|
+
"FormField",
|
26
|
+
"SearchResult",
|
27
|
+
"TableResult",
|
28
|
+
)
|
slidge/command/adhoc.py
ADDED
@@ -0,0 +1,258 @@
|
|
1
|
+
import asyncio
|
2
|
+
import functools
|
3
|
+
import logging
|
4
|
+
from functools import partial
|
5
|
+
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
|
6
|
+
|
7
|
+
from slixmpp import JID, Iq # type: ignore[attr-defined]
|
8
|
+
from slixmpp.exceptions import XMPPError
|
9
|
+
from slixmpp.plugins.xep_0004 import Form as SlixForm # type: ignore[attr-defined]
|
10
|
+
from slixmpp.plugins.xep_0030.stanza.items import DiscoItems
|
11
|
+
|
12
|
+
from . import Command, CommandResponseType, Confirmation, Form, TableResult
|
13
|
+
from .base import FormField
|
14
|
+
|
15
|
+
if TYPE_CHECKING:
|
16
|
+
from ..core.gateway.base import BaseGateway
|
17
|
+
from ..core.session import BaseSession
|
18
|
+
|
19
|
+
|
20
|
+
AdhocSessionType = dict[str, Any]
|
21
|
+
|
22
|
+
|
23
|
+
class AdhocProvider:
|
24
|
+
"""
|
25
|
+
A slixmpp-like plugin to handle adhoc commands, with less boilerplate and
|
26
|
+
untyped dict values than slixmpp.
|
27
|
+
"""
|
28
|
+
|
29
|
+
def __init__(self, xmpp: "BaseGateway") -> None:
|
30
|
+
self.xmpp = xmpp
|
31
|
+
self._commands = dict[str, Command]()
|
32
|
+
self._categories = dict[str, list[Command]]()
|
33
|
+
xmpp.plugin["xep_0030"].set_node_handler(
|
34
|
+
"get_items",
|
35
|
+
jid=xmpp.boundjid,
|
36
|
+
node=self.xmpp.plugin["xep_0050"].stanza.Command.namespace,
|
37
|
+
handler=self.get_items,
|
38
|
+
)
|
39
|
+
|
40
|
+
async def __wrap_initial_handler(
|
41
|
+
self, command: Command, iq: Iq, adhoc_session: AdhocSessionType
|
42
|
+
) -> AdhocSessionType:
|
43
|
+
ifrom = iq.get_from()
|
44
|
+
session = command.raise_if_not_authorized(ifrom)
|
45
|
+
result = await self.__wrap_handler(command.run, session, ifrom)
|
46
|
+
return await self.__handle_result(session, result, adhoc_session)
|
47
|
+
|
48
|
+
async def __handle_category_list(
|
49
|
+
self, category: str, iq: Iq, adhoc_session: AdhocSessionType
|
50
|
+
) -> AdhocSessionType:
|
51
|
+
session = self.xmpp.get_session_from_stanza(iq)
|
52
|
+
commands = []
|
53
|
+
for command in self._categories[category]:
|
54
|
+
try:
|
55
|
+
command.raise_if_not_authorized(iq.get_from())
|
56
|
+
except XMPPError:
|
57
|
+
continue
|
58
|
+
commands.append(command)
|
59
|
+
return await self.__handle_result(
|
60
|
+
session,
|
61
|
+
Form(
|
62
|
+
category,
|
63
|
+
"",
|
64
|
+
[
|
65
|
+
FormField(
|
66
|
+
var="command",
|
67
|
+
label="Command",
|
68
|
+
type="list-single",
|
69
|
+
options=[
|
70
|
+
{"label": command.NAME, "value": str(i)}
|
71
|
+
for i, command in enumerate(commands)
|
72
|
+
],
|
73
|
+
)
|
74
|
+
],
|
75
|
+
partial(self.__handle_category_choice, commands),
|
76
|
+
),
|
77
|
+
adhoc_session,
|
78
|
+
)
|
79
|
+
|
80
|
+
async def __handle_category_choice(
|
81
|
+
self,
|
82
|
+
commands: list[Command],
|
83
|
+
form_values: dict[str, str],
|
84
|
+
session: "BaseSession[Any, Any]",
|
85
|
+
jid: JID,
|
86
|
+
):
|
87
|
+
command = commands[int(form_values["command"])]
|
88
|
+
result = await self.__wrap_handler(command.run, session, jid)
|
89
|
+
return result
|
90
|
+
|
91
|
+
async def __handle_result(
|
92
|
+
self,
|
93
|
+
session: Optional["BaseSession[Any, Any]"],
|
94
|
+
result: CommandResponseType,
|
95
|
+
adhoc_session: AdhocSessionType,
|
96
|
+
) -> AdhocSessionType:
|
97
|
+
if isinstance(result, str) or result is None:
|
98
|
+
adhoc_session["has_next"] = False
|
99
|
+
adhoc_session["next"] = None
|
100
|
+
adhoc_session["payload"] = None
|
101
|
+
adhoc_session["notes"] = [("info", result or "Success!")]
|
102
|
+
return adhoc_session
|
103
|
+
|
104
|
+
if isinstance(result, Form):
|
105
|
+
adhoc_session["next"] = partial(self.__wrap_form_handler, session, result)
|
106
|
+
adhoc_session["has_next"] = True
|
107
|
+
adhoc_session["payload"] = result.get_xml()
|
108
|
+
return adhoc_session
|
109
|
+
|
110
|
+
if isinstance(result, Confirmation):
|
111
|
+
adhoc_session["next"] = partial(self.__wrap_confirmation, session, result)
|
112
|
+
adhoc_session["has_next"] = True
|
113
|
+
adhoc_session["payload"] = result.get_form()
|
114
|
+
adhoc_session["next"] = partial(self.__wrap_confirmation, session, result)
|
115
|
+
return adhoc_session
|
116
|
+
|
117
|
+
if isinstance(result, TableResult):
|
118
|
+
adhoc_session["next"] = None
|
119
|
+
adhoc_session["has_next"] = False
|
120
|
+
adhoc_session["payload"] = result.get_xml()
|
121
|
+
return adhoc_session
|
122
|
+
|
123
|
+
raise XMPPError("internal-server-error", text="OOPS!")
|
124
|
+
|
125
|
+
@staticmethod
|
126
|
+
async def __wrap_handler(f: Union[Callable, functools.partial], *a, **k): # type: ignore
|
127
|
+
try:
|
128
|
+
if asyncio.iscoroutinefunction(f):
|
129
|
+
return await f(*a, **k)
|
130
|
+
elif hasattr(f, "func") and asyncio.iscoroutinefunction(f.func):
|
131
|
+
return await f(*a, **k)
|
132
|
+
else:
|
133
|
+
return f(*a, **k)
|
134
|
+
except Exception as e:
|
135
|
+
log.debug("Exception in %s", f, exc_info=e)
|
136
|
+
raise XMPPError("internal-server-error", text=str(e))
|
137
|
+
|
138
|
+
async def __wrap_form_handler(
|
139
|
+
self,
|
140
|
+
session: Optional["BaseSession[Any, Any]"],
|
141
|
+
result: Form,
|
142
|
+
form: SlixForm,
|
143
|
+
adhoc_session: AdhocSessionType,
|
144
|
+
) -> AdhocSessionType:
|
145
|
+
form_values = result.get_values(form)
|
146
|
+
new_result = await self.__wrap_handler(
|
147
|
+
result.handler,
|
148
|
+
form_values,
|
149
|
+
session,
|
150
|
+
adhoc_session["from"],
|
151
|
+
*result.handler_args,
|
152
|
+
**result.handler_kwargs,
|
153
|
+
)
|
154
|
+
|
155
|
+
return await self.__handle_result(session, new_result, adhoc_session)
|
156
|
+
|
157
|
+
async def __wrap_confirmation(
|
158
|
+
self,
|
159
|
+
session: Optional["BaseSession[Any, Any]"],
|
160
|
+
confirmation: Confirmation,
|
161
|
+
form: SlixForm,
|
162
|
+
adhoc_session: AdhocSessionType,
|
163
|
+
) -> AdhocSessionType:
|
164
|
+
if form.get_values().get("confirm"): # type: ignore[no-untyped-call]
|
165
|
+
result = await self.__wrap_handler(
|
166
|
+
confirmation.handler,
|
167
|
+
session,
|
168
|
+
adhoc_session["from"],
|
169
|
+
*confirmation.handler_args,
|
170
|
+
**confirmation.handler_kwargs,
|
171
|
+
)
|
172
|
+
if confirmation.success:
|
173
|
+
result = confirmation.success
|
174
|
+
else:
|
175
|
+
result = "You canceled the operation"
|
176
|
+
|
177
|
+
return await self.__handle_result(session, result, adhoc_session)
|
178
|
+
|
179
|
+
def register(self, command: Command, jid: Optional[JID] = None) -> None:
|
180
|
+
"""
|
181
|
+
Register a command as a adhoc command.
|
182
|
+
|
183
|
+
this does not need to be called manually, ``BaseGateway`` takes care of
|
184
|
+
that.
|
185
|
+
|
186
|
+
:param command:
|
187
|
+
:param jid:
|
188
|
+
"""
|
189
|
+
if jid is None:
|
190
|
+
jid = self.xmpp.boundjid
|
191
|
+
elif not isinstance(jid, JID):
|
192
|
+
jid = JID(jid)
|
193
|
+
|
194
|
+
if (category := command.CATEGORY) is None:
|
195
|
+
if command.NODE in self._commands:
|
196
|
+
raise RuntimeError(
|
197
|
+
"There is already a command for the node '%s'", command.NODE
|
198
|
+
)
|
199
|
+
self._commands[command.NODE] = command
|
200
|
+
self.xmpp.plugin["xep_0050"].add_command( # type: ignore[no-untyped-call]
|
201
|
+
jid=jid,
|
202
|
+
node=command.NODE,
|
203
|
+
name=command.NAME,
|
204
|
+
handler=partial(self.__wrap_initial_handler, command),
|
205
|
+
)
|
206
|
+
else:
|
207
|
+
if category not in self._categories:
|
208
|
+
self._categories[category] = list[Command]()
|
209
|
+
self.xmpp.plugin["xep_0050"].add_command( # type: ignore[no-untyped-call]
|
210
|
+
jid=jid,
|
211
|
+
node=category,
|
212
|
+
name=category,
|
213
|
+
handler=partial(self.__handle_category_list, category),
|
214
|
+
)
|
215
|
+
self._categories[category].append(command)
|
216
|
+
|
217
|
+
async def get_items(self, jid: JID, node: str, iq: Iq) -> DiscoItems:
|
218
|
+
"""
|
219
|
+
Get items for a disco query
|
220
|
+
|
221
|
+
:param jid: who is requesting the disco
|
222
|
+
:param node: which command node is requested
|
223
|
+
:param iq: the disco query IQ
|
224
|
+
:return: commands accessible to the given JID will be listed
|
225
|
+
"""
|
226
|
+
all_items = self.xmpp.plugin["xep_0030"].static.get_items(jid, node, None, None)
|
227
|
+
log.debug("Static items: %r", all_items)
|
228
|
+
if not all_items:
|
229
|
+
return DiscoItems()
|
230
|
+
|
231
|
+
ifrom = iq.get_from()
|
232
|
+
|
233
|
+
filtered_items = DiscoItems()
|
234
|
+
filtered_items["node"] = self.xmpp.plugin["xep_0050"].stanza.Command.namespace
|
235
|
+
for item in all_items:
|
236
|
+
authorized = True
|
237
|
+
if item["node"] in self._categories:
|
238
|
+
for command in self._categories[item["node"]]:
|
239
|
+
try:
|
240
|
+
command.raise_if_not_authorized(ifrom)
|
241
|
+
except XMPPError:
|
242
|
+
authorized = False
|
243
|
+
else:
|
244
|
+
authorized = True
|
245
|
+
break
|
246
|
+
else:
|
247
|
+
try:
|
248
|
+
self._commands[item["node"]].raise_if_not_authorized(ifrom)
|
249
|
+
except XMPPError:
|
250
|
+
authorized = False
|
251
|
+
|
252
|
+
if authorized:
|
253
|
+
filtered_items.append(item)
|
254
|
+
|
255
|
+
return filtered_items
|
256
|
+
|
257
|
+
|
258
|
+
log = logging.getLogger(__name__)
|
slidge/command/admin.py
ADDED
@@ -0,0 +1,193 @@
|
|
1
|
+
# Commands only accessible for slidge admins
|
2
|
+
import functools
|
3
|
+
import logging
|
4
|
+
from datetime import datetime
|
5
|
+
from typing import Any, Optional
|
6
|
+
|
7
|
+
from slixmpp import JID
|
8
|
+
from slixmpp.exceptions import XMPPError
|
9
|
+
|
10
|
+
from ..util.db import user_store
|
11
|
+
from ..util.types import AnyBaseSession
|
12
|
+
from .base import (
|
13
|
+
Command,
|
14
|
+
CommandAccess,
|
15
|
+
Confirmation,
|
16
|
+
Form,
|
17
|
+
FormField,
|
18
|
+
FormValues,
|
19
|
+
TableResult,
|
20
|
+
)
|
21
|
+
from .categories import ADMINISTRATION
|
22
|
+
|
23
|
+
|
24
|
+
class AdminCommand(Command):
|
25
|
+
ACCESS = CommandAccess.ADMIN_ONLY
|
26
|
+
CATEGORY = ADMINISTRATION
|
27
|
+
|
28
|
+
|
29
|
+
class ListUsers(AdminCommand):
|
30
|
+
NAME = "👤 List registered users"
|
31
|
+
HELP = "List the users registered to this gateway"
|
32
|
+
NODE = CHAT_COMMAND = "list_users"
|
33
|
+
|
34
|
+
async def run(self, _session, _ifrom, *_):
|
35
|
+
items = []
|
36
|
+
for u in user_store.get_all():
|
37
|
+
d = u.registration_date
|
38
|
+
if d is None:
|
39
|
+
joined = ""
|
40
|
+
else:
|
41
|
+
joined = d.isoformat(timespec="seconds")
|
42
|
+
items.append({"jid": u.bare_jid, "joined": joined})
|
43
|
+
return TableResult(
|
44
|
+
description="List of registered users",
|
45
|
+
fields=[FormField("jid", type="jid-single"), FormField("joined")],
|
46
|
+
items=items, # type:ignore
|
47
|
+
)
|
48
|
+
|
49
|
+
|
50
|
+
class SlidgeInfo(AdminCommand):
|
51
|
+
NAME = "ℹ️ Server information"
|
52
|
+
HELP = "List the users registered to this gateway"
|
53
|
+
NODE = CHAT_COMMAND = "info"
|
54
|
+
ACCESS = CommandAccess.ANY
|
55
|
+
|
56
|
+
async def run(self, _session, _ifrom, *_):
|
57
|
+
from ..__main__ import __version__
|
58
|
+
|
59
|
+
start = self.xmpp.datetime_started
|
60
|
+
uptime = datetime.now() - start
|
61
|
+
|
62
|
+
if uptime.days:
|
63
|
+
days_ago = f"{uptime.days} day{'s' if uptime.days != 1 else ''}"
|
64
|
+
else:
|
65
|
+
days_ago = None
|
66
|
+
hours, seconds = divmod(uptime.seconds, 3600)
|
67
|
+
|
68
|
+
if hours:
|
69
|
+
hours_ago = f"{hours} hour"
|
70
|
+
if hours != 1:
|
71
|
+
hours_ago += "s"
|
72
|
+
else:
|
73
|
+
hours_ago = None
|
74
|
+
|
75
|
+
minutes, seconds = divmod(seconds, 60)
|
76
|
+
if minutes:
|
77
|
+
minutes_ago = f"{minutes} minute"
|
78
|
+
if minutes_ago != 1:
|
79
|
+
minutes_ago += "s"
|
80
|
+
else:
|
81
|
+
minutes_ago = None
|
82
|
+
|
83
|
+
if any((days_ago, hours_ago, minutes_ago)):
|
84
|
+
seconds_ago = None
|
85
|
+
else:
|
86
|
+
seconds_ago = f"{seconds} second"
|
87
|
+
if seconds != 1:
|
88
|
+
seconds_ago += "s"
|
89
|
+
|
90
|
+
ago = ", ".join(
|
91
|
+
[a for a in (days_ago, hours_ago, minutes_ago, seconds_ago) if a]
|
92
|
+
)
|
93
|
+
|
94
|
+
return (
|
95
|
+
f"{self.xmpp.COMPONENT_NAME} version {__version__}\n"
|
96
|
+
f"Up since {start:%Y-%m-%d %H:%M} ({ago} ago)"
|
97
|
+
)
|
98
|
+
|
99
|
+
|
100
|
+
class DeleteUser(AdminCommand):
|
101
|
+
NAME = "❌ Delete a user"
|
102
|
+
HELP = "Unregister a user from the gateway"
|
103
|
+
NODE = CHAT_COMMAND = "delete_user"
|
104
|
+
|
105
|
+
async def run(self, _session, _ifrom, *_):
|
106
|
+
return Form(
|
107
|
+
title="Remove a slidge user",
|
108
|
+
instructions="Enter the bare JID of the user you want to delete",
|
109
|
+
fields=[FormField("jid", type="jid-single", label="JID", required=True)],
|
110
|
+
handler=self.delete,
|
111
|
+
)
|
112
|
+
|
113
|
+
async def delete(
|
114
|
+
self, form_values: FormValues, _session: AnyBaseSession, _ifrom: JID
|
115
|
+
) -> Confirmation:
|
116
|
+
jid: JID = form_values.get("jid") # type:ignore
|
117
|
+
user = user_store.get_by_jid(jid)
|
118
|
+
if user is None:
|
119
|
+
raise XMPPError("item-not-found", text=f"There is no user '{jid}'")
|
120
|
+
|
121
|
+
return Confirmation(
|
122
|
+
prompt=f"Are you sure you want to unregister '{jid}' from slidge?",
|
123
|
+
success=f"User {jid} has been deleted",
|
124
|
+
handler=functools.partial(self.finish, jid=jid),
|
125
|
+
)
|
126
|
+
|
127
|
+
async def finish(
|
128
|
+
self, _session: Optional[AnyBaseSession], _ifrom: JID, jid: JID
|
129
|
+
) -> None:
|
130
|
+
user = user_store.get_by_jid(jid)
|
131
|
+
if user is None:
|
132
|
+
raise XMPPError("bad-request", f"{jid} has no account here!")
|
133
|
+
await self.xmpp.unregister_user(user)
|
134
|
+
|
135
|
+
|
136
|
+
class ChangeLoglevel(AdminCommand):
|
137
|
+
NAME = "📋 Change the verbosity of the logs"
|
138
|
+
HELP = "Set the logging level"
|
139
|
+
NODE = CHAT_COMMAND = "loglevel"
|
140
|
+
|
141
|
+
async def run(self, _session, _ifrom, *_):
|
142
|
+
return Form(
|
143
|
+
title=self.NAME,
|
144
|
+
instructions=self.HELP,
|
145
|
+
fields=[
|
146
|
+
FormField(
|
147
|
+
"level",
|
148
|
+
label="Log level",
|
149
|
+
required=True,
|
150
|
+
type="list-single",
|
151
|
+
options=[
|
152
|
+
{"label": "WARNING (quiet)", "value": str(logging.WARNING)},
|
153
|
+
{"label": "INFO (normal)", "value": str(logging.INFO)},
|
154
|
+
{"label": "DEBUG (verbose)", "value": str(logging.DEBUG)},
|
155
|
+
],
|
156
|
+
)
|
157
|
+
],
|
158
|
+
handler=self.finish,
|
159
|
+
)
|
160
|
+
|
161
|
+
@staticmethod
|
162
|
+
async def finish(
|
163
|
+
form_values: FormValues, _session: AnyBaseSession, _ifrom: JID
|
164
|
+
) -> None:
|
165
|
+
logging.getLogger().setLevel(int(form_values["level"])) # type:ignore
|
166
|
+
|
167
|
+
|
168
|
+
class Exec(AdminCommand):
|
169
|
+
NAME = HELP = "Exec arbitrary python code. SHOULD NEVER BE AVAILABLE IN PROD."
|
170
|
+
CHAT_COMMAND = "!"
|
171
|
+
NODE = "exec"
|
172
|
+
ACCESS = CommandAccess.ADMIN_ONLY
|
173
|
+
|
174
|
+
prev_snapshot = None
|
175
|
+
|
176
|
+
context = dict[str, Any]()
|
177
|
+
|
178
|
+
def __init__(self, xmpp):
|
179
|
+
super().__init__(xmpp)
|
180
|
+
|
181
|
+
async def run(self, session, ifrom: JID, *args):
|
182
|
+
from contextlib import redirect_stdout
|
183
|
+
from io import StringIO
|
184
|
+
|
185
|
+
f = StringIO()
|
186
|
+
with redirect_stdout(f):
|
187
|
+
exec(" ".join(args), self.context)
|
188
|
+
|
189
|
+
out = f.getvalue()
|
190
|
+
if out:
|
191
|
+
return f"```\n{out}\n```"
|
192
|
+
else:
|
193
|
+
return "No output"
|