Reformatted code base using black.

This commit is contained in:
Goffi 2024-06-19 18:44:57 +02:00
commit 53fdaa9d09
35 changed files with 12604 additions and 8966 deletions

View file

@ -92,9 +92,7 @@ def get_use_args(host, args, use, verbose=False, parser=None):
else:
if verbose:
host.disp(
_("arg {name}={value} (in USE)").format(
name=arg, value=escape(value)
)
_("arg {name}={value} (in USE)").format(name=arg, value=escape(value))
)
if not action.option_strings:
pos_args.append(value)

File diff suppressed because it is too large Load diff

View file

@ -51,12 +51,9 @@ import gi
from libervia.backend.core.i18n import _
from libervia.frontends.tools import aio, display_servers, webrtc
gi.require_versions({
"Gst": "1.0",
"GstWebRTC": "1.0"
})
from gi.repository import Gst
gi.require_versions({"Gst": "1.0", "GstWebRTC": "1.0"})
from gi.repository import Gst
ICON_SIZE = QSize(45, 45)
@ -389,7 +386,7 @@ class AVCallUI(QMainWindow):
self.fullscreen_btn.setIcon(self.fullscreen_icon_normal)
self.showNormal()
def closeEvent(self, a0: QCloseEvent|None) -> None:
def closeEvent(self, a0: QCloseEvent | None) -> None:
super().closeEvent(a0)
global running
running = False

View file

@ -88,7 +88,9 @@ class BaseAVTUI:
def get_video_display(self):
assert self.webrtc is not None
if self.webrtc.video_muted:
return Panel(Text("❌ ") + self.styled_shortcut_key("Video Off"), expand=False)
return Panel(
Text("❌ ") + self.styled_shortcut_key("Video Off"), expand=False
)
else:
return Panel(Text("🎥 ") + self.styled_shortcut_key("Video On"), expand=False)

View file

@ -114,7 +114,7 @@ class AVCallUI(BaseAVTUI):
if self.render_class is None:
self.render_class = t_image.auto_image_class()
loop_sleep = 1/self.fps
loop_sleep = 1 / self.fps
with self.input.raw_mode():
# for whatever reason, using self.input.attach is breaking KittyImage and uses

View file

@ -43,12 +43,8 @@ class AccountCreate(base.CommandBase):
)
def add_parser_options(self):
self.parser.add_argument(
"jid", help=_("jid to create")
)
self.parser.add_argument(
"password", help=_("password of the account")
)
self.parser.add_argument("jid", help=_("jid to create"))
self.parser.add_argument("password", help=_("password of the account"))
self.parser.add_argument(
"-p",
"--profile",
@ -73,9 +69,7 @@ class AccountCreate(base.CommandBase):
"--port",
type=int,
default=0,
help=_("server port (default: {port})").format(
port=C.XMPP_C2S_PORT
),
help=_("server port (default: {port})").format(port=C.XMPP_C2S_PORT),
)
async def start(self):
@ -89,16 +83,15 @@ class AccountCreate(base.CommandBase):
)
except BridgeException as e:
if e.condition == 'conflict':
self.disp(
f"The account {self.args.jid} already exists",
error=True
)
if e.condition == "conflict":
self.disp(f"The account {self.args.jid} already exists", error=True)
self.host.quit(C.EXIT_CONFLICT)
else:
self.disp(
f"can't create account on {self.args.host or 'localhost'!r} with jid "
f"{self.args.jid!r} using In-Band Registration: {e}", error=True)
f"{self.args.jid!r} using In-Band Registration: {e}",
error=True,
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
except Exception as e:
self.disp(f"Internal error: {e}", error=True)
@ -109,7 +102,6 @@ class AccountCreate(base.CommandBase):
if self.args.profile is None:
self.host.quit()
self.disp(_("creating profile"), 2)
try:
await self.host.bridge.profile_create(
@ -118,20 +110,15 @@ class AccountCreate(base.CommandBase):
"",
)
except BridgeException as e:
if e.condition == 'conflict':
self.disp(
f"The profile {self.args.profile} already exists",
error=True
)
if e.condition == "conflict":
self.disp(f"The profile {self.args.profile} already exists", error=True)
self.host.quit(C.EXIT_CONFLICT)
else:
self.disp(
_("Can't create profile {profile} to associate with jid "
"{jid}: {e}").format(
profile=self.args.profile,
jid=self.args.jid,
e=e
),
_(
"Can't create profile {profile} to associate with jid "
"{jid}: {e}"
).format(profile=self.args.profile, jid=self.args.jid, e=e),
error=True,
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -173,7 +160,9 @@ class AccountCreate(base.CommandBase):
self.disp(
f"profile {self.args.profile} successfully created and associated to the new "
f"account", 1)
f"account",
1,
)
self.host.quit()
@ -184,9 +173,7 @@ class AccountModify(base.CommandBase):
)
def add_parser_options(self):
self.parser.add_argument(
"password", help=_("new XMPP password")
)
self.parser.add_argument("password", help=_("new XMPP password"))
async def start(self):
try:

View file

@ -97,8 +97,9 @@ class Remote(base.CommandBase):
for method in methods:
path, iface, command = method
self.disp(
_("Command found: (path:{path}, iface: {iface}) [{command}]")
.format(path=path, iface=iface, command=command),
_(
"Command found: (path:{path}, iface: {iface}) [{command}]"
).format(path=path, iface=iface, command=command),
1,
)
self.host.quit()

View file

