slidge 0.1.0b2__py3-none-any.whl → 0.1.1__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (155) hide show
  1. slidge/__init__.py +55 -31
  2. slidge/__main__.py +118 -116
  3. slidge/command/__init__.py +28 -0
  4. slidge/command/adhoc.py +258 -0
  5. slidge/command/admin.py +193 -0
  6. slidge/command/base.py +441 -0
  7. slidge/command/categories.py +3 -0
  8. slidge/command/chat_command.py +288 -0
  9. slidge/command/register.py +179 -0
  10. slidge/command/user.py +250 -0
  11. slidge/contact/__init__.py +8 -0
  12. slidge/contact/contact.py +452 -0
  13. slidge/contact/roster.py +192 -0
  14. slidge/core/__init__.py +2 -0
  15. slidge/core/cache.py +183 -0
  16. slidge/core/config.py +216 -0
  17. slidge/core/gateway/__init__.py +3 -0
  18. slidge/core/gateway/base.py +895 -0
  19. slidge/core/gateway/caps.py +63 -0
  20. slidge/core/gateway/delivery_receipt.py +52 -0
  21. slidge/core/gateway/disco.py +80 -0
  22. slidge/core/gateway/mam.py +75 -0
  23. slidge/core/gateway/muc_admin.py +35 -0
  24. slidge/core/gateway/ping.py +66 -0
  25. slidge/core/gateway/presence.py +95 -0
  26. slidge/core/gateway/registration.py +53 -0
  27. slidge/core/gateway/search.py +102 -0
  28. slidge/core/gateway/session_dispatcher.py +789 -0
  29. slidge/core/gateway/vcard_temp.py +130 -0
  30. slidge/core/mixins/__init__.py +19 -0
  31. slidge/core/mixins/attachment.py +506 -0
  32. slidge/core/mixins/avatar.py +167 -0
  33. slidge/core/mixins/base.py +31 -0
  34. slidge/core/mixins/disco.py +130 -0
  35. slidge/core/mixins/lock.py +31 -0
  36. slidge/core/mixins/message.py +398 -0
  37. slidge/core/mixins/message_maker.py +154 -0
  38. slidge/core/mixins/presence.py +217 -0
  39. slidge/core/mixins/recipient.py +43 -0
  40. slidge/core/pubsub.py +282 -116
  41. slidge/core/session.py +595 -372
  42. slidge/group/__init__.py +10 -0
  43. slidge/group/archive.py +125 -0
  44. slidge/group/bookmarks.py +163 -0
  45. slidge/group/participant.py +458 -0
  46. slidge/group/room.py +1103 -0
  47. slidge/migration.py +18 -0
  48. slidge/slixfix/__init__.py +68 -0
  49. slidge/{util/xep_0084 → slixfix/link_preview}/__init__.py +3 -5
  50. slidge/slixfix/link_preview/link_preview.py +17 -0
  51. slidge/slixfix/link_preview/stanza.py +99 -0
  52. slidge/slixfix/roster.py +60 -0
  53. slidge/{util → slixfix}/xep_0077/register.py +14 -2
  54. slidge/slixfix/xep_0077/stanza.py +104 -0
  55. slidge/{util → slixfix}/xep_0100/gateway.py +25 -15
  56. slidge/slixfix/xep_0100/stanza.py +9 -0
  57. slidge/slixfix/xep_0153/__init__.py +10 -0
  58. slidge/slixfix/xep_0153/stanza.py +25 -0
  59. slidge/slixfix/xep_0153/vcard_avatar.py +23 -0
  60. slidge/slixfix/xep_0264/__init__.py +5 -0
  61. slidge/slixfix/xep_0264/stanza.py +36 -0
  62. slidge/slixfix/xep_0264/thumbnail.py +23 -0
  63. slidge/slixfix/xep_0292/__init__.py +5 -0
  64. slidge/slixfix/xep_0292/vcard4.py +100 -0
  65. slidge/slixfix/xep_0313/__init__.py +12 -0
  66. slidge/slixfix/xep_0313/mam.py +262 -0
  67. slidge/slixfix/xep_0313/stanza.py +359 -0
  68. slidge/slixfix/xep_0317/__init__.py +5 -0
  69. slidge/slixfix/xep_0317/hats.py +17 -0
  70. slidge/slixfix/xep_0317/stanza.py +28 -0
  71. slidge/{util → slixfix}/xep_0356_old/privilege.py +9 -7
  72. slidge/slixfix/xep_0424/__init__.py +9 -0
  73. slidge/slixfix/xep_0424/retraction.py +77 -0
  74. slidge/slixfix/xep_0424/stanza.py +28 -0
  75. slidge/slixfix/xep_0490/__init__.py +8 -0
  76. slidge/slixfix/xep_0490/mds.py +47 -0
  77. slidge/slixfix/xep_0490/stanza.py +17 -0
  78. slidge/util/__init__.py +4 -6
  79. slidge/util/archive_msg.py +61 -0
  80. slidge/util/conf.py +206 -0
  81. slidge/util/db.py +57 -76
  82. slidge/util/schema.sql +126 -0
  83. slidge/util/sql.py +508 -0
  84. slidge/util/test.py +215 -25
  85. slidge/util/types.py +177 -4
  86. slidge/util/util.py +225 -59
  87. slidge-0.1.1.dist-info/METADATA +110 -0
  88. slidge-0.1.1.dist-info/RECORD +96 -0
  89. {slidge-0.1.0b2.dist-info → slidge-0.1.1.dist-info}/WHEEL +1 -1
  90. slidge/core/contact.py +0 -891
  91. slidge/core/gateway.py +0 -916
  92. slidge/plugins/discord/__init__.py +0 -90
  93. slidge/plugins/discord/client.py +0 -108
  94. slidge/plugins/discord/session.py +0 -162
  95. slidge/plugins/dummy.py +0 -203
  96. slidge/plugins/facebook.py +0 -493
  97. slidge/plugins/hackernews.py +0 -213
  98. slidge/plugins/mattermost/__init__.py +0 -1
  99. slidge/plugins/mattermost/api.py +0 -280
  100. slidge/plugins/mattermost/gateway.py +0 -365
  101. slidge/plugins/mattermost/websocket.py +0 -252
  102. slidge/plugins/signal/__init__.py +0 -3
  103. slidge/plugins/signal/contact.py +0 -106
  104. slidge/plugins/signal/gateway.py +0 -282
  105. slidge/plugins/signal/session.py +0 -448
  106. slidge/plugins/signal/txt.py +0 -53
  107. slidge/plugins/skype.py +0 -325
  108. slidge/plugins/steam.py +0 -310
  109. slidge/plugins/telegram/__init__.py +0 -5
  110. slidge/plugins/telegram/client.py +0 -228
  111. slidge/plugins/telegram/config.py +0 -12
  112. slidge/plugins/telegram/contact.py +0 -176
  113. slidge/plugins/telegram/gateway.py +0 -150
  114. slidge/plugins/telegram/session.py +0 -256
  115. slidge/util/xep_0030/__init__.py +0 -13
  116. slidge/util/xep_0030/disco.py +0 -811
  117. slidge/util/xep_0030/stanza/__init__.py +0 -7
  118. slidge/util/xep_0030/stanza/info.py +0 -270
  119. slidge/util/xep_0030/stanza/items.py +0 -147
  120. slidge/util/xep_0030/static.py +0 -467
  121. slidge/util/xep_0055/__init__.py +0 -5
  122. slidge/util/xep_0055/search.py +0 -75
  123. slidge/util/xep_0055/stanza.py +0 -10
  124. slidge/util/xep_0077/stanza.py +0 -71
  125. slidge/util/xep_0084/avatar.py +0 -137
  126. slidge/util/xep_0084/stanza.py +0 -104
  127. slidge/util/xep_0115/__init__.py +0 -12
  128. slidge/util/xep_0115/caps.py +0 -379
  129. slidge/util/xep_0115/stanza.py +0 -16
  130. slidge/util/xep_0115/static.py +0 -137
  131. slidge/util/xep_0292/__init__.py +0 -1
  132. slidge/util/xep_0292/stanza.py +0 -167
  133. slidge/util/xep_0292/vcard4.py +0 -75
  134. slidge/util/xep_0333/__init__.py +0 -10
  135. slidge/util/xep_0333/markers.py +0 -96
  136. slidge/util/xep_0333/stanza.py +0 -34
  137. slidge/util/xep_0356/__init__.py +0 -7
  138. slidge/util/xep_0356/permissions.py +0 -35
  139. slidge/util/xep_0356/privilege.py +0 -160
  140. slidge/util/xep_0356/stanza.py +0 -44
  141. slidge/util/xep_0363/__init__.py +0 -16
  142. slidge/util/xep_0363/http_upload.py +0 -215
  143. slidge/util/xep_0363/stanza.py +0 -46
  144. slidge/util/xep_0461/__init__.py +0 -6
  145. slidge/util/xep_0461/reply.py +0 -48
  146. slidge/util/xep_0461/stanza.py +0 -47
  147. slidge-0.1.0b2.dist-info/METADATA +0 -171
  148. slidge-0.1.0b2.dist-info/RECORD +0 -81
  149. /slidge/{plugins/__init__.py → py.typed} +0 -0
  150. /slidge/{util → slixfix}/xep_0077/__init__.py +0 -0
  151. /slidge/{util → slixfix}/xep_0100/__init__.py +0 -0
  152. /slidge/{util → slixfix}/xep_0356_old/__init__.py +0 -0
  153. /slidge/{util → slixfix}/xep_0356_old/stanza.py +0 -0
  154. {slidge-0.1.0b2.dist-info → slidge-0.1.1.dist-info}/LICENSE +0 -0
  155. {slidge-0.1.0b2.dist-info → slidge-0.1.1.dist-info}/entry_points.txt +0 -0
