Mercurial > libervia-backend
comparison libervia/backend/plugins/plugin_exp_command_export.py @ 4071:4b842c1fb686
refactoring: renamed `sat` package to `libervia.backend`
author | Goffi <goffi@goffi.org> |
---|---|
date | Fri, 02 Jun 2023 11:49:51 +0200 |
parents | sat/plugins/plugin_exp_command_export.py@c23cad65ae99 |
children | 0d7bb4df2343 |
comparison
equal
deleted
inserted
replaced
4070:d10748475025 | 4071:4b842c1fb686 |
---|---|
1 #!/usr/bin/env python3 | |
2 | |
3 | |
4 # SAT plugin to export commands (experimental) | |
5 # Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org) | |
6 | |
7 # This program is free software: you can redistribute it and/or modify | |
8 # it under the terms of the GNU Affero General Public License as published by | |
9 # the Free Software Foundation, either version 3 of the License, or | |
10 # (at your option) any later version. | |
11 | |
12 # This program is distributed in the hope that it will be useful, | |
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 # GNU Affero General Public License for more details. | |
16 | |
17 # You should have received a copy of the GNU Affero General Public License | |
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
19 | |
20 from libervia.backend.core.i18n import _ | |
21 from libervia.backend.core.constants import Const as C | |
22 from libervia.backend.core.log import getLogger | |
23 | |
24 log = getLogger(__name__) | |
25 from twisted.words.protocols.jabber import jid | |
26 from twisted.internet import reactor, protocol | |
27 | |
28 from libervia.backend.tools import trigger | |
29 from libervia.backend.tools.utils import clean_ustr | |
30 | |
31 PLUGIN_INFO = { | |
32 C.PI_NAME: "Command export plugin", | |
33 C.PI_IMPORT_NAME: "EXP-COMMANS-EXPORT", | |
34 C.PI_TYPE: "EXP", | |
35 C.PI_PROTOCOLS: [], | |
36 C.PI_DEPENDENCIES: [], | |
37 C.PI_MAIN: "CommandExport", | |
38 C.PI_HANDLER: "no", | |
39 C.PI_DESCRIPTION: _("""Implementation of command export"""), | |
40 } | |
41 | |
42 | |
43 class ExportCommandProtocol(protocol.ProcessProtocol): | |
44 """ Try to register an account with prosody """ | |
45 | |
46 def __init__(self, parent, client, target, options): | |
47 self.parent = parent | |
48 self.target = target | |
49 self.options = options | |
50 self.client = client | |
51 | |
52 def _clean(self, data): | |
53 if not data: | |
54 log.error("data should not be empty !") | |
55 return "" | |
56 decoded = data.decode("utf-8", "ignore")[: -1 if data[-1] == "\n" else None] | |
57 return clean_ustr(decoded) | |
58 | |
59 def connectionMade(self): | |
60 log.info("connectionMade :)") | |
61 | |
62 def outReceived(self, data): | |
63 self.client.sendMessage(self.target, {"": self._clean(data)}, no_trigger=True) | |
64 | |
65 def errReceived(self, data): | |
66 self.client.sendMessage(self.target, {"": self._clean(data)}, no_trigger=True) | |
67 | |
68 def processEnded(self, reason): | |
69 log.info("process finished: %d" % (reason.value.exitCode,)) | |
70 self.parent.removeProcess(self.target, self) | |
71 | |
72 def write(self, message): | |
73 self.transport.write(message.encode("utf-8")) | |
74 | |
75 def bool_option(self, key): | |
76 """ Get boolean value from options | |
77 @param key: name of the option | |
78 @return: True if key exists and set to "true" (case insensitive), | |
79 False in all other cases """ | |
80 value = self.options.get(key, "") | |
81 return value.lower() == "true" | |
82 | |
83 | |
84 class CommandExport(object): | |
85 """Command export plugin: export a command to an entity""" | |
86 | |
87 # XXX: This plugin can be potentially dangerous if we don't trust entities linked | |
88 # this is specially true if we have other triggers. | |
89 # FIXME: spawned should be a client attribute, not a class one | |
90 | |
91 def __init__(self, host): | |
92 log.info(_("Plugin command export initialization")) | |
93 self.host = host | |
94 self.spawned = {} # key = entity | |
95 host.trigger.add("message_received", self.message_received_trigger, priority=10000) | |
96 host.bridge.add_method( | |
97 "command_export", | |
98 ".plugin", | |
99 in_sign="sasasa{ss}s", | |
100 out_sign="", | |
101 method=self._export_command, | |
102 ) | |
103 | |
104 def removeProcess(self, entity, process): | |
105 """ Called when the process is finished | |
106 @param entity: jid.JID attached to the process | |
107 @param process: process to remove""" | |
108 try: | |
109 processes_set = self.spawned[(entity, process.client.profile)] | |
110 processes_set.discard(process) | |
111 if not processes_set: | |
112 del (self.spawned[(entity, process.client.profile)]) | |
113 except ValueError: | |
114 pass | |
115 | |
116 def message_received_trigger(self, client, message_elt, post_treat): | |
117 """ Check if source is linked and repeat message, else do nothing """ | |
118 from_jid = jid.JID(message_elt["from"]) | |
119 spawned_key = (from_jid.userhostJID(), client.profile) | |
120 | |
121 if spawned_key in self.spawned: | |
122 try: | |
123 body = next(message_elt.elements(C.NS_CLIENT, "body")) | |
124 except StopIteration: | |
125 # do not block message without body (chat state notification...) | |
126 return True | |
127 | |
128 mess_data = str(body) + "\n" | |
129 processes_set = self.spawned[spawned_key] | |
130 _continue = False | |
131 exclusive = False | |
132 for process in processes_set: | |
133 process.write(mess_data) | |
134 _continue &= process.bool_option("continue") | |
135 exclusive |= process.bool_option("exclusive") | |
136 if exclusive: | |
137 raise trigger.SkipOtherTriggers | |
138 return _continue | |
139 | |
140 return True | |
141 | |
142 def _export_command(self, command, args, targets, options, profile_key): | |
143 """ Export a commands to authorised targets | |
144 @param command: full path of the command to execute | |
145 @param args: list of arguments, with command name as first one | |
146 @param targets: list of allowed entities | |
147 @param options: export options, a dict which can have the following keys ("true" to set booleans): | |
148 - exclusive: if set, skip all other triggers | |
149 - loop: if set, restart the command once terminated #TODO | |
150 - pty: if set, launch in a pseudo terminal | |
151 - continue: continue normal message_received handling | |
152 """ | |
153 client = self.host.get_client(profile_key) | |
154 for target in targets: | |
155 try: | |
156 _jid = jid.JID(target) | |
157 if not _jid.user or not _jid.host: | |
158 raise jid.InvalidFormat | |
159 _jid = _jid.userhostJID() | |
160 except (RuntimeError, jid.InvalidFormat, AttributeError): | |
161 log.info("invalid target ignored: %s" % (target,)) | |
162 continue | |
163 process_prot = ExportCommandProtocol(self, client, _jid, options) | |
164 self.spawned.setdefault((_jid, client.profile), set()).add(process_prot) | |
165 reactor.spawnProcess( | |
166 process_prot, command, args, usePTY=process_prot.bool_option("pty") | |
167 ) |