@ -29,8 +29,11 @@ class List(base.CommandBase):
def __init__(self, host):
super(List, self).__init__(
host, "list", use_profile=False, use_output=C.OUTPUT_LIST,
help=_("list available applications")
host,
"list",
use_profile=False,
use_output=C.OUTPUT_LIST,
help=_("list available applications"),
)
def add_parser_options(self):
@ -52,7 +55,7 @@ class List(base.CommandBase):
if self.args.filters:
self.args.filters = list(set(self.args.filters))
else:
self.args.filters = ['available']
self.args.filters = ["available"]
try:
found_apps = await self.host.bridge.applications_list(self.args.filters)
@ -123,12 +126,12 @@ class Stop(base.CommandBase):
)
except Exception as e:
if self.args.name is not None:
self.disp(
f"can't stop application {self.args.name!r}: {e}", error=True)
self.disp(f"can't stop application {self.args.name!r}: {e}", error=True)
else:
self.disp(
f"can't stop application instance with id {self.args.id!r}: {e}",
error=True)
error=True,
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
else:
self.host.quit()
@ -138,8 +141,11 @@ class Exposed(base.CommandBase):
def __init__(self, host):
super(Exposed, self).__init__(
host, "exposed", use_profile=False, use_output=C.OUTPUT_DICT,
help=_("show data exposed by a running application")
host,
"exposed",
use_profile=False,
use_output=C.OUTPUT_DICT,
help=_("show data exposed by a running application"),
)
def add_parser_options(self):
@ -169,11 +175,13 @@ class Exposed(base.CommandBase):
if self.args.name is not None:
self.disp(
f"can't get values exposed from application {self.args.name!r}: {e}",
error=True)
error=True,
)
else:
self.disp(
f"can't values exposed from application instance with id {self.args.id!r}: {e}",
error=True)
error=True,
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
else:
exposed_data = data_format.deserialise(exposed_data_raw)
@ -186,6 +194,9 @@ class Application(base.CommandBase):
def __init__(self, host):
super(Application, self).__init__(
host, "application", use_profile=False, help=_("manage applications"),
aliases=['app'],
host,
"application",
use_profile=False,
help=_("manage applications"),
aliases=["app"],
)

View file

@ -45,7 +45,7 @@ class Get(base.CommandBase):
self.parser.add_argument(
"-s", "--show", action="store_true", help=_("show avatar")
)
self.parser.add_argument("jid", nargs='?', default='', help=_("entity"))
self.parser.add_argument("jid", nargs="?", default="", help=_("entity"))
async def show_image(self, path):
sat_conf = config.parse_main_conf()
@ -87,7 +87,7 @@ class Get(base.CommandBase):
self.disp(_("No avatar found."), 1)
self.host.quit(C.EXIT_NOT_FOUND)
avatar_path = avatar_data['path']
avatar_path = avatar_data["path"]
self.disp(avatar_path)
if self.args.show:
@ -99,13 +99,16 @@ class Get(base.CommandBase):
class Set(base.CommandBase):
def __init__(self, host):
super(Set, self).__init__(
host, "set", use_verbose=True,
help=_("set avatar of the profile or an entity")
host,
"set",
use_verbose=True,
help=_("set avatar of the profile or an entity"),
)
def add_parser_options(self):
self.parser.add_argument(
"-j", "--jid", default='', help=_("entity whose avatar must be changed"))
"-j", "--jid", default="", help=_("entity whose avatar must be changed")
)
self.parser.add_argument(
"image_path", type=str, help=_("path to the image to upload")
)

View file

@ -72,10 +72,7 @@ class Block(base.CommandBase):
async def start(self):
try:
await self.host.bridge.blocking_block(
self.args.entities,
self.profile
)
await self.host.bridge.blocking_block(self.args.entities, self.profile)
except Exception as e:
self.disp(f"can't block entities: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -110,17 +107,14 @@ class Unblock(base.CommandBase):
if not self.args.force:
await self.host.confirm_or_quit(
_("All entities will be unblocked, are you sure"),
_("unblock cancelled")
_("unblock cancelled"),
)
self.args.entities.clear()
elif self.args.force:
self.parser.error(_('--force is only allowed when "all" is used as target'))
try:
await self.host.bridge.blocking_unblock(
self.args.entities,
self.profile
)
await self.host.bridge.blocking_unblock(self.args.entities, self.profile)
except Exception as e:
self.disp(f"can't unblock entities: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -132,6 +126,4 @@ class Blocking(base.CommandBase):
subcommands = (List, Block, Unblock)
def __init__(self, host):
super().__init__(
host, "blocking", use_profile=False, help=_("entities blocking")
)
super().__init__(host, "blocking", use_profile=False, help=_("entities blocking"))

View file

@ -86,7 +86,7 @@ MB_KEYS = (
"content_xhtml",
"title",
"title_xhtml",
"extra"
"extra",
)
OUTPUT_OPT_NO_HEADER = "no-header"
RE_ATTACHMENT_METADATA = re.compile(r"^(?P<key>[a-z_]+)=(?P<value>.*)")
@ -130,9 +130,9 @@ class AltLinkAction(argparse.Action):
f"invalid number of argument for {', '.join(self.option_strings)}, it "
"must have at most 2 arguments."
)
alt_link = {'url': url}
alt_link = {"url": url}
if media_type is not None:
alt_link['media_type'] = media_type
alt_link["media_type"] = media_type
alt_links = getattr(namespace, self.dest)
if alt_links is None:
alt_links = []
@ -189,20 +189,18 @@ class BlogPublishCommon:
"--attachment",
dest="attachments",
nargs="+",
help=_(
"attachment in the form URL [metadata_name=value]"
)
help=_("attachment in the form URL [metadata_name=value]"),
)
self.parser.add_argument(
'--alt-link',
"--alt-link",
action=AltLinkAction,
dest="alt_links",
metavar=('URL', 'MEDIA_TYPE'),
metavar=("URL", "MEDIA_TYPE"),
help=(
"add an alternative link, you can use {service}, {node} and {item} "
"template values in URL"
)
),
)
comments_group = self.parser.add_mutually_exclusive_group()
@ -228,7 +226,7 @@ class BlogPublishCommon:
self.parser.add_argument(
"--no-id-suffix",
action="store_true",
help=_("do no add random suffix to friendly ID")
help=_("do no add random suffix to friendly ID"),
)
self.parser.add_argument(
@ -240,19 +238,19 @@ class BlogPublishCommon:
"-e",
"--encrypt",
action="store_true",
help=_("end-to-end encrypt the blog post")
help=_("end-to-end encrypt the blog post"),
)
self.parser.add_argument(
"--encrypt-for",
metavar="JID",
action="append",
help=_("encrypt a single item for")
help=_("encrypt a single item for"),
)
self.parser.add_argument(
"-X",
"--sign",
action="store_true",
help=_("cryptographically sign the blog post")
help=_("cryptographically sign the blog post"),
)
async def set_mb_data_content(self, content, mb_data):
@ -301,7 +299,7 @@ class BlogPublishCommon:
value = m.group("value").strip()
if key == "external":
if not value:
value=True
value = True
else:
value = C.bool(value)
attachment[key] = value
@ -1217,7 +1215,6 @@ class AttachmentGet(cmd_pubsub.AttachmentGet):
super().__init__(host)
self.override_pubsub_flags({C.SERVICE, C.SINGLE_ITEM})
async def start(self):
if not self.args.node:
namespaces = await self.host.bridge.namespaces_get()