slidge/__init__.py CHANGED
@@ -1,37 +1,61 @@
1
- import slixmpp.plugins
2
-
3
- from .core.contact import LegacyContact, LegacyRoster
4
- from .core.gateway import BaseGateway
5
- from .core.session import BaseSession
6
- from .util import (
7
- FormField,
8
- SearchResult,
9
- xep_0030,
10
- xep_0055,
11
- xep_0077,
12
- xep_0084,
13
- xep_0100,
14
- xep_0115,
15
- xep_0292,
16
- xep_0333,
17
- xep_0356,
18
- xep_0356_old,
19
- xep_0363,
20
- xep_0461,
21
- )
22
- from .util.db import GatewayUser, user_store
23
-
24
- slixmpp.plugins.__all__.extend(
25
- ["xep_0055", "xep_0292_provider", "xep_0356", "xep_0356_old", "xep_0461"]
26
- )
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
+
27
41
 
28
42
  __all__ = [
29
43
  "BaseGateway",
30
44
  "BaseSession",
31
- "GatewayUser",
32
- "LegacyContact",
33
- "LegacyRoster",
34
- "FormField",
35
- "SearchResult",
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",
58
+ "global_config",
37
59
  ]
60
+
61
+ addLoggingLevel()
slidge/__main__.py CHANGED
@@ -1,119 +1,72 @@
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
20
+ import signal
7
21
  from pathlib import Path
8
22
 
9
23
  import configargparse
10
24
 
11
25
  from slidge import BaseGateway
12
- from slidge.core.pubsub import PepAvatar
26
+ from slidge.core import config
27
+ from slidge.core.cache import avatar_cache
28
+ from slidge.migration import migrate
29
+ from slidge.util.conf import ConfigModule
13
30
  from slidge.util.db import user_store
31
+ from slidge.util.util import get_version # noqa: F401
14
32
 
15
33
 
16
- # noinspection PyUnresolvedReferences
17
- def get_parser():
18
- p = configargparse.ArgParser(
19
- default_config_files=["/etc/slidge/conf.d/*.conf"], description=__doc__
34
+ class MainConfig(ConfigModule):
35
+ def update_dynamic_defaults(self, args):
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
+ )
44
+
45
+ if args.home_dir is None:
46
+ args.home_dir = Path("/var/lib/slidge") / str(args.jid)
47
+
48
+ if args.user_jid_validator is None:
49
+ args.user_jid_validator = ".*@" + args.server
50
+
51
+
52
+ class SigTermInterrupt(Exception):
53
+ pass
54
+
55
+
56
+ def get_configurator():
57
+ p = configargparse.ArgumentParser(
58
+ default_config_files=os.getenv(
59
+ "SLIDGE_CONF_DIR", "/etc/slidge/conf.d/*.conf"
60
+ ).split(":"),
61
+ description=__doc__,
20
62
  )