View file

@ -37,7 +37,6 @@ __commands__ = ["Call"]
class Common(base.CommandBase):
def __init__(self, *args, **kwargs):
super().__init__(
*args,
@ -52,7 +51,7 @@ class Common(base.CommandBase):
#: experimental TUI output
"tui": partial(self.use_output, "tui"),
},
**kwargs
**kwargs,
)
def add_parser_options(self):
@ -61,8 +60,11 @@ class Common(base.CommandBase):
)
sources_group = self.parser.add_mutually_exclusive_group()
sources_group.add_argument(
"-s", "--sources", choices=['auto', 'test'], default='auto',
help='Well-known sources to use (default: "auto").'
"-s",
"--sources",
choices=["auto", "test"],
default="auto",
help='Well-known sources to use (default: "auto").',
)
def get_call_data_kw(self) -> dict[str, Any]:
@ -70,10 +72,10 @@ class Common(base.CommandBase):
kwargs: dict[str, Any] = {}
if self.args.sources == "test":
from libervia.frontends.tools.webrtc_models import SourcesTest
kwargs["sources_data"] = SourcesTest()
return kwargs
async def start(self):
root_logger = logging.getLogger()
# we don't want any formatting for messages from webrtc
@ -133,10 +135,9 @@ class Make(Common):
async def start(self):
await super().start()
await super().output(CallData(
callee=jid.JID(self.args.entity),
kwargs=self.get_call_data_kw()
))
await super().output(
CallData(callee=jid.JID(self.args.entity), kwargs=self.get_call_data_kw())
)
class Receive(Common):
@ -157,12 +158,14 @@ class Receive(Common):
action="append",
metavar="JID",
default=[],
help=_("automatically accept call from this jid (can be used multiple times)")
help=_(
"automatically accept call from this jid (can be used multiple times)"
),
)
auto_accept_group.add_argument(
"--auto-accept-all",
action="store_true",
help=_("automatically accept call from anybody")
help=_("automatically accept call from anybody"),
)
async def on_action_new(
@ -179,9 +182,7 @@ class Receive(Common):
not self.args.auto_accept_all
and caller not in self.args.auto_accept
and not await self.host.confirm(
_("📞 Incoming call from {caller}, do you accept?").format(
caller=caller
)
_("📞 Incoming call from {caller}, do you accept?").format(caller=caller)
)
):
await self.host.bridge.action_launch(
@ -191,12 +192,14 @@ class Receive(Common):
self.disp(_("✅ Incoming call from {caller} accepted.").format(caller=caller))
await super().output(CallData(
callee=peer_jid,
sid=action_data["session_id"],
action_id=action_id,
kwargs=self.get_call_data_kw()
))
await super().output(
CallData(
callee=peer_jid,
sid=action_data["session_id"],
action_id=action_id,
kwargs=self.get_call_data_kw(),
)
)
async def start(self):
await super().start()

View file

@ -31,11 +31,13 @@ class EncryptionAlgorithms(base.CommandBase):
def __init__(self, host):
extra_outputs = {"default": self.default_output}
super(EncryptionAlgorithms, self).__init__(
host, "algorithms",
host,
"algorithms",
use_output=C.OUTPUT_LIST_DICT,
extra_outputs=extra_outputs,
use_profile=False,
help=_("show available encryption algorithms"))
help=_("show available encryption algorithms"),
)
def add_parser_options(self):
pass
@ -44,8 +46,11 @@ class EncryptionAlgorithms(base.CommandBase):
if not plugins:
self.disp(_("No encryption plugin registered!"))
else:
self.disp(_("Following encryption algorithms are available: {algos}").format(
algos=', '.join([p['name'] for p in plugins])))
self.disp(
_("Following encryption algorithms are available: {algos}").format(
algos=", ".join([p["name"] for p in plugins])
)
)
async def start(self):
try:
@ -63,15 +68,11 @@ class EncryptionGet(base.CommandBase):
def __init__(self, host):
super(EncryptionGet, self).__init__(
host, "get",
use_output=C.OUTPUT_DICT,
help=_("get encryption session data"))
host, "get", use_output=C.OUTPUT_DICT, help=_("get encryption session data")
)
def add_parser_options(self):
self.parser.add_argument(
"jid",
help=_("jid of the entity to check")
)
self.parser.add_argument("jid", help=_("jid of the entity to check"))
async def start(self):
jids = await self.host.check_jids([self.args.jid])
@ -84,8 +85,7 @@ class EncryptionGet(base.CommandBase):
session_data = data_format.deserialise(serialised)
if session_data is None:
self.disp(
"No encryption session found, the messages are sent in plain text.")
self.disp("No encryption session found, the messages are sent in plain text.")
self.host.quit(C.EXIT_NOT_FOUND)
await self.output(session_data)
self.host.quit()
@ -95,29 +95,34 @@ class EncryptionStart(base.CommandBase):
def __init__(self, host):
super(EncryptionStart, self).__init__(
host, "start",
help=_("start encrypted session with an entity"))
host, "start", help=_("start encrypted session with an entity")
)
def add_parser_options(self):
self.parser.add_argument(
"--encrypt-noreplace",
action="store_true",
help=_("don't replace encryption algorithm if an other one is already used"))
help=_("don't replace encryption algorithm if an other one is already used"),
)
algorithm = self.parser.add_mutually_exclusive_group()
algorithm.add_argument(
"-n", "--name", help=_("algorithm name (DEFAULT: choose automatically)"))
"-n", "--name", help=_("algorithm name (DEFAULT: choose automatically)")
)
algorithm.add_argument(
"-N", "--namespace",
help=_("algorithm namespace (DEFAULT: choose automatically)"))
"-N",
"--namespace",
help=_("algorithm namespace (DEFAULT: choose automatically)"),
)
self.parser.add_argument(
"jid",
help=_("jid of the entity to stop encrypted session with")
"jid", help=_("jid of the entity to stop encrypted session with")
)
async def start(self):
if self.args.name is not None:
try:
namespace = await self.host.bridge.encryption_namespace_get(self.args.name)
namespace = await self.host.bridge.encryption_namespace_get(
self.args.name
)
except Exception as e:
self.disp(f"can't get encryption namespace: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -131,8 +136,8 @@ class EncryptionStart(base.CommandBase):
try:
await self.host.bridge.message_encryption_start(
jid, namespace, not self.args.encrypt_noreplace,
self.profile)
jid, namespace, not self.args.encrypt_noreplace, self.profile
)
except Exception as e:
self.disp(f"can't get encryption namespace: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -144,13 +149,12 @@ class EncryptionStop(base.CommandBase):
def __init__(self, host):
super(EncryptionStop, self).__init__(
host, "stop",
help=_("stop encrypted session with an entity"))
host, "stop", help=_("stop encrypted session with an entity")
)
def add_parser_options(self):
self.parser.add_argument(
"jid",
help=_("jid of the entity to stop encrypted session with")
"jid", help=_("jid of the entity to stop encrypted session with")
)
async def start(self):
@ -168,26 +172,28 @@ class EncryptionStop(base.CommandBase):
class TrustUI(base.CommandBase):
def __init__(self, host):
super(TrustUI, self).__init__(
host, "ui",
help=_("get UI to manage trust"))
super(TrustUI, self).__init__(host, "ui", help=_("get UI to manage trust"))
def add_parser_options(self):
self.parser.add_argument(
"jid",
help=_("jid of the entity to stop encrypted session with")
"jid", help=_("jid of the entity to stop encrypted session with")
)
algorithm = self.parser.add_mutually_exclusive_group()
algorithm.add_argument(
"-n", "--name", help=_("algorithm name (DEFAULT: current algorithm)"))
"-n", "--name", help=_("algorithm name (DEFAULT: current algorithm)")
)
algorithm.add_argument(
"-N", "--namespace",
help=_("algorithm namespace (DEFAULT: current algorithm)"))
"-N",
"--namespace",
help=_("algorithm namespace (DEFAULT: current algorithm)"),
)
async def start(self):
if self.args.name is not None:
try:
namespace = await self.host.bridge.encryption_namespace_get(self.args.name)
namespace = await self.host.bridge.encryption_namespace_get(
self.args.name
)
except Exception as e:
self.disp(f"can't get encryption namespace: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -201,7 +207,8 @@ class TrustUI(base.CommandBase):
try:
xmlui_raw = await self.host.bridge.encryption_trust_ui_get(
jid, namespace, self.profile)
jid, namespace, self.profile
)
except Exception as e:
self.disp(f"can't get encryption session trust UI: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -212,6 +219,7 @@ class TrustUI(base.CommandBase):
await xmlui.submit_form()
self.host.quit()
class EncryptionTrust(base.CommandBase):
subcommands = (TrustUI,)
@ -222,8 +230,13 @@ class EncryptionTrust(base.CommandBase):
class Encryption(base.CommandBase):
subcommands = (EncryptionAlgorithms, EncryptionGet, EncryptionStart, EncryptionStop,
EncryptionTrust)
subcommands = (
EncryptionAlgorithms,
EncryptionGet,
EncryptionStart,
EncryptionStop,
EncryptionTrust,
)
def __init__(self, host):
super(Encryption, self).__init__(

View file

@ -87,16 +87,22 @@ class Get(base.CommandBase):
start, "medium", tz_info=date_utils.TZ_LOCAL
)
end = event["end"]
self.disp(A.color(
A.BOLD, start_human, A.RESET, " ",
f"({date_utils.delta2human(start, end)}) ",
C.A_HEADER, name
))
self.disp(
A.color(
A.BOLD,
start_human,
A.RESET,
" ",
f"({date_utils.delta2human(start, end)}) ",
C.A_HEADER,
name,
)
)
if self.verbosity > 0:
descriptions = event.get("descriptions", [])
if descriptions:
self.disp(descriptions[0]["description"])
if idx < (nb_events-1):
if idx < (nb_events - 1):
self.disp("")
@ -106,7 +112,7 @@ class CategoryAction(argparse.Action):
if nargs is not None or metavar is not None:
raise ValueError("nargs and metavar must not be used")
if metavar is not None:
metavar="TERM WIKIDATA_ID LANG"
metavar = "TERM WIKIDATA_ID LANG"
if "--help" in sys.argv:
# FIXME: dirty workaround to have correct --help message
# argparse doesn't normally allow variable number of arguments beside "+"
@ -128,9 +134,7 @@ class CategoryAction(argparse.Action):
if not values:
parser.error("category values must be set")
category = {
"term": values[0]
}
category = {"term": values[0]}
if len(values) == 1:
pass
@ -153,14 +157,21 @@ class CategoryAction(argparse.Action):
class EventBase:
def add_parser_options(self):
self.parser.add_argument(
"-S", "--start", type=base.date_decoder, metavar="TIME_PATTERN",
help=_("the start time of the event"))
"-S",
"--start",
type=base.date_decoder,
metavar="TIME_PATTERN",
help=_("the start time of the event"),
)
end_group = self.parser.add_mutually_exclusive_group()
end_group.add_argument(
"-E", "--end", type=base.date_decoder, metavar="TIME_PATTERN",
help=_("the time of the end of the event"))
end_group.add_argument(
"-D", "--duration", help=_("duration of the event"))
"-E",
"--end",
type=base.date_decoder,
metavar="TIME_PATTERN",
help=_("the time of the end of the event"),
)
end_group.add_argument("-D", "--duration", help=_("duration of the event"))
self.parser.add_argument(
"-H", "--head-picture", help="URL to a picture to use as head-picture"
)
@ -168,47 +179,65 @@ class EventBase:
"-d", "--description", help="plain text description the event"
)
self.parser.add_argument(
"-C", "--category", action=CategoryAction, dest="categories",
help="Category of the event"
"-C",
"--category",
action=CategoryAction,
dest="categories",
help="Category of the event",
)
self.parser.add_argument(
"-l", "--location", action="append", nargs="+", metavar="[KEY] VALUE",
help="Location metadata"
"-l",
"--location",
action="append",
nargs="+",
metavar="[KEY] VALUE",
help="Location metadata",
)
rsvp_group = self.parser.add_mutually_exclusive_group()
rsvp_group.add_argument(
"--rsvp", action="store_true", help=_("RSVP is requested"))
"--rsvp", action="store_true", help=_("RSVP is requested")
)
rsvp_group.add_argument(
"--rsvp_json", metavar="JSON", help=_("JSON description of RSVP form"))
"--rsvp_json", metavar="JSON", help=_("JSON description of RSVP form")
)
for node_type in ("invitees", "comments", "blog", "schedule"):
self.parser.add_argument(
f"--{node_type}",
nargs=2,
metavar=("JID", "NODE"),
help=_("link {node_type} pubsub node").format(node_type=node_type)
help=_("link {node_type} pubsub node").format(node_type=node_type),
)
self.parser.add_argument(
"-a", "--attachment", action="append", dest="attachments",
help=_("attach a file")
"-a",
"--attachment",
action="append",
dest="attachments",
help=_("attach a file"),
)
self.parser.add_argument("--website", help=_("website of the event"))
self.parser.add_argument(
"--status", choices=["confirmed", "tentative", "cancelled"],
help=_("status of the event")
"--status",
choices=["confirmed", "tentative", "cancelled"],
help=_("status of the event"),
)
self.parser.add_argument(
"-T", "--language", metavar="LANG", action="append", dest="languages",
help=_("main languages spoken at the event")
"-T",
"--language",
metavar="LANG",
action="append",
dest="languages",
help=_("main languages spoken at the event"),
)
self.parser.add_argument(
"--wheelchair", choices=["full", "partial", "no"],
help=_("is the location accessible by wheelchair")
"--wheelchair",
choices=["full", "partial", "no"],
help=_("is the location accessible by wheelchair"),
)
self.parser.add_argument(
"--external",
nargs=3,
metavar=("JID", "NODE", "ITEM"),
help=_("link to an external event")
help=_("link to an external event"),
)
def get_event_data(self):
@ -229,17 +258,10 @@ class EventBase:
event["end"] = self.args.end
if self.args.head_picture:
event["head-picture"] = {
"sources": [{
"url": self.args.head_picture
}]
}
event["head-picture"] = {"sources": [{"url": self.args.head_picture}]}
if self.args.description:
event["descriptions"] = [
{
"type": "text",
"description": self.args.description
}
{"type": "text", "description": self.args.description}
]
if self.args.categories:
event["categories"] = self.args.categories
@ -270,9 +292,7 @@ class EventBase:
if self.args.attachments:
attachments = event["attachments"] = []
for attachment in self.args.attachments:
attachments.append({
"sources": [{"url": attachment}]
})
attachments.append({"sources": [{"url": attachment}]})
extra = {}
@ -288,11 +308,7 @@ class EventBase:
if self.args.external:
ext_jid, ext_node, ext_item = self.args.external
event["external"] = {
"jid": ext_jid,
"node": ext_node,
"item": ext_item
}
event["external"] = {"jid": ext_jid, "node": ext_node, "item": ext_item}
return event
@ -388,8 +404,12 @@ class InviteeGet(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
"-j", "--jid", action="append", dest="jids", default=[],
help=_("only retrieve RSVP from those JIDs")
"-j",
"--jid",
action="append",
dest="jids",
default=[],
help=_("only retrieve RSVP from those JIDs"),
)
async def start(self):

View file

@ -80,12 +80,10 @@ class Send(base.CommandBase):
"-e",
"--encrypt",
action="store_true",
help=_("end-to-end encrypt the file transfer")
help=_("end-to-end encrypt the file transfer"),
)
self.parser.add_argument(
"--webrtc",
action="store_true",
help=_("Use WebRTC Data Channel transport.")
"--webrtc", action="store_true", help=_("Use WebRTC Data Channel transport.")
)
async def on_progress_started(self, metadata):
@ -111,7 +109,6 @@ class Send(base.CommandBase):
self.disp(_("Can't send file to {jid}".format(jid=self.args.jid)), error=True)
self.host.quit(2)
async def start(self):
file_ = None
for file_ in self.args.files:
@ -170,17 +167,16 @@ class Send(base.CommandBase):
if self.verbosity >= 2:
root_logger.setLevel(logging.DEBUG)
from libervia.frontends.tools.webrtc_file import WebRTCFileSender
aio.install_glib_asyncio_iteration()
file_sender = WebRTCFileSender(
self.host.bridge,
self.profile,
on_call_start_cb=self.got_id,
end_call_cb=self.host.a_quit
end_call_cb=self.host.a_quit,
)
await file_sender.send_file_webrtc(
file_path,
self.args.jid,
self.args.name
file_path, self.args.jid, self.args.name
)
else:
try:
@ -319,7 +315,9 @@ class Receive(base.CommandAnswering):
use_verbose=True,
help=_("wait for a file to be sent by a contact"),
)
self._overwrite_refused = False # True when one overwrite has already been refused
self._overwrite_refused = (
False # True when one overwrite has already been refused
)
self.action_callbacks = {
C.META_TYPE_CONFIRM: self.on_confirm_action,
C.META_TYPE_FILE: self.on_file_action,
@ -377,12 +375,10 @@ class Receive(base.CommandAnswering):
await self.host.a_quit()
async def on_webrtc_file(
self,
from_jid: jid.JID,
session_id: str,
file_data: dict
self, from_jid: jid.JID, session_id: str, file_data: dict
) -> None:
from libervia.frontends.tools.webrtc_file import WebRTCFileReceiver
aio.install_glib_asyncio_iteration()
root_logger = logging.getLogger()
# we don't want any formatting for messages from webrtc
@ -401,29 +397,20 @@ class Receive(base.CommandAnswering):
filename = file_data.get("name", "unammed_file")
dest_path /= filename
if dest_path.exists() and not self.args.force:
self.host.disp(
"Destination file already exists",
error=True
)
self.host.disp("Destination file already exists", error=True)
aio.run_from_thread(
self.host.a_quit, C.EXIT_ERROR, loop=self.host.loop.loop
)
return
file_receiver = WebRTCFileReceiver(
self.host.bridge,
self.profile,
on_close_cb=self._on_webrtc_close
self.host.bridge, self.profile, on_close_cb=self._on_webrtc_close
)
await file_receiver.receive_file_webrtc(
from_jid,
session_id,
dest_path,
file_data
from_jid, session_id, dest_path, file_data
)
def get_xmlui_id(self, action_data):
# FIXME: we temporarily use ElementTree, but a real XMLUI managing module
# should be available in the futur
@ -482,8 +469,9 @@ class Receive(base.CommandAnswering):
if self._overwrite_refused:
self.disp(_("File refused because overwrite is needed"), error=True)
await self.host.bridge.action_launch(
xmlui_id, data_format.serialise({"cancelled": C.BOOL_TRUE}),
profile_key=profile
xmlui_id,
data_format.serialise({"cancelled": C.BOOL_TRUE}),
profile_key=profile,
)
return self.host.quit_from_signal(2)
await self.set_progress_id(progress_id)
@ -495,11 +483,7 @@ class Receive(base.CommandAnswering):
except KeyError:
self.disp(_("ignoring action without session id"), 1)
return
await self.on_webrtc_file(
from_jid,
session_id,
file_data
)
await self.on_webrtc_file(from_jid, session_id, file_data)
else:
xmlui_data = {"path": self.path}
@ -604,8 +588,9 @@ class Get(base.CommandBase):
help=_("overwrite existing file without confirmation"),
)
self.parser.add_argument(
"attachment", type=str,
help=_("URI of the file to retrieve or JSON of the whole attachment")
"attachment",
type=str,
help=_("URI of the file to retrieve or JSON of the whole attachment"),
)
async def on_progress_started(self, metadata):