21
- p.add(
63
+ p.add_argument(
22
64
  "-c",
23
65
  "--config",
24
66
  help="Path to a INI config file.",
25
67
  env_var="SLIDGE_CONFIG",
26
68
  is_config_file=True,
27
69
  )
28
- p.add(
29
- "--legacy-module",
30
- help="Importable python module containing (at least) "
31
- "a BaseGateway and a LegacySession subclass",
32
- env_var="SLIDGE_LEGACY_MODULE",
33
- )
34
- p.add(
35
- "-s",
36
- "--server",
37
- env_var="SLIDGE_SERVER",
38
- required=True,
39
- help="The XMPP server's host name.",
40
- )
41
- p.add(
42
- "-p",
43
- "--port",
44
- default="5347",
45
- env_var="SLIDGE_PORT",
46
- help="The XMPP server's port for incoming component connections",
47
- )
48
- p.add(
49
- "--secret",
50
- required=True,
51
- env_var="SLIDGE_SECRET",
52
- help="The gateway component's secret (required to connect to the XMPP server)",
53
- )
54
- p.add(
55
- "-j",
56
- "--jid",
57
- required=True,
58
- env_var="SLIDGE_JID",
59
- help="The gateway component's JID",
60
- )
61
- p.add(
62
- "--upload-service",
63
- env_var="SLIDGE_UPLOAD",
64
- help="JID of an HTTP upload service the gateway can use. "
65
- "This is optional, as it should be automatically determined via service discovery",
66
- )
67
- p.add(
68
- "--home-dir",
69
- env_var="SLIDGE_HOME_DIR",
70
- help="Shelve file used to store persistent user data. "
71
- "Defaults to /var/lib/slidge/${SLIDGE_JID}",
72
- )
73
- p.add(
74
- "--admins",
75
- env_var="SLIDGE_ADMINS",
76
- nargs="*",
77
- help="JIDs of the gateway admins",
78
- )
79
- p.add(
80
- "--user-jid-validator",
81
- env_var="SLIDGE_RESTRICT",
82
- help="Regular expression to restrict user that can register to the gateway by JID. "
83
- "Defaults to .*@${SLIDGE_SERVER}, forbids the gateway to JIDs "
84
- "not using the same XMPP server as the gateway",
85
- )
86
- p.add(
87
- "--secret-key",
88
- env_var="SLIDGE_SECRET_KEY",
89
- help="Encryption for disk storage",
90
- )
91
- p.add(
92
- "--no-roster-push",
93
- env_var="SLIDGE_NO_ROSTER_PUSH",
94
- help="Do not fill users' rosters with legacy contacts automatically",
95
- action="store_true",
96
- )
97
- p.add_argument(
98
- "--avatar-size",
99
- env_var="SLIDGE_AVATAR_SIZE",
100
- type=int,
101
- default=200,
102
- help="Maximum image size (width and height), image ratio will be preserved",
103
- )
104
- p.add_argument(
105
- "--upload-requester",
106
- env_var="SLIDGE_UPLOAD_REQUESTER",
107
- help="Set which JID should request the upload slots. Defaults to the component JID.",
108
- )
109
- p.add_argument(
110
- "--ignore-delay-threshold",
111
- env_var="SLIDGE_IGNORE_DELAY_THRESHOLD",
112
- help="Threshold, in seconds, below which the <delay> information is stripped "
113
- "out of emitted stanzas.",
114
- default=300,
115
- )
116
-
117
70
  p.add_argument(
118
71
  "-q",
119
72
  "--quiet",
@@ -133,34 +86,73 @@ def get_parser():
133
86
  const=logging.DEBUG,
134
87
  env_var="SLIDGE_DEBUG",
135
88
  )
136
-
137
- return p
89
+ p.add_argument(
90
+ "--version",
91
+ action="version",
92
+ version=f"%(prog)s {__version__}",
93
+ )
94
+ configurator = MainConfig(config, p)
95
+ return configurator
138
96
 
139
97
 
140
- def main():
141
- args, argv = get_parser().parse_known_args()
142
- logging.basicConfig(level=args.loglevel)
98
+ def get_parser():
99
+ return get_configurator().parser
143
100
 
144
- if args.home_dir is None:
145
- args.home_dir = Path("/var/lib/slidge") / args.jid
146
- else:
147
- args.home_dir = Path(args.home_dir)
148
101
 
149
- if not args.home_dir.exists():
150
- logging.info("Creating directory '%s'", args.home_dir)
151
- args.home_dir.mkdir()
102
+ def configure():
103
+ configurator = get_configurator()
104
+ args, unknown_argv = configurator.set_conf()
152
105
 
153
- if args.user_jid_validator is None:
154
- args.user_jid_validator = ".*@" + args.server
106
+ if not (h := config.HOME_DIR).exists():
107
+ logging.info("Creating directory '%s'", h)
108
+ h.mkdir()
155
109
 
156
- db_file = Path(args.home_dir) / "slidge.db"
110
+ db_file = config.HOME_DIR / "slidge.db"
157
111
  user_store.set_file(db_file, args.secret_key)
158
112
 
159
- PepAvatar.AVATAR_SIZE = args.avatar_size
113
+ avatar_cache.set_dir(h / "slidge_avatars_v2")
160
114
 
161
- importlib.import_module(args.legacy_module)
162
- gateway = BaseGateway.get_unique_subclass()(args)
163
- gateway.config(argv)
115
+ config.UPLOAD_REQUESTER = config.UPLOAD_REQUESTER or config.JID.bare
116
+
117
+ return unknown_argv
118
+
119
+
120
+ def handle_sigterm(_signum, _frame):
121
+ logging.info("Caught SIGTERM")
122
+ raise SigTermInterrupt
123
+
124
+
125
+ def main():
126
+ signal.signal(signal.SIGTERM, handle_sigterm)
127
+
128
+ unknown_argv = configure()
129
+ logging.info("Starting slidge version %s", __version__)
130
+
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
+ )
138
+
139
+ if plugin_config_obj := getattr(
140
+ legacy_module, "config", getattr(legacy_module, "Config", None)
141
+ ):
142
+ logging.debug("Found a config object in plugin: %r", plugin_config_obj)
143
+ ConfigModule.ENV_VAR_PREFIX += (
144
+ f"_{config.LEGACY_MODULE.split('.')[-1].upper()}_"
145
+ )
146
+ logging.debug("Env var prefix: %s", ConfigModule.ENV_VAR_PREFIX)
147
+ ConfigModule(plugin_config_obj).set_conf(unknown_argv)
148
+ else:
149
+ if unknown_argv:
150
+ raise RuntimeError("Some arguments have not been recognized", unknown_argv)
151
+
152
+ migrate()
153
+
154
+ gateway: BaseGateway = BaseGateway.get_unique_subclass()()
155
+ avatar_cache.http = gateway.http
164
156
  gateway.connect()