View file

@ -41,18 +41,13 @@ class Get(base.CommandBase):
self.parser.add_argument(
"--no-cache", action="store_true", help=_("do no use cached values")
)
self.parser.add_argument(
"jid", help=_("entity to check")
)
self.parser.add_argument("jid", help=_("entity to check"))
async def start(self):
jid_ = (await self.host.check_jids([self.args.jid]))[0]
try:
data = await self.host.bridge.identity_get(
jid_,
[],
not self.args.no_cache,
self.profile
jid_, [], not self.args.no_cache, self.profile
)
except Exception as e:
self.disp(f"can't get identity data: {e}", error=True)

View file

@ -131,45 +131,53 @@ class Disco(base.CommandBase):
data = {k: e[k] for k in sorted(e)}
host = data.pop("host")
type_ = data.pop("type")
fmt_lines.append(A.color(
"\t",
C.A_SUBHEADER,
host,
" ",
A.RESET,
"[",
C.A_LEVEL_COLORS[1],
type_,
A.RESET,
"]",
))
fmt_lines.append(
A.color(
"\t",
C.A_SUBHEADER,
host,
" ",
A.RESET,
"[",
C.A_LEVEL_COLORS[1],
type_,
A.RESET,
"]",
)
)
extended = data.pop("extended", None)
for key, value in data.items():
fmt_lines.append(A.color(
"\t\t",
C.A_LEVEL_COLORS[2],
f"{key}: ",
C.A_LEVEL_COLORS[3],
str(value)
))
fmt_lines.append(
A.color(
"\t\t",
C.A_LEVEL_COLORS[2],
f"{key}: ",
C.A_LEVEL_COLORS[3],
str(value),
)
)
if extended:
fmt_lines.append(A.color(
"\t\t",
C.A_HEADER,
"extended",
))
fmt_lines.append(
A.color(
"\t\t",
C.A_HEADER,
"extended",
)
)
nb_extended = len(extended)
for idx, form_data in enumerate(extended):
namespace = form_data.get("namespace")
if namespace:
fmt_lines.append(A.color(
"\t\t",
C.A_LEVEL_COLORS[2],
"namespace: ",
C.A_LEVEL_COLORS[3],
A.BOLD,
namespace
))
fmt_lines.append(
A.color(
"\t\t",
C.A_LEVEL_COLORS[2],
"namespace: ",
C.A_LEVEL_COLORS[3],
A.BOLD,
namespace,
)
)
for field_data in form_data["fields"]:
name = field_data.get("name")
if not name:
@ -183,15 +191,17 @@ class Disco(base.CommandBase):
continue
if field_type == "boolean":
value = C.bool(value)
fmt_lines.append(A.color(
"\t\t",
C.A_LEVEL_COLORS[2],
f"{name}: ",
C.A_LEVEL_COLORS[3],
A.BOLD,
str(value)
))
if nb_extended>1 and idx < nb_extended-1:
fmt_lines.append(
A.color(
"\t\t",
C.A_LEVEL_COLORS[2],
f"{name}: ",
C.A_LEVEL_COLORS[3],
A.BOLD,
str(value),
)
)
if nb_extended > 1 and idx < nb_extended - 1:
fmt_lines.append("\n")
fmt_lines.append("\n")
@ -218,7 +228,7 @@ class Disco(base.CommandBase):
if self.args.node:
if self.args.type == "external":
self.parser.error(
'--node can\'t be used with discovery of external services '
"--node can't be used with discovery of external services "
'(--type="external")'
)
else:
@ -245,7 +255,11 @@ class Disco(base.CommandBase):
features.sort()
identities.sort(key=lambda identity: identity[2])
data.update(
{"features": features, "identities": identities, "extensions": extensions}
{
"features": features,
"identities": identities,
"extensions": extensions,
}
)
# items
@ -274,7 +288,7 @@ class Disco(base.CommandBase):
except Exception as e:
self.disp(
_("error while doing external service discovery: {e}").format(e=e),
error=True
error=True,
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
else:

View file

@ -194,10 +194,10 @@ class InputCommon(base.CommandBase):
error=True,
)
self.host.quit(C.EXIT_DATA_ERROR)
end = '\n' if self.args.debug else ' '
end = "\n" if self.args.debug else " "
self.disp(
A.color(C.A_HEADER, _("command {idx}").format(idx=self.idx)),
end = end,
end=end,
)
stdin = "".join(self._stdin)
if self.args.debug:
@ -206,7 +206,7 @@ class InputCommon(base.CommandBase):
C.A_SUBHEADER,
_("values: "),
A.RESET,
", ".join([shlex.quote(a) for a in self._values_ori])
", ".join([shlex.quote(a) for a in self._values_ori]),
),
2,
)
@ -227,7 +227,7 @@ class InputCommon(base.CommandBase):
)
self.disp("\n")
else:
self.disp(" (" + ", ".join(self._values_ori) + ")", 2, end=' ')
self.disp(" (" + ", ".join(self._values_ori) + ")", 2, end=" ")
args = [sys.argv[0]] + self.args.command + self._opts + self._pos
p = await asyncio.create_subprocess_exec(
*args,
@ -235,18 +235,24 @@ class InputCommon(base.CommandBase):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = await p.communicate(stdin.encode('utf-8'))
stdout, stderr = await p.communicate(stdin.encode("utf-8"))
log = self.args.log
log_err = self.args.log_err
log_tpl = "{command}\n{buff}\n\n"
if log:
log.write(log_tpl.format(
command=" ".join(shlex.quote(a) for a in args),
buff=stdout.decode('utf-8', 'replace')))
log.write(
log_tpl.format(
command=" ".join(shlex.quote(a) for a in args),
buff=stdout.decode("utf-8", "replace"),
)
)
if log_err:
log_err.write(log_tpl.format(
command=" ".join(shlex.quote(a) for a in args),
buff=stderr.decode('utf-8', 'replace')))
log_err.write(
log_tpl.format(
command=" ".join(shlex.quote(a) for a in args),
buff=stderr.decode("utf-8", "replace"),
)
)
ret = p.returncode
if ret == 0:
self.disp(A.color(C.A_SUCCESS, _("OK")))

View file

@ -55,9 +55,7 @@ class Send(base.CommandBase):
"-n",
"--new-line",
action="store_true",
help=_(
"add a new line at the beginning of the input"
),
help=_("add a new line at the beginning of the input"),
)
self.parser.add_argument(
"-S",
@ -74,22 +72,29 @@ class Send(base.CommandBase):
default=C.MESS_TYPE_AUTO,
help=_("type of the message"),
)
self.parser.add_argument("-e", "--encrypt", metavar="ALGORITHM",
help=_("encrypt message using given algorithm"))
self.parser.add_argument(
"-e",
"--encrypt",
metavar="ALGORITHM",
help=_("encrypt message using given algorithm"),
)
self.parser.add_argument(
"--encrypt-noreplace",
action="store_true",
help=_("don't replace encryption algorithm if an other one is already used"))
help=_("don't replace encryption algorithm if an other one is already used"),
)
self.parser.add_argument(
"-a", "--attach", dest="attachments", action="append", metavar="FILE_PATH",
help=_("add a file as an attachment")
"-a",
"--attach",
dest="attachments",
action="append",
metavar="FILE_PATH",
help=_("add a file as an attachment"),
)
syntax = self.parser.add_mutually_exclusive_group()
syntax.add_argument("-x", "--xhtml", action="store_true", help=_("XHTML body"))
syntax.add_argument("-r", "--rich", action="store_true", help=_("rich body"))
self.parser.add_argument(
"jid", help=_("the destination jid")
)
self.parser.add_argument("jid", help=_("the destination jid"))
async def send_stdin(self, dest_jid):
"""Send incomming data on stdin to jabber contact
@ -98,9 +103,7 @@ class Send(base.CommandBase):
"""
header = "\n" if self.args.new_line else ""
# FIXME: stdin is not read asynchronously at the moment
stdin_lines = [
stream for stream in sys.stdin.readlines()
]
stdin_lines = [stream for stream in sys.stdin.readlines()]
extra = {}
if self.args.subject is None:
subject = {}
@ -134,8 +137,9 @@ class Send(base.CommandBase):
self.disp(f"can't send header: {e}", error=True)
error = True
to_send.extend({self.args.lang: clean_ustr(l.replace("\n", ""))}
for l in stdin_lines)
to_send.extend(
{self.args.lang: clean_ustr(l.replace("\n", ""))} for l in stdin_lines
)
else:
# we sent all in a single message
if not (self.args.xhtml or self.args.rich):
@ -166,7 +170,8 @@ class Send(base.CommandBase):
subject,
self.args.type,
data_format.serialise(extra),
profile_key=self.host.profile)
profile_key=self.host.profile,
)
except Exception as e:
self.disp(f"can't send message {msg!r}: {e}", error=True)
error = True
@ -194,7 +199,8 @@ class Send(base.CommandBase):
if self.args.encrypt is not None:
try:
namespace = await self.host.bridge.encryption_namespace_get(
self.args.encrypt)
self.args.encrypt
)
except Exception as e:
self.disp(f"can't get encryption namespace: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -216,24 +222,19 @@ class Retract(base.CommandBase):
super().__init__(host, "retract", help=_("retract a message"))
def add_parser_options(self):
self.parser.add_argument(
"message_id",
help=_("ID of the message (internal ID)")
)
self.parser.add_argument("message_id", help=_("ID of the message (internal ID)"))
async def start(self):
try:
await self.host.bridge.message_retract(
self.args.message_id,
self.profile
)
await self.host.bridge.message_retract(self.args.message_id, self.profile)
except Exception as e:
self.disp(f"can't retract message: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
else:
self.disp(
"message retraction has been requested, please note that this is a "
"request which can't be enforced (see documentation for details).")
"request which can't be enforced (see documentation for details)."
)
self.host.quit(C.EXIT_OK)
@ -241,36 +242,66 @@ class MAM(base.CommandBase):
def __init__(self, host):
super(MAM, self).__init__(
host, "mam", use_output=C.OUTPUT_MESS, use_verbose=True,
help=_("query archives using MAM"))
host,
"mam",
use_output=C.OUTPUT_MESS,
use_verbose=True,
help=_("query archives using MAM"),
)
def add_parser_options(self):
self.parser.add_argument(
"-s", "--service", default="",
help=_("jid of the service (default: profile's server"))
"-s",
"--service",
default="",
help=_("jid of the service (default: profile's server"),
)
self.parser.add_argument(
"-S", "--start", dest="mam_start", type=base.date_decoder,
help=_(
"start fetching archive from this date (default: from the beginning)"))
"-S",
"--start",
dest="mam_start",
type=base.date_decoder,
help=_("start fetching archive from this date (default: from the beginning)"),
)
self.parser.add_argument(
"-E", "--end", dest="mam_end", type=base.date_decoder,
help=_("end fetching archive after this date (default: no limit)"))
"-E",
"--end",
dest="mam_end",
type=base.date_decoder,
help=_("end fetching archive after this date (default: no limit)"),
)
self.parser.add_argument(
"-W", "--with", dest="mam_with",
help=_("retrieve only archives with this jid"))
"-W",
"--with",
dest="mam_with",
help=_("retrieve only archives with this jid"),
)
self.parser.add_argument(
"-m", "--max", dest="rsm_max", type=int, default=20,
help=_("maximum number of items to retrieve, using RSM (default: 20))"))
"-m",
"--max",
dest="rsm_max",
type=int,
default=20,
help=_("maximum number of items to retrieve, using RSM (default: 20))"),
)
rsm_page_group = self.parser.add_mutually_exclusive_group()
rsm_page_group.add_argument(
"-a", "--after", dest="rsm_after",
help=_("find page after this item"), metavar='ITEM_ID')
"-a",
"--after",
dest="rsm_after",
help=_("find page after this item"),
metavar="ITEM_ID",
)
rsm_page_group.add_argument(
"-b", "--before", dest="rsm_before",
help=_("find page before this item"), metavar='ITEM_ID')
"-b",
"--before",
dest="rsm_before",
help=_("find page before this item"),
metavar="ITEM_ID",
)
rsm_page_group.add_argument(
"--index", dest="rsm_index", type=int,
help=_("index of the page to retrieve"))
"--index", dest="rsm_index", type=int, help=_("index of the page to retrieve")
)
async def start(self):
extra = {}
@ -280,14 +311,15 @@ class MAM(base.CommandBase):
extra["mam_end"] = float(self.args.mam_end)
if self.args.mam_with is not None:
extra["mam_with"] = self.args.mam_with
for suff in ('max', 'after', 'before', 'index'):
key = 'rsm_' + suff
value = getattr(self.args,key)
for suff in ("max", "after", "before", "index"):
key = "rsm_" + suff
value = getattr(self.args, key)
if value is not None:
extra[key] = str(value)
try:
data, metadata_s, profile = await self.host.bridge.mam_get(
self.args.service, data_format.serialise(extra), self.profile)
self.args.service, data_format.serialise(extra), self.profile
)
except Exception as e:
self.disp(f"can't retrieve MAM archives: {e}", error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -308,12 +340,17 @@ class MAM(base.CommandBase):
# FIXME: metadata are not displayed correctly and don't play nice with output
# they should be added to output data somehow
if self.verbosity:
for value in ("rsm_first", "rsm_last", "rsm_index", "rsm_count",
"mam_complete", "mam_stable"):
for value in (
"rsm_first",
"rsm_last",
"rsm_index",
"rsm_count",
"mam_complete",
"mam_stable",
):
if value in metadata:
label = value.split("_")[1]
self.disp(A.color(
C.A_HEADER, label, ': ' , A.RESET, metadata[value]))
self.disp(A.color(C.A_HEADER, label, ": ", A.RESET, metadata[value]))
self.host.quit()

View file

@ -98,10 +98,10 @@ class Add(base.CommandBase):
await self.host.bridge.notification_add(
self.args.type,
self.args.body_plain,
"", # TODO: self.args.body_rich or "",
"", # TODO: self.args.body_rich or "",
self.args.title or "",
self.args.is_global,
False, # TODO: self.args.requires_action,
False, # TODO: self.args.requires_action,
self.args.priority,
self.args.expire_at,
"",
@ -300,7 +300,8 @@ class Delete(base.CommandBase):
)
self.parser.add_argument(
"-g", "--is-global",
"-g",
"--is-global",
action="store_true",
help=_("true if the notification is a global one"),
)

Some files were not shown because too many files have changed in this diff Show more