165
157
 
166
158
  return_code = 0
@@ -168,8 +160,10 @@ def main():
168
160
  gateway.loop.run_forever()
169
161
  except KeyboardInterrupt:
170
162
  logging.debug("Received SIGINT")
163
+ except SigTermInterrupt:
164
+ logging.debug("Received SIGTERM")
171
165
  except SystemExit as e:
172
- return_code = e.code
166
+ return_code = e.code # type: ignore
173
167
  logging.debug("Exit called")
174
168
  except Exception as e:
175
169
  return_code = 2
@@ -182,15 +176,23 @@ def main():
182
176
  return_code = 3
183
177
  if gateway.is_connected():
184
178
  logging.debug("Gateway is connected, cleaning up")
185
- gateway.shutdown()
179
+ gateway.loop.run_until_complete(asyncio.gather(*gateway.shutdown()))
186
180
  gateway.disconnect()
187
181
  gateway.loop.run_until_complete(gateway.disconnected)
188
182
  else:
189
183
  logging.debug("Gateway is not connected, no need to clean up")
184
+ user_store.close()
185
+ avatar_cache.close()
186
+ gateway.loop.run_until_complete(gateway.http.close())
190
187
  logging.info("Successful clean shut down")
191
188
  logging.debug("Exiting with code %s", return_code)
192
189
  exit(return_code)
193
190
 
194
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
+
195
197
  if __name__ == "__main__":
196
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
+ )
@@ -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__)