Python 3 port:

/!\ this is a huge commit
/!\ starting from this commit, SàT is needs Python 3.6+
/!\ SàT maybe be instable or some feature may not work anymore, this will improve with time

This patch port backend, bridge and frontends to Python 3.

Roughly this has been done this way:

- 2to3 tools has been applied (with python 3.7)
- all references to python2 have been replaced with python3 (notably shebangs)
- fixed files not handled by 2to3 (notably the shell script)
- several manual fixes
- fixed issues reported by Python 3 that where not handled in Python 2
- replaced "async" with "async_" when needed (it's a reserved word from Python 3.7)
- replaced zope's "implements" with @implementer decorator
- temporary hack to handle data pickled in database, as str or bytes may be returned,
  to be checked later
- fixed hash comparison for password
- removed some code which is not needed anymore with Python 3
- deactivated some code which needs to be checked (notably certificate validation)
- tested with jp, fixed reported issues until some basic commands worked
- ported Primitivus (after porting dependencies like urwid satext)
- more manual fixes
This commit is contained in:
Goffi 2019-08-13 19:08:41 +02:00
commit fbfe96c505
63 changed files with 6336 additions and 6398 deletions

View file

@ -29,10 +29,10 @@ class BridgeException(Exception):
@param condition (str) : error condition
"""
Exception.__init__(self)
self.fullname = unicode(name)
self.message = unicode(message)
self.condition = unicode(condition) if condition else ""
self.module, __, self.classname = unicode(self.fullname).rpartition(".")
self.fullname = str(name)
self.message = str(message)
self.condition = str(condition) if condition else ""
self.module, __, self.classname = str(self.fullname).rpartition(".")
def __str__(self):
message = (": %s" % self.message) if self.message else ""

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
# SAT communication bridge
@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from bridge_frontend import BridgeException
from .bridge_frontend import BridgeException
import dbus
from sat.core.log import getLogger
log = getLogger(__name__)
@ -70,12 +70,12 @@ class Bridge(object):
dbus_interface=const_INT_PREFIX + const_CORE_SUFFIX)
self.db_plugin_iface = dbus.Interface(self.db_object,
dbus_interface=const_INT_PREFIX + const_PLUGIN_SUFFIX)
except dbus.exceptions.DBusException, e:
except dbus.exceptions.DBusException as e:
if e._dbus_error_name in ('org.freedesktop.DBus.Error.ServiceUnknown',
'org.freedesktop.DBus.Error.Spawn.ExecFailed'):
errback(BridgeExceptionNoService())
elif e._dbus_error_name == 'org.freedesktop.DBus.Error.NotSupported':
log.error(_(u"D-Bus is not launched, please see README to see instructions on how to launch it"))
log.error(_("D-Bus is not launched, please see README to see instructions on how to launch it"))
errback(BridgeInitError)
else:
errback(e)
@ -102,14 +102,14 @@ class Bridge(object):
# - if we have the 'callback' and 'errback' keyword arguments
# - or if the last two arguments are callable
async = False
async_ = False
args = list(args)
if kwargs:
if 'callback' in kwargs:
async = True
async_ = True
_callback = kwargs.pop('callback')
_errback = kwargs.pop('errback', lambda failure: log.error(unicode(failure)))
_errback = kwargs.pop('errback', lambda failure: log.error(str(failure)))
try:
args.append(kwargs.pop('profile'))
except KeyError:
@ -119,15 +119,15 @@ class Bridge(object):
pass
# at this point, kwargs should be empty
if kwargs:
log.warnings(u"unexpected keyword arguments, they will be ignored: {}".format(kwargs))
log.warnings("unexpected keyword arguments, they will be ignored: {}".format(kwargs))
elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
async = True
async_ = True
_errback = args.pop()
_callback = args.pop()
method = getattr(self.db_plugin_iface, name)
if async:
if async_:
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = _callback
kwargs['error_handler'] = lambda err: _errback(dbus_to_bridge_exception(err))
@ -180,7 +180,7 @@ class Bridge(object):
if errback is None:
errback = log.error
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
return unicode(self.db_core_iface.asyncGetParamA(name, category, attribute, security_limit, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler))
return str(self.db_core_iface.asyncGetParamA(name, category, attribute, security_limit, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler))
def asyncGetParamsValuesFromCategory(self, category, security_limit=-1, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
@ -209,7 +209,7 @@ class Bridge(object):
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
return self.db_core_iface.delContact(entity_jid, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler)
def discoFindByFeatures(self, namespaces, identities, bare_jid=False, service=True, roster=True, own_jid=True, local_device=False, profile_key=u"@DEFAULT@", callback=None, errback=None):
def discoFindByFeatures(self, namespaces, identities, bare_jid=False, service=True, roster=True, own_jid=True, local_device=False, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
error_handler = None
else:
@ -218,7 +218,7 @@ class Bridge(object):
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
return self.db_core_iface.discoFindByFeatures(namespaces, identities, bare_jid, service, roster, own_jid, local_device, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler)
def discoInfos(self, entity_jid, node=u'', use_cache=True, profile_key=u"@DEFAULT@", callback=None, errback=None):
def discoInfos(self, entity_jid, node='', use_cache=True, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
error_handler = None
else:
@ -227,7 +227,7 @@ class Bridge(object):
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
return self.db_core_iface.discoInfos(entity_jid, node, use_cache, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler)
def discoItems(self, entity_jid, node=u'', use_cache=True, profile_key=u"@DEFAULT@", callback=None, errback=None):
def discoItems(self, entity_jid, node='', use_cache=True, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
error_handler = None
else:
@ -257,7 +257,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.encryptionNamespaceGet(arg_0, **kwargs))
return str(self.db_core_iface.encryptionNamespaceGet(arg_0, **kwargs))
def encryptionPluginsGet(self, callback=None, errback=None):
if callback is None:
@ -273,14 +273,14 @@ class Bridge(object):
kwargs['error_handler'] = error_handler
return self.db_core_iface.encryptionPluginsGet(**kwargs)
def encryptionTrustUIGet(self, namespace, arg_1, profile_key, callback=None, errback=None):
def encryptionTrustUIGet(self, to_jid, namespace, profile_key, callback=None, errback=None):
if callback is None:
error_handler = None
else:
if errback is None:
errback = log.error
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
return unicode(self.db_core_iface.encryptionTrustUIGet(namespace, arg_1, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler))
return str(self.db_core_iface.encryptionTrustUIGet(to_jid, namespace, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler))
def getConfig(self, section, name, callback=None, errback=None):
if callback is None:
@ -294,7 +294,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.getConfig(section, name, **kwargs))
return str(self.db_core_iface.getConfig(section, name, **kwargs))
def getContacts(self, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
@ -368,7 +368,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.getMainResource(contact_jid, profile_key, **kwargs))
return str(self.db_core_iface.getMainResource(contact_jid, profile_key, **kwargs))
def getParamA(self, name, category, attribute="value", profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
@ -382,7 +382,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.getParamA(name, category, attribute, profile_key, **kwargs))
return str(self.db_core_iface.getParamA(name, category, attribute, profile_key, **kwargs))
def getParamsCategories(self, callback=None, errback=None):
if callback is None:
@ -405,7 +405,7 @@ class Bridge(object):
if errback is None:
errback = log.error
error_handler = lambda err:errback(dbus_to_bridge_exception(err))
return unicode(self.db_core_iface.getParamsUI(security_limit, app, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler))
return str(self.db_core_iface.getParamsUI(security_limit, app, profile_key, timeout=const_TIMEOUT, reply_handler=callback, error_handler=error_handler))
def getPresenceStatuses(self, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
@ -442,7 +442,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.getVersion(**kwargs))
return str(self.db_core_iface.getVersion(**kwargs))
def getWaitingSub(self, profile_key="@DEFAULT@", callback=None, errback=None):
if callback is None:
@ -516,7 +516,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.menuHelpGet(menu_id, language, **kwargs))
return str(self.db_core_iface.menuHelpGet(menu_id, language, **kwargs))
def menuLaunch(self, menu_type, path, data, security_limit, profile_key, callback=None, errback=None):
if callback is None:
@ -553,7 +553,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.messageEncryptionGet(to_jid, profile_key, **kwargs))
return str(self.db_core_iface.messageEncryptionGet(to_jid, profile_key, **kwargs))
def messageEncryptionStart(self, to_jid, namespace='', replace=False, profile_key="@NONE@", callback=None, errback=None):
if callback is None:
@ -645,7 +645,7 @@ class Bridge(object):
kwargs['timeout'] = const_TIMEOUT
kwargs['reply_handler'] = callback
kwargs['error_handler'] = error_handler
return unicode(self.db_core_iface.profileNameGet(profile_key, **kwargs))
return str(self.db_core_iface.profileNameGet(profile_key, **kwargs))
def profileSetDefault(self, profile, callback=None, errback=None):
if callback is None:

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SAT communication bridge
@ -28,7 +28,7 @@ from twisted.internet import reactor
class SignalsHandler(pb.Referenceable):
def __getattr__(self, name):
if name.startswith("remote_"):
log.debug(u"calling an unregistered signal: {name}".format(name=name[7:]))
log.debug("calling an unregistered signal: {name}".format(name=name[7:]))
return lambda *args, **kwargs: None
else:
@ -43,7 +43,7 @@ class SignalsHandler(pb.Referenceable):
pass
else:
raise exceptions.InternalError(
u"{name} signal handler has been registered twice".format(
"{name} signal handler has been registered twice".format(
name=method_name
)
)
@ -99,7 +99,7 @@ class Bridge(object):
d.addErrback(errback)
def _initBridgeEb(self, failure):
log.error(u"Can't init bridge: {msg}".format(msg=failure))
log.error("Can't init bridge: {msg}".format(msg=failure))
def _set_root(self, root):
"""set remote root object
@ -112,7 +112,7 @@ class Bridge(object):
return d
def _generic_errback(self, failure):
log.error(u"bridge failure: {}".format(failure))
log.error("bridge failure: {}".format(failure))
def bridgeConnect(self, callback, errback):
factory = pb.PBClientFactory()
@ -182,7 +182,7 @@ class Bridge(object):
errback = self._generic_errback
d.addErrback(errback)
def discoFindByFeatures(self, namespaces, identities, bare_jid=False, service=True, roster=True, own_jid=True, local_device=False, profile_key=u"@DEFAULT@", callback=None, errback=None):
def discoFindByFeatures(self, namespaces, identities, bare_jid=False, service=True, roster=True, own_jid=True, local_device=False, profile_key="@DEFAULT@", callback=None, errback=None):
d = self.root.callRemote("discoFindByFeatures", namespaces, identities, bare_jid, service, roster, own_jid, local_device, profile_key)
if callback is not None:
d.addCallback(callback)
@ -190,7 +190,7 @@ class Bridge(object):
errback = self._generic_errback
d.addErrback(errback)
def discoInfos(self, entity_jid, node=u'', use_cache=True, profile_key=u"@DEFAULT@", callback=None, errback=None):
def discoInfos(self, entity_jid, node='', use_cache=True, profile_key="@DEFAULT@", callback=None, errback=None):
d = self.root.callRemote("discoInfos", entity_jid, node, use_cache, profile_key)
if callback is not None:
d.addCallback(callback)
@ -198,7 +198,7 @@ class Bridge(object):
errback = self._generic_errback
d.addErrback(errback)
def discoItems(self, entity_jid, node=u'', use_cache=True, profile_key=u"@DEFAULT@", callback=None, errback=None):
def discoItems(self, entity_jid, node='', use_cache=True, profile_key="@DEFAULT@", callback=None, errback=None):
d = self.root.callRemote("discoItems", entity_jid, node, use_cache, profile_key)
if callback is not None:
d.addCallback(callback)
@ -230,8 +230,8 @@ class Bridge(object):
errback = self._generic_errback
d.addErrback(errback)
def encryptionTrustUIGet(self, namespace, arg_1, profile_key, callback=None, errback=None):
d = self.root.callRemote("encryptionTrustUIGet", namespace, arg_1, profile_key)
def encryptionTrustUIGet(self, to_jid, namespace, profile_key, callback=None, errback=None):
d = self.root.callRemote("encryptionTrustUIGet", to_jid, namespace, profile_key)
if callback is not None:
d.addCallback(callback)
if errback is None:

View file

@ -28,7 +28,7 @@ def escape(arg, smart=True):
"""
if smart and not " " in arg and not '"' in arg:
return arg
return u'"' + arg.replace(u'"', u'\\"') + u'"'
return '"' + arg.replace('"', '\\"') + '"'
def get_cmd_choices(cmd=None, parser=None):
@ -76,23 +76,23 @@ def get_use_args(host, args, use, verbose=False, parser=None):
opt_args = []
pos_args = []
actions = {a.dest: a for a in parser._actions}
for arg, value in use.iteritems():
for arg, value in use.items():
try:
if arg == u"item" and not u"item" in actions:
if arg == "item" and not "item" in actions:
# small hack when --item is appended to a --items list
arg = u"items"
arg = "items"
action = actions[arg]
except KeyError:
if verbose:
host.disp(
_(
u"ignoring {name}={value}, not corresponding to any argument (in USE)"
"ignoring {name}={value}, not corresponding to any argument (in USE)"
).format(name=arg, value=escape(value))
)
else:
if verbose:
host.disp(
_(u"arg {name}={value} (in USE)").format(
_("arg {name}={value} (in USE)").format(
name=arg, value=escape(value)
)
)

View file

@ -78,7 +78,7 @@ if 'dbus' in bridge_name:
GLib.timeout_add(delay, callback, *args)
else:
print u"can't start jp: only D-Bus bridge is currently handled"
print("can't start jp: only D-Bus bridge is currently handled")
sys.exit(C.EXIT_ERROR)
# FIXME: twisted loop can be used when jp can handle fully async bridges
# from twisted.internet import reactor
@ -104,28 +104,20 @@ if bridge_name == "embedded":
from sat.core import sat_main
sat = sat_main.SAT()
if sys.version_info < (2, 7, 3):
# XXX: shlex.split only handle unicode since python 2.7.3
# this is a workaround for older versions
old_split = shlex.split
new_split = (lambda s, *a, **kw: [t.decode('utf-8') for t in old_split(s.encode('utf-8'), *a, **kw)]
if isinstance(s, unicode) else old_split(s, *a, **kw))
shlex.split = new_split
try:
import progressbar
except ImportError:
msg = (_(u'ProgressBar not available, please download it at http://pypi.python.org/pypi/progressbar\n') +
_(u'Progress bar deactivated\n--\n'))
print >>sys.stderr,msg.encode('utf-8')
msg = (_('ProgressBar not available, please download it at http://pypi.python.org/pypi/progressbar\n') +
_('Progress bar deactivated\n--\n'))
print(msg.encode('utf-8'), file=sys.stderr)
progressbar=None
#consts
PROG_NAME = u"jp"
PROG_NAME = "jp"
DESCRIPTION = """This software is a command line tool for XMPP.
Get the latest version at """ + C.APP_URL
COPYLEFT = u"""Copyright (C) 2009-2019 Jérôme Poisson, Adrien Cossa
COPYLEFT = """Copyright (C) 2009-2019 Jérôme Poisson, Adrien Cossa
This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it under certain conditions.
"""
@ -133,11 +125,6 @@ This is free software, and you are welcome to redistribute it under certain cond
PROGRESS_DELAY = 10 # the progression will be checked every PROGRESS_DELAY ms
def unicode_decoder(arg):
# Needed to have unicode strings from arguments
return arg.decode(locale.getpreferredencoding())
def date_decoder(arg):
return date_utils.date_parse_ext(arg, default_tz=date_utils.TZ_LOCAL)
@ -167,7 +154,7 @@ class Jp(object):
# loop will always be needed
bridge_module = dynamic_import.bridge(bridge_name, 'sat_frontends.bridge')
if bridge_module is None:
log.error(u"Can't import {} bridge".format(bridge_name))
log.error("Can't import {} bridge".format(bridge_name))
sys.exit(1)
self.bridge = bridge_module.Bridge()
@ -178,7 +165,7 @@ class Jp(object):
description=DESCRIPTION)
self._make_parents()
self.add_parser_options()
self.subparsers = self.parser.add_subparsers(title=_(u'Available commands'), dest='subparser_name')
self.subparsers = self.parser.add_subparsers(title=_('Available commands'), dest='subparser_name')
self._auto_loop = False # when loop is used for internal reasons
self._need_loop = False
@ -196,11 +183,11 @@ class Jp(object):
def _bridgeEb(self, failure):
if isinstance(failure, exceptions.BridgeExceptionNoService):
print(_(u"Can't connect to SàT backend, are you sure it's launched ?"))
print((_("Can't connect to SàT backend, are you sure it's launched ?")))
elif isinstance(failure, exceptions.BridgeInitError):
print(_(u"Can't init bridge"))
print((_("Can't init bridge")))
else:
print(_(u"Error while initialising bridge: {}".format(failure)))
print((_("Error while initialising bridge: {}".format(failure))))
sys.exit(C.EXIT_BRIDGE_ERROR)
@property
@ -264,14 +251,14 @@ class Jp(object):
if self.verbosity >= verbosity:
if error:
if no_lf:
print >>sys.stderr,msg.encode('utf-8'),
print(msg, end=' ', file=sys.stderr)
else:
print >>sys.stderr,msg.encode('utf-8')
print(msg, file=sys.stderr)
else:
if no_lf:
print msg.encode('utf-8'),
print(msg, end=' ')
else:
print msg.encode('utf-8')
print(msg)
def output(self, type_, name, extra_outputs, data):
if name in extra_outputs:
@ -297,7 +284,7 @@ class Jp(object):
@param output_type: True for default,
else can be any registered type
"""
return self._outputs[output_type].keys()
return list(self._outputs[output_type].keys())
def _make_parents(self):
self.parents = {}
@ -307,11 +294,11 @@ class Jp(object):
for parent_name in ('profile', 'profile_session'):
parent = self.parents[parent_name] = argparse.ArgumentParser(add_help=False)
parent.add_argument("-p", "--profile", action="store", type=str, default='@DEFAULT@', help=_("Use PROFILE profile key (default: %(default)s)"))
parent.add_argument("--pwd", action="store", type=unicode_decoder, default='', metavar='PASSWORD', help=_("Password used to connect profile, if necessary"))
parent.add_argument("--pwd", action="store", default='', metavar='PASSWORD', help=_("Password used to connect profile, if necessary"))
profile_parent, profile_session_parent = self.parents['profile'], self.parents['profile_session']
connect_short, connect_long, connect_action, connect_help = "-c", "--connect", "store_true", _(u"Connect the profile before doing anything else")
connect_short, connect_long, connect_action, connect_help = "-c", "--connect", "store_true", _("Connect the profile before doing anything else")
profile_parent.add_argument(connect_short, connect_long, action=connect_action, help=connect_help)
profile_session_connect_group = profile_session_parent.add_mutually_exclusive_group()
@ -323,12 +310,12 @@ class Jp(object):
progress_parent.add_argument("-P", "--progress", action="store_true", help=_("Show progress bar"))
verbose_parent = self.parents['verbose'] = argparse.ArgumentParser(add_help=False)
verbose_parent.add_argument('--verbose', '-v', action='count', default=0, help=_(u"Add a verbosity level (can be used multiple times)"))
verbose_parent.add_argument('--verbose', '-v', action='count', default=0, help=_("Add a verbosity level (can be used multiple times)"))
draft_parent = self.parents['draft'] = argparse.ArgumentParser(add_help=False)
draft_group = draft_parent.add_argument_group(_('draft handling'))
draft_group.add_argument("-D", "--current", action="store_true", help=_(u"load current draft"))
draft_group.add_argument("-F", "--draft-path", type=unicode_decoder, help=_(u"path to a draft file to retrieve"))
draft_group.add_argument("-D", "--current", action="store_true", help=_("load current draft"))
draft_group.add_argument("-F", "--draft-path", help=_("path to a draft file to retrieve"))
def make_pubsub_group(self, flags, defaults):
@ -343,71 +330,71 @@ class Jp(object):
flags = misc.FlagsHandler(flags)
parent = argparse.ArgumentParser(add_help=False)
pubsub_group = parent.add_argument_group('pubsub')
pubsub_group.add_argument("-u", "--pubsub-url", type=unicode_decoder,
help=_(u"Pubsub URL (xmpp or http)"))
pubsub_group.add_argument("-u", "--pubsub-url",
help=_("Pubsub URL (xmpp or http)"))
service_help = _(u"JID of the PubSub service")
service_help = _("JID of the PubSub service")
if not flags.service:
default = defaults.pop(u'service', _(u'PEP service'))
default = defaults.pop('service', _('PEP service'))
if default is not None:
service_help += _(u" (DEFAULT: {default})".format(default=default))
pubsub_group.add_argument("-s", "--service", type=unicode_decoder, default=u'',
service_help += _(" (DEFAULT: {default})".format(default=default))
pubsub_group.add_argument("-s", "--service", default='',
help=service_help)
node_help = _(u"node to request")
node_help = _("node to request")
if not flags.node:
default = defaults.pop(u'node', _(u'standard node'))
default = defaults.pop('node', _('standard node'))
if default is not None:
node_help += _(u" (DEFAULT: {default})".format(default=default))
pubsub_group.add_argument("-n", "--node", type=unicode_decoder, default=u'', help=node_help)
node_help += _(" (DEFAULT: {default})".format(default=default))
pubsub_group.add_argument("-n", "--node", default='', help=node_help)
if flags.single_item:
item_help = (u"item to retrieve")
item_help = ("item to retrieve")
if not flags.item:
default = defaults.pop(u'item', _(u'last item'))
default = defaults.pop('item', _('last item'))
if default is not None:
item_help += _(u" (DEFAULT: {default})".format(default=default))
pubsub_group.add_argument("-i", "--item", type=unicode_decoder, default=u'',
item_help += _(" (DEFAULT: {default})".format(default=default))
pubsub_group.add_argument("-i", "--item", default='',
help=item_help)
pubsub_group.add_argument("-L", "--last-item", action='store_true', help=_(u'retrieve last item'))
pubsub_group.add_argument("-L", "--last-item", action='store_true', help=_('retrieve last item'))
elif flags.multi_items:
# mutiple items, this activate several features: max-items, RSM, MAM
# and Orbder-by
pubsub_group.add_argument("-i", "--item", type=unicode_decoder, action='append', dest='items', default=[], help=_(u"items to retrieve (DEFAULT: all)"))
pubsub_group.add_argument("-i", "--item", action='append', dest='items', default=[], help=_("items to retrieve (DEFAULT: all)"))
if not flags.no_max:
max_group = pubsub_group.add_mutually_exclusive_group()
# XXX: defaut value for --max-items or --max is set in parse_pubsub_args
max_group.add_argument(
"-M", "--max-items", dest="max", type=int,
help=_(u"maximum number of items to get ({no_limit} to get all items)"
help=_("maximum number of items to get ({no_limit} to get all items)"
.format(no_limit=C.NO_LIMIT)))
# FIXME: it could be possible to no duplicate max (between pubsub
# max-items and RSM max)should not be duplicated, RSM could be
# used when available and pubsub max otherwise
max_group.add_argument(
"-m", "--max", dest="rsm_max", type=int,
help=_(u"maximum number of items to get per page (DEFAULT: 10)"))
help=_("maximum number of items to get per page (DEFAULT: 10)"))
# RSM
rsm_page_group = pubsub_group.add_mutually_exclusive_group()
rsm_page_group.add_argument(
"-a", "--after", dest="rsm_after", type=unicode_decoder,
help=_(u"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", type=unicode_decoder,
help=_(u"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=_(u"index of the page to retrieve"))
help=_("index of the page to retrieve"))
# MAM
pubsub_group.add_argument(
"-f", "--filter", dest='mam_filters', type=unicode_decoder, nargs=2,
action='append', default=[], help=_(u"MAM filters to use"),
metavar=(u"FILTER_NAME", u"VALUE")
"-f", "--filter", dest='mam_filters', nargs=2,
action='append', default=[], help=_("MAM filters to use"),
metavar=("FILTER_NAME", "VALUE")
)
# Order-By
@ -419,10 +406,10 @@ class Jp(object):
pubsub_group.add_argument(
"-o", "--order-by", choices=[C.ORDER_BY_CREATION,
C.ORDER_BY_MODIFICATION],
help=_(u"how items should be ordered"))
help=_("how items should be ordered"))
if not flags.all_used:
raise exceptions.InternalError('unknown flags: {flags}'.format(flags=u', '.join(flags.unused)))
raise exceptions.InternalError('unknown flags: {flags}'.format(flags=', '.join(flags.unused)))
if defaults:
raise exceptions.InternalError('unused defaults: {defaults}'.format(defaults=defaults))
@ -433,14 +420,14 @@ class Jp(object):
def register_output(self, type_, name, callback, description="", default=False):
if type_ not in C.OUTPUT_TYPES:
log.error(u"Invalid output type {}".format(type_))
log.error("Invalid output type {}".format(type_))
return
self._outputs[type_][name] = {'callback': callback,
'description': description
}
if default:
if type_ in self.default_output:
self.disp(_(u'there is already a default output for {}, ignoring new one').format(type_))
self.disp(_('there is already a default output for {}, ignoring new one').format(type_))
else:
self.default_output[type_] = name
@ -450,7 +437,7 @@ class Jp(object):
options_dict = {}
for option in options:
try:
key, value = option.split(u'=', 1)
key, value = option.split('=', 1)
except ValueError:
key, value = option, None
options_dict[key.strip()] = value.strip() if value is not None else None
@ -458,8 +445,8 @@ class Jp(object):
def check_output_options(self, accepted_set, options):
if not accepted_set.issuperset(options):
self.disp(u"The following output options are invalid: {invalid_options}".format(
invalid_options = u', '.join(set(options).difference(accepted_set))),
self.disp("The following output options are invalid: {invalid_options}".format(
invalid_options = ', '.join(set(options).difference(accepted_set))),
error=True)
self.quit(C.EXIT_BAD_ARG)
@ -478,13 +465,13 @@ class Jp(object):
module = import_module(module_path)
self.import_plugin_module(module, type_)
except ImportError as e:
self.disp(_(u"Can't import {module_path} plugin, ignoring it: {msg}".format(
self.disp(_("Can't import {module_path} plugin, ignoring it: {msg}".format(
module_path = module_path,
msg = e)), error=True)
except exceptions.CancelError:
continue
except exceptions.MissingModule as e:
self.disp(_(u"Missing module for plugin {name}: {missing}".format(
self.disp(_("Missing module for plugin {name}: {missing}".format(
name = module_path,
missing = e)), error=True)
@ -498,7 +485,7 @@ class Jp(object):
try:
class_names = getattr(module, '__{}__'.format(type_))
except AttributeError:
log.disp(_(u"Invalid plugin module [{type}] {module}").format(type=type_, module=module), error=True)
log.disp(_("Invalid plugin module [{type}] {module}").format(type=type_, module=module), error=True)
raise ImportError
else:
for class_name in class_names:
@ -508,29 +495,29 @@ class Jp(object):
def get_xmpp_uri_from_http(self, http_url):
"""parse HTML page at http(s) URL, and looks for xmpp: uri"""
if http_url.startswith('https'):
scheme = u'https'
scheme = 'https'
elif http_url.startswith('http'):
scheme = u'http'
scheme = 'http'
else:
raise exceptions.InternalError(u'An HTTP scheme is expected in this method')
self.disp(u"{scheme} URL found, trying to find associated xmpp: URI".format(scheme=scheme.upper()),1)
raise exceptions.InternalError('An HTTP scheme is expected in this method')
self.disp("{scheme} URL found, trying to find associated xmpp: URI".format(scheme=scheme.upper()),1)
# HTTP URL, we try to find xmpp: links
try:
from lxml import etree
except ImportError:
self.disp(u"lxml module must be installed to use http(s) scheme, please install it with \"pip install lxml\"", error=True)
self.disp("lxml module must be installed to use http(s) scheme, please install it with \"pip install lxml\"", error=True)
self.quit(1)
import urllib2
import urllib.request, urllib.error, urllib.parse
parser = etree.HTMLParser()
try:
root = etree.parse(urllib2.urlopen(http_url), parser)
root = etree.parse(urllib.request.urlopen(http_url), parser)
except etree.XMLSyntaxError as e:
self.disp(_(u"Can't parse HTML page : {msg}").format(msg=e))
self.disp(_("Can't parse HTML page : {msg}").format(msg=e))
links = []
else:
links = root.xpath("//link[@rel='alternate' and starts-with(@href, 'xmpp:')]")
if not links:
self.disp(u'Could not find alternate "xmpp:" URI, can\'t find associated XMPP PubSub node/item', error=True)
self.disp('Could not find alternate "xmpp:" URI, can\'t find associated XMPP PubSub node/item', error=True)
self.quit(1)
xmpp_uri = links[0].get('href')
return xmpp_uri
@ -546,15 +533,15 @@ class Jp(object):
try:
uri_data = uri.parseXMPPUri(url)
except ValueError:
self.parser.error(_(u'invalid XMPP URL: {url}').format(url=url))
self.parser.error(_('invalid XMPP URL: {url}').format(url=url))
else:
if uri_data[u'type'] == 'pubsub':
if uri_data['type'] == 'pubsub':
# URL is alright, we only set data not already set by other options
if not self.args.service:
self.args.service = uri_data[u'path']
self.args.service = uri_data['path']
if not self.args.node:
self.args.node = uri_data[u'node']
uri_item = uri_data.get(u'item')
self.args.node = uri_data['node']
uri_item = uri_data.get('item')
if uri_item:
# there is an item in URI
# we use it only if item is not already set
@ -565,7 +552,7 @@ class Jp(object):
try:
items = self.args.items
except AttributeError:
self.disp(_(u"item specified in URL but not needed in command, ignoring it"), error=True)
self.disp(_("item specified in URL but not needed in command, ignoring it"), error=True)
else:
if not items:
self.args.items = [uri_item]
@ -578,22 +565,22 @@ class Jp(object):
if not item_last:
self.args.item = uri_item
else:
self.parser.error(_(u'XMPP URL is not a pubsub one: {url}').format(url=url))
self.parser.error(_('XMPP URL is not a pubsub one: {url}').format(url=url))
flags = self.args._cmd._pubsub_flags
# we check required arguments here instead of using add_arguments' required option
# because the required argument can be set in URL
if C.SERVICE in flags and not self.args.service:
self.parser.error(_(u"argument -s/--service is required"))
self.parser.error(_("argument -s/--service is required"))
if C.NODE in flags and not self.args.node:
self.parser.error(_(u"argument -n/--node is required"))
self.parser.error(_("argument -n/--node is required"))
if C.ITEM in flags and not self.args.item:
self.parser.error(_(u"argument -i/--item is required"))
self.parser.error(_("argument -i/--item is required"))
# FIXME: mutually groups can't be nested in a group and don't support title
# so we check conflict here. This may be fixed in Python 3, to be checked
try:
if self.args.item and self.args.item_last:
self.parser.error(_(u"--item and --item-last can't be used at the same time"))
self.parser.error(_("--item and --item-last can't be used at the same time"))
except AttributeError:
pass
@ -639,10 +626,10 @@ class Jp(object):
except AttributeError:
pass
def confirmOrQuit(self, message, cancel_message=_(u"action cancelled by user")):
def confirmOrQuit(self, message, cancel_message=_("action cancelled by user")):
"""Request user to confirm action, and quit if he doesn't"""
res = raw_input("{} (y/N)? ".format(message))
res = input("{} (y/N)? ".format(message))
if res not in ("y", "Y"):
self.disp(cancel_message)
self.quit(C.EXIT_USER_CANCELLED)
@ -728,11 +715,11 @@ class Jp(object):
# FIXME: need better exit codes
def cant_connect(failure):
log.error(_(u"Can't connect profile: {reason}").format(reason=failure))
log.error(_("Can't connect profile: {reason}").format(reason=failure))
self.quit(1)
def cant_start_session(failure):
log.error(_(u"Can't start {profile}'s session: {reason}").format(profile=self.profile, reason=failure))
log.error(_("Can't start {profile}'s session: {reason}").format(profile=self.profile, reason=failure))
self.quit(1)
self.profile = self.bridge.profileNameGet(self.args.profile)
@ -752,7 +739,7 @@ class Jp(object):
return
elif not self.bridge.profileIsSessionStarted(self.profile):
if not self.args.connect:
log.error(_(u"Session for [{profile}] is not started, please start it before using jp, or use either --start-session or --connect option").format(profile=self.profile))
log.error(_("Session for [{profile}] is not started, please start it before using jp, or use either --start-session or --connect option").format(profile=self.profile))
self.quit(1)
elif not getattr(self.args, "connect", False):
callback()
@ -768,7 +755,7 @@ class Jp(object):
return
else:
if not self.bridge.isConnected(self.profile):
log.error(_(u"Profile [{profile}] is not connected, please connect it before using jp, or use --connect option").format(profile=self.profile))
log.error(_("Profile [{profile}] is not connected, please connect it before using jp, or use --connect option").format(profile=self.profile))
self.quit(1)
callback()
@ -855,14 +842,14 @@ class CommandBase(object):
try:
default = self.host.default_output[use_output]
except KeyError:
if u'default' in choices:
default = u'default'
elif u'simple' in choices:
default = u'simple'
if 'default' in choices:
default = 'default'
elif 'simple' in choices:
default = 'simple'
else:
default = list(choices)[0]
output_parent.add_argument('--output', '-O', choices=sorted(choices), default=default, help=_(u"select output format (default: {})".format(default)))
output_parent.add_argument('--output-option', '--oo', type=unicode_decoder, action="append", dest='output_opts', default=[], help=_(u"output specific option"))
output_parent.add_argument('--output', '-O', choices=sorted(choices), default=default, help=_("select output format (default: {})".format(default)))
output_parent.add_argument('--output-option', '--oo', action="append", dest='output_opts', default=[], help=_("output specific option"))
parents.add(output_parent)
else:
assert extra_outputs is None
@ -875,11 +862,11 @@ class CommandBase(object):
self._pubsub_flags = flags
# other common options
use_opts = {k:v for k,v in kwargs.iteritems() if k.startswith('use_')}
for param, do_use in use_opts.iteritems():
use_opts = {k:v for k,v in kwargs.items() if k.startswith('use_')}
for param, do_use in use_opts.items():
opt=param[4:] # if param is use_verbose, opt is verbose
if opt not in self.host.parents:
raise exceptions.InternalError(u"Unknown parent option {}".format(opt))
raise exceptions.InternalError("Unknown parent option {}".format(opt))
del kwargs[param]
if do_use:
parents.add(self.host.parents[opt])
@ -957,12 +944,12 @@ class CommandBase(object):
try:
size = data['size']
except KeyError:
self.disp(_(u"file size is not known, we can't show a progress bar"), 1, error=True)
self.disp(_("file size is not known, we can't show a progress bar"), 1, error=True)
return False
if self.host.pbar is None:
#first answer, we must construct the bar
self.host.pbar = progressbar.ProgressBar(max_value=int(size),
widgets=[_(u"Progress: "),progressbar.Percentage(),
widgets=[_("Progress: "),progressbar.Percentage(),
" ",
progressbar.Bar(),
" ",
@ -986,7 +973,7 @@ class CommandBase(object):
can be overidden by a command
@param metadata(dict): metadata as sent by bridge.progressStarted
"""
self.disp(_(u"Operation started"), 2)
self.disp(_("Operation started"), 2)
def onProgressUpdate(self, metadata):
"""Method called on each progress updata
@ -1002,14 +989,14 @@ class CommandBase(object):
can be overidden by a command
@param metadata(dict): metadata as sent by bridge.progressFinished
"""
self.disp(_(u"Operation successfully finished"), 2)
self.disp(_("Operation successfully finished"), 2)
def onProgressError(self, error_msg):
"""Called when a progress failed
@param error_msg(unicode): error message as sent by bridge.progressError
"""
self.disp(_(u"Error while doing operation: {}").format(error_msg), error=True)
self.disp(_("Error while doing operation: {}").format(error_msg), error=True)
def disp(self, msg, verbosity=0, error=False, no_lf=False):
return self.host.disp(msg, verbosity, error, no_lf)
@ -1018,7 +1005,7 @@ class CommandBase(object):
try:
output_type = self._output_type
except AttributeError:
raise exceptions.InternalError(_(u'trying to use output when use_output has not been set'))
raise exceptions.InternalError(_('trying to use output when use_output has not been set'))
return self.host.output(output_type, self.args.output, self.extra_outputs, data)
def exitCb(self, msg=None):
@ -1041,7 +1028,7 @@ class CommandBase(object):
@param exit_code(int): shell exit code
"""
if msg is None:
msg = _(u"error: {}")
msg = _("error: {}")
self.disp(msg.format(failure_), error=True)
self.host.quit(exit_code)
@ -1054,31 +1041,31 @@ class CommandBase(object):
if extra is None:
extra = {}
else:
intersection = {C.KEY_ORDER_BY}.intersection(extra.keys())
intersection = {C.KEY_ORDER_BY}.intersection(list(extra.keys()))
if intersection:
raise exceptions.ConflictError(
u"given extra dict has conflicting keys with pubsub keys "
u"{intersection}".format(intersection=intersection))
"given extra dict has conflicting keys with pubsub keys "
"{intersection}".format(intersection=intersection))
# RSM
for attribute in (u'max', u'after', u'before', 'index'):
key = u'rsm_' + attribute
for attribute in ('max', 'after', 'before', 'index'):
key = 'rsm_' + attribute
if key in extra:
raise exceptions.ConflictError(
u"This key already exists in extra: u{key}".format(key=key))
"This key already exists in extra: u{key}".format(key=key))
value = getattr(self.args, key, None)
if value is not None:
extra[key] = unicode(value)
extra[key] = str(value)
# MAM
if hasattr(self.args, u'mam_filters'):
if hasattr(self.args, 'mam_filters'):
for key, value in self.args.mam_filters:
key = u'filter_' + key
key = 'filter_' + key
if key in extra:
raise exceptions.ConflictError(
u"This key already exists in extra: u{key}".format(key=key))
"This key already exists in extra: u{key}".format(key=key))
extra[key] = value
# Order-By

View file

@ -37,45 +37,42 @@ class AccountCreate(base.CommandBase):
"create",
use_profile=False,
use_verbose=True,
help=_(u"create a XMPP account"),
help=_("create a XMPP account"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"jid", type=base.unicode_decoder, help=_(u"jid to create")
"jid", help=_("jid to create")
)
self.parser.add_argument(
"password", type=base.unicode_decoder, help=_(u"password of the account")
"password", help=_("password of the account")
)
self.parser.add_argument(
"-p",
"--profile",
type=base.unicode_decoder,
help=_(
u"create a profile to use this account (default: don't create profile)"
"create a profile to use this account (default: don't create profile)"
),
)
self.parser.add_argument(
"-e",
"--email",
type=base.unicode_decoder,
default="",
help=_(u"email (usage depends of XMPP server)"),
help=_("email (usage depends of XMPP server)"),
)
self.parser.add_argument(
"-H",
"--host",
type=base.unicode_decoder,
default="",
help=_(u"server host (IP address or domain, default: use localhost)"),
help=_("server host (IP address or domain, default: use localhost)"),
)
self.parser.add_argument(
"-P",
"--port",
type=int,
default=0,
help=_(u"server port (IP address or domain, default: use localhost)"),
help=_("server port (IP address or domain, default: use localhost)"),
)
def _setParamCb(self):
@ -99,7 +96,7 @@ class AccountCreate(base.CommandBase):
)
def _profileCreateCb(self):
self.disp(_(u"profile created"), 1)
self.disp(_("profile created"), 1)
self.host.bridge.profileStartSession(
self.args.password,
self.args.profile,
@ -110,16 +107,16 @@ class AccountCreate(base.CommandBase):
def _profileCreateEb(self, failure_):
self.disp(
_(
u"Can't create profile {profile} to associate with jid {jid}: {msg}"
"Can't create profile {profile} to associate with jid {jid}: {msg}"
).format(profile=self.args.profile, jid=self.args.jid, msg=failure_),
error=True,
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
def accountNewCb(self):
self.disp(_(u"XMPP account created"), 1)
self.disp(_("XMPP account created"), 1)
if self.args.profile is not None:
self.disp(_(u"creating profile"), 2)
self.disp(_("creating profile"), 2)
self.host.bridge.profileCreate(
self.args.profile,
self.args.password,
@ -132,8 +129,8 @@ class AccountCreate(base.CommandBase):
def accountNewEb(self, failure_):
self.disp(
_(u"Can't create new account on server {host} with jid {jid}: {msg}").format(
host=self.args.host or u"localhost", jid=self.args.jid, msg=failure_
_("Can't create new account on server {host} with jid {jid}: {msg}").format(
host=self.args.host or "localhost", jid=self.args.jid, msg=failure_
),
error=True,
)
@ -154,13 +151,13 @@ class AccountCreate(base.CommandBase):
class AccountModify(base.CommandBase):
def __init__(self, host):
super(AccountModify, self).__init__(
host, "modify", help=_(u"change password for XMPP account")
host, "modify", help=_("change password for XMPP account")
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"password", type=base.unicode_decoder, help=_(u"new XMPP password")
"password", help=_("new XMPP password")
)
def start(self):
@ -175,7 +172,7 @@ class AccountModify(base.CommandBase):
class AccountDelete(base.CommandBase):
def __init__(self, host):
super(AccountDelete, self).__init__(
host, "delete", help=_(u"delete a XMPP account")
host, "delete", help=_("delete a XMPP account")
)
self.need_loop = True
@ -184,22 +181,22 @@ class AccountDelete(base.CommandBase):
"-f",
"--force",
action="store_true",
help=_(u"delete account without confirmation"),
help=_("delete account without confirmation"),
)
def _got_jid(self, jid_str):
jid_ = jid.JID(jid_str)
if not self.args.force:
message = (
u"You are about to delete the XMPP account with jid {jid_}\n"
u'This is the XMPP account of profile "{profile}"\n'
u"Are you sure that you want to delete this account ?".format(
"You are about to delete the XMPP account with jid {jid_}\n"
'This is the XMPP account of profile "{profile}"\n'
"Are you sure that you want to delete this account ?".format(
jid_=jid_, profile=self.profile
)
)
res = raw_input("{} (y/N)? ".format(message))
res = input("{} (y/N)? ".format(message))
if res not in ("y", "Y"):
self.disp(_(u"Account deletion cancelled"))
self.disp(_("Account deletion cancelled"))
self.host.quit(2)
self.host.bridge.inBandUnregister(
jid_.domain, self.args.profile, callback=self.host.quit, errback=self.errback
@ -220,5 +217,5 @@ class Account(base.CommandBase):
def __init__(self, host):
super(Account, self).__init__(
host, "account", use_profile=False, help=(u"XMPP account management")
host, "account", use_profile=False, help=("XMPP account management")
)

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from functools import partial
from sat_frontends.jp.constants import Const as C
@ -32,43 +32,39 @@ MAGIC_BAREJID = "@PROFILE_BAREJID@"
class Remote(base.CommandBase):
def __init__(self, host):
super(Remote, self).__init__(
host, "remote", use_verbose=True, help=_(u"remote control a software")
host, "remote", use_verbose=True, help=_("remote control a software")
)
def add_parser_options(self):
self.parser.add_argument("software", type=str, help=_(u"software name"))
self.parser.add_argument("software", type=str, help=_("software name"))
self.parser.add_argument(
"-j",
"--jids",
type=base.unicode_decoder,
nargs="*",
default=[],
help=_(u"jids allowed to use the command"),
help=_("jids allowed to use the command"),
)
self.parser.add_argument(
"-g",
"--groups",
type=base.unicode_decoder,
nargs="*",
default=[],
help=_(u"groups allowed to use the command"),
help=_("groups allowed to use the command"),
)
self.parser.add_argument(
"--forbidden-groups",
type=base.unicode_decoder,
nargs="*",
default=[],
help=_(u"groups that are *NOT* allowed to use the command"),
help=_("groups that are *NOT* allowed to use the command"),
)
self.parser.add_argument(
"--forbidden-jids",
type=base.unicode_decoder,
nargs="*",
default=[],
help=_(u"jids that are *NOT* allowed to use the command"),
help=_("jids that are *NOT* allowed to use the command"),
)
self.parser.add_argument(
"-l", "--loop", action="store_true", help=_(u"loop on the commands")
"-l", "--loop", action="store_true", help=_("loop on the commands")
)
def start(self):
@ -109,7 +105,7 @@ class Run(base.CommandBase):
def __init__(self, host):
super(Run, self).__init__(
host, "run", use_verbose=True, help=_(u"run an Ad-Hoc command")
host, "run", use_verbose=True, help=_("run an Ad-Hoc command")
)
self.need_loop = True
@ -117,9 +113,8 @@ class Run(base.CommandBase):
self.parser.add_argument(
"-j",
"--jid",
type=base.unicode_decoder,
default=u"",
help=_(u"jid of the service (default: profile's server"),
default="",
help=_("jid of the service (default: profile's server"),
)
self.parser.add_argument(
"-S",
@ -127,24 +122,22 @@ class Run(base.CommandBase):
action="append_const",
const=xmlui_manager.SUBMIT,
dest="workflow",
help=_(u"submit form/page"),
help=_("submit form/page"),
)
self.parser.add_argument(
"-f",
"--field",
type=base.unicode_decoder,
action="append",
nargs=2,
dest="workflow",
metavar=(u"KEY", u"VALUE"),
help=_(u"field value"),
metavar=("KEY", "VALUE"),
help=_("field value"),
)
self.parser.add_argument(
"node",
type=base.unicode_decoder,
nargs="?",
default=u"",
help=_(u"node of the command (default: list commands)"),
default="",
help=_("node of the command (default: list commands)"),
)
def adHocRunCb(self, xmlui_raw):
@ -165,7 +158,7 @@ class Run(base.CommandBase):
callback=self.adHocRunCb,
errback=partial(
self.errback,
msg=_(u"can't get ad-hoc commands list: {}"),
msg=_("can't get ad-hoc commands list: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -176,7 +169,7 @@ class List(base.CommandBase):
def __init__(self, host):
super(List, self).__init__(
host, "list", use_verbose=True, help=_(u"list Ad-Hoc commands of a service")
host, "list", use_verbose=True, help=_("list Ad-Hoc commands of a service")
)
self.need_loop = True
@ -184,9 +177,8 @@ class List(base.CommandBase):
self.parser.add_argument(
"-j",
"--jid",
type=base.unicode_decoder,
default=u"",
help=_(u"jid of the service (default: profile's server"),
default="",
help=_("jid of the service (default: profile's server"),
)
def adHocListCb(self, xmlui_raw):
@ -202,7 +194,7 @@ class List(base.CommandBase):
callback=self.adHocListCb,
errback=partial(
self.errback,
msg=_(u"can't get ad-hoc commands list: {}"),
msg=_("can't get ad-hoc commands list: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
import os
import os.path
from sat.core.i18n import _
@ -47,7 +47,7 @@ class Set(base.CommandBase):
"""Send files to jabber contact"""
path = self.args.image_path
if not os.path.exists(path):
self.disp(_(u"file [{}] doesn't exist !").format(path), error=True)
self.disp(_("file [{}] doesn't exist !").format(path), error=True)
self.host.quit(1)
path = os.path.abspath(path)
self.host.bridge.avatarSet(
@ -73,9 +73,9 @@ class Get(base.CommandBase):
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument("jid", type=base.unicode_decoder, help=_("entity"))
self.parser.add_argument("jid", help=_("entity"))
self.parser.add_argument(
"-s", "--show", action="store_true", help=_(u"show avatar")
"-s", "--show", action="store_true", help=_("show avatar")
)
def showImage(self, path):
@ -100,7 +100,7 @@ class Get(base.CommandBase):
def _avatarGetCb(self, avatar_path):
if not avatar_path:
self.disp(_(u"No avatar found."), 1)
self.disp(_("No avatar found."), 1)
self.host.quit(C.EXIT_NOT_FOUND)
self.disp(avatar_path)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat_frontends.jp import common
@ -26,7 +26,7 @@ from sat.tools.common.ansi import ANSI as A
from sat.tools.common import data_objects
from sat.tools.common import uri
from sat.tools import config
from ConfigParser import NoSectionError, NoOptionError
from configparser import NoSectionError, NoOptionError
from functools import partial
import json
import sys
@ -40,7 +40,7 @@ from sat.tools.common import data_format
__commands__ = ["Blog"]
SYNTAX_XHTML = u"xhtml"
SYNTAX_XHTML = "xhtml"
# extensions to use with known syntaxes
SYNTAX_EXT = {
# FIXME: default syntax doesn't sounds needed, there should always be a syntax set
@ -51,8 +51,8 @@ SYNTAX_EXT = {
}
CONF_SYNTAX_EXT = u"syntax_ext_dict"
BLOG_TMP_DIR = u"blog"
CONF_SYNTAX_EXT = "syntax_ext_dict"
BLOG_TMP_DIR = "blog"
# key to remove from metadata tmp file if they exist
KEY_TO_REMOVE_METADATA = (
"id",
@ -66,24 +66,24 @@ KEY_TO_REMOVE_METADATA = (
URL_REDIRECT_PREFIX = "url_redirect_"
INOTIFY_INSTALL = '"pip install inotify"'
MB_KEYS = (
u"id",
u"url",
u"atom_id",
u"updated",
u"published",
u"language",
u"comments", # this key is used for all comments* keys
u"tags", # this key is used for all tag* keys
u"author",
u"author_jid",
u"author_email",
u"author_jid_verified",
u"content",
u"content_xhtml",
u"title",
u"title_xhtml",
"id",
"url",
"atom_id",
"updated",
"published",
"language",
"comments", # this key is used for all comments* keys
"tags", # this key is used for all tag* keys
"author",
"author_jid",
"author_email",
"author_jid_verified",
"content",
"content_xhtml",
"title",
"title_xhtml",
)
OUTPUT_OPT_NO_HEADER = u"no-header"
OUTPUT_OPT_NO_HEADER = "no-header"
def guessSyntaxFromPath(host, sat_conf, path):
@ -96,7 +96,7 @@ def guessSyntaxFromPath(host, sat_conf, path):
# we first try to guess syntax with extension
ext = os.path.splitext(path)[1][1:] # we get extension without the '.'
if ext:
for k, v in SYNTAX_EXT.iteritems():
for k, v in SYNTAX_EXT.items():
if k and ext == v:
return k
@ -117,32 +117,30 @@ class BlogPublishCommon(object):
def add_parser_options(self):
self.parser.add_argument(
"-T", "--title", type=base.unicode_decoder, help=_(u"title of the item")
"-T", "--title", help=_("title of the item")
)
self.parser.add_argument(
"-t",
"--tag",
type=base.unicode_decoder,
action="append",
help=_(u"tag (category) of your item"),
help=_("tag (category) of your item"),
)
comments_group = self.parser.add_mutually_exclusive_group()
comments_group.add_argument(
"-C", "--comments", action="store_const", const=True, dest="comments",
help=_(u"enable comments (default: comments not enabled except if they "
u"already exist)")
help=_("enable comments (default: comments not enabled except if they "
"already exist)")
)
comments_group.add_argument(
"--no-comments", action="store_const", const=False, dest="comments",
help=_(u"disable comments (will remove comments node if it exist)")
help=_("disable comments (will remove comments node if it exist)")
)
self.parser.add_argument(
"-S",
"--syntax",
type=base.unicode_decoder,
help=_(u"syntax to use (default: get profile's default syntax)"),
help=_("syntax to use (default: get profile's default syntax)"),
)
def setMbDataContent(self, content, mb_data):
@ -164,7 +162,7 @@ class BlogPublishCommon(object):
if self.args.comments is not None:
mb_data["allow_comments"] = self.args.comments
if self.args.tag:
mb_data[u'tags'] = self.args.tag
mb_data['tags'] = self.args.tag
if self.args.title is not None:
mb_data["title"] = self.args.title
@ -177,7 +175,7 @@ class Set(base.CommandBase, BlogPublishCommon):
"set",
use_pubsub=True,
pubsub_flags={C.SINGLE_ITEM},
help=_(u"publish a new blog item or update an existing one"),
help=_("publish a new blog item or update an existing one"),
)
BlogPublishCommon.__init__(self)
self.need_loop = True
@ -186,7 +184,7 @@ class Set(base.CommandBase, BlogPublishCommon):
BlogPublishCommon.add_parser_options(self)
def mbSendCb(self):
self.disp(u"Item published")
self.disp("Item published")
self.host.quit(C.EXIT_OK)
def start(self):
@ -207,14 +205,14 @@ class Set(base.CommandBase, BlogPublishCommon):
callback=self.exitCb,
errback=partial(
self.errback,
msg=_(u"can't send item: {}"),
msg=_("can't send item: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
class Get(base.CommandBase):
TEMPLATE = u"blog/articles.html"
TEMPLATE = "blog/articles.html"
def __init__(self, host):
extra_outputs = {"default": self.default_output, "fancy": self.fancy_output}
@ -227,7 +225,7 @@ class Get(base.CommandBase):
pubsub_flags={C.MULTI_ITEMS},
use_output=C.OUTPUT_COMPLEX,
extra_outputs=extra_outputs,
help=_(u"get blog item(s)"),
help=_("get blog item(s)"),
)
self.need_loop = True
@ -236,34 +234,33 @@ class Get(base.CommandBase):
self.parser.add_argument(
"-k",
"--key",
type=base.unicode_decoder,
action="append",
dest="keys",
help=_(u"microblog data key(s) to display (default: depend of verbosity)"),
help=_("microblog data key(s) to display (default: depend of verbosity)"),
)
# TODO: add MAM filters
def template_data_mapping(self, data):
return {u"items": data_objects.BlogItems(data, deserialise=False)}
return {"items": data_objects.BlogItems(data, deserialise=False)}
def format_comments(self, item, keys):
comments_data = data_format.dict2iterdict(
u"comments", item, (u"node", u"service"), pop=True
"comments", item, ("node", "service"), pop=True
)
lines = []
for data in comments_data:
lines.append(data[u"comments"])
for k in (u"node", u"service"):
lines.append(data["comments"])
for k in ("node", "service"):
if OUTPUT_OPT_NO_HEADER in self.args.output_opts:
header = u""
header = ""
else:
header = C.A_HEADER + k + u": " + A.RESET
header = C.A_HEADER + k + ": " + A.RESET
lines.append(header + data[k])
return u"\n".join(lines)
return "\n".join(lines)
def format_tags(self, item, keys):
tags = item.pop(u'tags', [])
return u", ".join(tags)
tags = item.pop('tags', [])
return ", ".join(tags)
def format_updated(self, item, keys):
return self.format_time(item["updated"])
@ -273,11 +270,11 @@ class Get(base.CommandBase):
def format_url(self, item, keys):
return uri.buildXMPPUri(
u"pubsub",
subtype=u"microblog",
path=self.metadata[u"service"],
node=self.metadata[u"node"],
item=item[u"id"],
"pubsub",
subtype="microblog",
path=self.metadata["service"],
node=self.metadata["node"],
item=item["id"],
)
def get_keys(self):
@ -286,10 +283,10 @@ class Get(base.CommandBase):
if self.args.keys:
if not set(MB_KEYS).issuperset(self.args.keys):
self.disp(
u"following keys are invalid: {invalid}.\n"
u"Valid keys are: {valid}.".format(
invalid=u", ".join(set(self.args.keys).difference(MB_KEYS)),
valid=u", ".join(sorted(MB_KEYS)),
"following keys are invalid: {invalid}.\n"
"Valid keys are: {valid}.".format(
invalid=", ".join(set(self.args.keys).difference(MB_KEYS)),
valid=", ".join(sorted(MB_KEYS)),
),
error=True,
)
@ -297,18 +294,18 @@ class Get(base.CommandBase):
return self.args.keys
else:
if verbosity == 0:
return (u"title", u"content")
return ("title", "content")
elif verbosity == 1:
return (
u"title",
u"tags",
u"author",
u"author_jid",
u"author_email",
u"author_jid_verified",
u"published",
u"updated",
u"content",
"title",
"tags",
"author",
"author_jid",
"author_email",
"author_jid_verified",
"published",
"updated",
"content",
)
else:
return MB_KEYS
@ -334,19 +331,19 @@ class Get(base.CommandBase):
if OUTPUT_OPT_NO_HEADER in self.args.output_opts:
header = ""
else:
header = u"{k_fmt}{key}:{k_fmt_e} {sep}".format(
header = "{k_fmt}{key}:{k_fmt_e} {sep}".format(
k_fmt=C.A_HEADER,
key=k,
k_fmt_e=A.RESET,
sep=u"\n" if "content" in k else u"",
sep="\n" if "content" in k else "",
)
value = k_cb[k](item, keys) if k in k_cb else item[k]
if isinstance(value, bool):
value = unicode(value).lower()
value = str(value).lower()
self.disp(header + value)
# we want a separation line after each item but the last one
if idx < len(items) - 1:
print(u"")
print("")
def format_time(self, timestamp):
"""return formatted date for timestamp
@ -354,7 +351,7 @@ class Get(base.CommandBase):
@param timestamp(str,int,float): unix timestamp
@return (unicode): formatted date
"""
fmt = u"%d/%m/%Y %H:%M:%S"
fmt = "%d/%m/%Y %H:%M:%S"
return time.strftime(fmt, time.localtime(float(timestamp)))
def fancy_output(self, data):
@ -363,46 +360,46 @@ class Get(base.CommandBase):
this output doesn't use keys filter
"""
# thanks to http://stackoverflow.com/a/943921
rows, columns = map(int, os.popen("stty size", "r").read().split())
rows, columns = list(map(int, os.popen("stty size", "r").read().split()))
items, metadata = data
verbosity = self.args.verbose
sep = A.color(A.FG_BLUE, columns * u"▬")
sep = A.color(A.FG_BLUE, columns * "▬")
if items:
print(u"\n" + sep + "\n")
print(("\n" + sep + "\n"))
for idx, item in enumerate(items):
title = item.get(u"title")
title = item.get("title")
if verbosity > 0:
author = item[u"author"]
published, updated = item[u"published"], item.get("updated")
author = item["author"]
published, updated = item["published"], item.get("updated")
else:
author = published = updated = None
if verbosity > 1:
tags = item.pop('tags', [])
else:
tags = None
content = item.get(u"content")
content = item.get("content")
if title:
print(A.color(A.BOLD, A.FG_CYAN, item[u"title"]))
print((A.color(A.BOLD, A.FG_CYAN, item["title"])))
meta = []
if author:
meta.append(A.color(A.FG_YELLOW, author))
if published:
meta.append(A.color(A.FG_YELLOW, u"on ", self.format_time(published)))
meta.append(A.color(A.FG_YELLOW, "on ", self.format_time(published)))
if updated != published:
meta.append(
A.color(A.FG_YELLOW, u"(updated on ", self.format_time(updated), u")")
A.color(A.FG_YELLOW, "(updated on ", self.format_time(updated), ")")
)
print(u" ".join(meta))
print((" ".join(meta)))
if tags:
print(A.color(A.FG_MAGENTA, u", ".join(tags)))
print((A.color(A.FG_MAGENTA, ", ".join(tags))))
if (title or tags) and content:
print("")
if content:
self.disp(content)
print(u"\n" + sep + "\n")
print(("\n" + sep + "\n"))
def mbGetCb(self, mb_result):
items, metadata = mb_result
@ -412,7 +409,7 @@ class Get(base.CommandBase):
self.host.quit(C.EXIT_OK)
def mbGetEb(self, failure_):
self.disp(u"can't get blog items: {reason}".format(reason=failure_), error=True)
self.disp("can't get blog items: {reason}".format(reason=failure_), error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
def start(self):
@ -438,7 +435,7 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
pubsub_flags={C.SINGLE_ITEM},
use_draft=True,
use_verbose=True,
help=_(u"edit an existing or new blog post"),
help=_("edit an existing or new blog post"),
)
BlogPublishCommon.__init__(self)
common.BaseEdit.__init__(self, self.host, BLOG_TMP_DIR, use_metadata=True)
@ -449,7 +446,7 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
"-P",
"--preview",
action="store_true",
help=_(u"launch a blog preview in parallel"),
help=_("launch a blog preview in parallel"),
)
def buildMetadataFile(self, content_file_path, mb_data=None):
@ -465,13 +462,13 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
# or re-use the existing one if it exists
meta_file_path = os.path.splitext(content_file_path)[0] + common.METADATA_SUFF
if os.path.exists(meta_file_path):
self.disp(u"Metadata file already exists, we re-use it")
self.disp("Metadata file already exists, we re-use it")
try:
with open(meta_file_path, "rb") as f:
mb_data = json.load(f)
except (OSError, IOError, ValueError) as e:
self.disp(
u"Can't read existing metadata file at {path}, aborting: {reason}".format(
"Can't read existing metadata file at {path}, aborting: {reason}".format(
path=meta_file_path, reason=e
),
error=True,
@ -513,7 +510,7 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
# do we need a preview ?
if self.args.preview:
self.disp(u"Preview requested, launching it", 1)
self.disp("Preview requested, launching it", 1)
# we redirect outputs to /dev/null to avoid console pollution in editor
# if user wants to see messages, (s)he can call "blog preview" directly
DEVNULL = open(os.devnull, "wb")
@ -552,7 +549,7 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
self.host.bridge.mbSend(
self.pubsub_service, self.pubsub_node, mb_data, self.profile
)
self.disp(u"Blog item published")
self.disp("Blog item published")
def getTmpSuff(self):
# we get current syntax to determine file extension
@ -577,15 +574,15 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
if content and self.current_syntax == SYNTAX_XHTML:
content = content.strip()
if not content.startswith('<div>'):
content = u'<div>' + content + u'</div>'
content = '<div>' + content + '</div>'
try:
from lxml import etree
except ImportError:
self.disp(_(u"You need lxml to edit pretty XHTML"))
self.disp(_("You need lxml to edit pretty XHTML"))
else:
parser = etree.XMLParser(remove_blank_text=True)
root = etree.fromstring(content, parser)
content = etree.tostring(root, encoding=unicode, pretty_print=True)
content = etree.tostring(root, encoding=str, pretty_print=True)
return content, mb_data, mb_data["id"]
@ -599,11 +596,11 @@ class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
self.current_syntax
)
except Exception as e:
if "NotFound" in unicode(
if "NotFound" in str(
e
): #  FIXME: there is not good way to check bridge errors
self.parser.error(
_(u"unknown syntax requested ({syntax})").format(
_("unknown syntax requested ({syntax})").format(
syntax=self.args.syntax
)
)
@ -627,7 +624,7 @@ class Preview(base.CommandBase, common.BaseEdit):
def __init__(self, host):
base.CommandBase.__init__(
self, host, "preview", use_verbose=True, help=_(u"preview a blog content")
self, host, "preview", use_verbose=True, help=_("preview a blog content")
)
common.BaseEdit.__init__(self, self.host, BLOG_TMP_DIR, use_metadata=True)
@ -636,15 +633,14 @@ class Preview(base.CommandBase, common.BaseEdit):
"--inotify",
type=str,
choices=("auto", "true", "false"),
default=u"auto",
help=_(u"use inotify to handle preview"),
default="auto",
help=_("use inotify to handle preview"),
)
self.parser.add_argument(
"file",
type=base.unicode_decoder,
nargs="?",
default=u"current",
help=_(u"path to the content file"),
default="current",
help=_("path to the content file"),
)
def showPreview(self):
@ -660,7 +656,7 @@ class Preview(base.CommandBase, common.BaseEdit):
)
if not args:
self.disp(
u'Couln\'t find command in "{name}", abording'.format(name=opt_name),
'Couln\'t find command in "{name}", abording'.format(name=opt_name),
error=True,
)
self.host.quit(1)
@ -683,11 +679,11 @@ class Preview(base.CommandBase, common.BaseEdit):
)
xhtml = (
u'<html xmlns="http://www.w3.org/1999/xhtml">'
u'<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'
u"</head>"
u"<body>{}</body>"
u"</html>"
'<html xmlns="http://www.w3.org/1999/xhtml">'
'<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'
"</head>"
"<body>{}</body>"
"</html>"
).format(content)
with open(self.preview_file_path, "wb") as f:
@ -695,7 +691,7 @@ class Preview(base.CommandBase, common.BaseEdit):
def start(self):
import webbrowser
import urllib
import urllib.request, urllib.parse, urllib.error
self.webbrowser, self.urllib = webbrowser, urllib
@ -708,13 +704,13 @@ class Preview(base.CommandBase, common.BaseEdit):
if self.args.inotify == "auto":
inotify = None
self.disp(
u"inotify module not found, deactivating feature. You can install"
u" it with {install}".format(install=INOTIFY_INSTALL)
"inotify module not found, deactivating feature. You can install"
" it with {install}".format(install=INOTIFY_INSTALL)
)
else:
self.disp(
u"inotify not found, can't activate the feature! Please install "
u"it with {install}".format(install=INOTIFY_INSTALL),
"inotify not found, can't activate the feature! Please install "
"it with {install}".format(install=INOTIFY_INSTALL),
error=True,
)
self.host.quit(1)
@ -724,7 +720,7 @@ class Preview(base.CommandBase, common.BaseEdit):
inotify.adapters._LOGGER.setLevel(40)
except AttributeError:
self.disp(
u"Logger doesn't exists, inotify may have chanded", error=True
"Logger doesn't exists, inotify may have chanded", error=True
)
else:
inotify = None
@ -768,8 +764,8 @@ class Preview(base.CommandBase, common.BaseEdit):
# XXX: we don't delete file automatically because browser need it
# (and webbrowser.open can return before it is read)
self.disp(
u"temporary file created at {}\nthis file will NOT BE DELETED "
u"AUTOMATICALLY, please delete it yourself when you have finished".format(
"temporary file created at {}\nthis file will NOT BE DELETED "
"AUTOMATICALLY, please delete it yourself when you have finished".format(
self.preview_file_path
)
)
@ -793,10 +789,10 @@ class Preview(base.CommandBase, common.BaseEdit):
try:
for event in i.event_gen():
if event is not None:
self.disp(u"Content updated", 1)
self.disp("Content updated", 1)
if {"IN_DELETE_SELF", "IN_MOVE_SELF"}.intersection(event[1]):
self.disp(
u"{} event catched, changing the watch".format(
"{} event catched, changing the watch".format(
", ".join(event[1])
),
2,
@ -813,7 +809,7 @@ class Preview(base.CommandBase, common.BaseEdit):
update_cb()
except InotifyError:
self.disp(
u"Can't catch inotify events, as the file been deleted?", error=True
"Can't catch inotify events, as the file been deleted?", error=True
)
finally:
os.unlink(self.preview_file_path)
@ -830,28 +826,27 @@ class Import(base.CommandAnswering):
"import",
use_pubsub=True,
use_progress=True,
help=_(u"import an external blog"),
help=_("import an external blog"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"importer",
type=base.unicode_decoder,
nargs="?",
help=_(u"importer name, nothing to display importers list"),
help=_("importer name, nothing to display importers list"),
)
self.parser.add_argument(
"--host", type=base.unicode_decoder, help=_(u"original blog host")
"--host", help=_("original blog host")
)
self.parser.add_argument(
"--no-images-upload",
action="store_true",
help=_(u"do *NOT* upload images (default: do upload images)"),
help=_("do *NOT* upload images (default: do upload images)"),
)
self.parser.add_argument(
"--upload-ignore-host",
help=_(u"do not upload images from this host (default: upload all images)"),
help=_("do not upload images from this host (default: upload all images)"),
)
self.parser.add_argument(
"--ignore-tls-errors",
@ -864,52 +859,51 @@ class Import(base.CommandAnswering):
action="append",
nargs=2,
default=[],
metavar=(u"NAME", u"VALUE"),
help=_(u"importer specific options (see importer description)"),
metavar=("NAME", "VALUE"),
help=_("importer specific options (see importer description)"),
)
self.parser.add_argument(
"location",
type=base.unicode_decoder,
nargs="?",
help=_(
u"importer data location (see importer description), nothing to show "
u"importer description"
"importer data location (see importer description), nothing to show "
"importer description"
),
)
def onProgressStarted(self, metadata):
self.disp(_(u"Blog upload started"), 2)
self.disp(_("Blog upload started"), 2)
def onProgressFinished(self, metadata):
self.disp(_(u"Blog uploaded successfully"), 2)
self.disp(_("Blog uploaded successfully"), 2)
redirections = {
k[len(URL_REDIRECT_PREFIX) :]: v
for k, v in metadata.iteritems()
for k, v in metadata.items()
if k.startswith(URL_REDIRECT_PREFIX)
}
if redirections:
conf = u"\n".join(
conf = "\n".join(
[
u"url_redirections_dict = {}".format(
"url_redirections_dict = {}".format(
# we need to add ' ' before each new line
# and to double each '%' for ConfigParser
u"\n ".join(
"\n ".join(
json.dumps(redirections, indent=1, separators=(",", ": "))
.replace(u"%", u"%%")
.split(u"\n")
.replace("%", "%%")
.split("\n")
)
),
]
)
self.disp(
_(
u"\nTo redirect old URLs to new ones, put the following lines in your"
u" sat.conf file, in [libervia] section:\n\n{conf}".format(conf=conf)
"\nTo redirect old URLs to new ones, put the following lines in your"
" sat.conf file, in [libervia] section:\n\n{conf}".format(conf=conf)
)
)
def onProgressError(self, error_msg):
self.disp(_(u"Error while uploading blog: {}").format(error_msg), error=True)
self.disp(_("Error while uploading blog: {}").format(error_msg), error=True)
def error(self, failure):
self.disp(
@ -924,14 +918,14 @@ class Import(base.CommandAnswering):
if getattr(self.args, name):
self.parser.error(
_(
u"{name} argument can't be used without location argument"
"{name} argument can't be used without location argument"
).format(name=name)
)
if self.args.importer is None:
self.disp(
u"\n".join(
"\n".join(
[
u"{}: {}".format(name, desc)
"{}: {}".format(name, desc)
for name, desc in self.host.bridge.blogImportList()
]
)
@ -942,14 +936,14 @@ class Import(base.CommandAnswering):
self.args.importer
)
except Exception as e:
msg = [l for l in unicode(e).split("\n") if l][
msg = [l for l in str(e).split("\n") if l][
-1
] # we only keep the last line
self.disp(msg)
self.host.quit(1)
else:
self.disp(
u"{name}: {short_desc}\n\n{long_desc}".format(
"{name}: {short_desc}\n\n{long_desc}".format(
name=self.args.importer,
short_desc=short_desc,
long_desc=long_desc,
@ -967,8 +961,8 @@ class Import(base.CommandAnswering):
options["upload_images"] = C.BOOL_FALSE
if self.args.upload_ignore_host:
self.parser.error(
u"upload-ignore-host option can't be used when no-images-upload "
u"is set"
"upload-ignore-host option can't be used when no-images-upload "
"is set"
)
elif self.args.upload_ignore_host:
options["upload_ignore_host"] = self.args.upload_ignore_host

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
__commands__ = ["Bookmarks"]
@ -33,7 +33,7 @@ class BookmarksCommon(base.CommandBase):
self.parser.add_argument('-t', '--type', type=str, choices=TYPES, default=TYPES[0], help=_("bookmarks type (default: %(default)s)"))
def _errback(self, failure):
print (("Something went wrong: [%s]") % failure)
print((("Something went wrong: [%s]") % failure))
self.host.quit(1)
class BookmarksList(BookmarksCommon):
@ -48,20 +48,20 @@ class BookmarksList(BookmarksCommon):
if not data[location]:
continue
loc_mess = []
loc_mess.append(u"%s:" % location)
loc_mess.append("%s:" % location)
book_mess = []
for book_link, book_data in data[location].items():
for book_link, book_data in list(data[location].items()):
name = book_data.get('name')
autojoin = book_data.get('autojoin', 'false') == 'true'
nick = book_data.get('nick')
book_mess.append(u"\t%s[%s%s]%s" % ((name+' ') if name else '',
book_mess.append("\t%s[%s%s]%s" % ((name+' ') if name else '',
book_link,
u' (%s)' % nick if nick else '',
u' (*)' if autojoin else ''))
loc_mess.append(u'\n'.join(book_mess))
mess.append(u'\n'.join(loc_mess))
' (%s)' % nick if nick else '',
' (*)' if autojoin else ''))
loc_mess.append('\n'.join(book_mess))
mess.append('\n'.join(loc_mess))
print u'\n\n'.join(mess)
print('\n\n'.join(mess))
class BookmarksRemove(BookmarksCommon):
@ -72,7 +72,7 @@ class BookmarksRemove(BookmarksCommon):
def add_parser_options(self):
super(BookmarksRemove, self).add_parser_options()
self.parser.add_argument('bookmark', type=base.unicode_decoder, help=_('jid (for muc bookmark) or url of to remove'))
self.parser.add_argument('bookmark', help=_('jid (for muc bookmark) or url of to remove'))
def start(self):
self.host.bridge.bookmarksRemove(self.args.type, self.args.bookmark, self.args.location, self.host.profile, callback = lambda: self.host.quit(), errback=self._errback)
@ -86,16 +86,16 @@ class BookmarksAdd(BookmarksCommon):
def add_parser_options(self):
super(BookmarksAdd, self).add_parser_options(location_default='auto')
self.parser.add_argument('bookmark', type=base.unicode_decoder, help=_('jid (for muc bookmark) or url of to remove'))
self.parser.add_argument('-n', '--name', type=base.unicode_decoder, help=_("bookmark name"))
self.parser.add_argument('bookmark', help=_('jid (for muc bookmark) or url of to remove'))
self.parser.add_argument('-n', '--name', help=_("bookmark name"))
muc_group = self.parser.add_argument_group(_('MUC specific options'))
muc_group.add_argument('-N', '--nick', type=base.unicode_decoder, help=_('nickname'))
muc_group.add_argument('-N', '--nick', help=_('nickname'))
muc_group.add_argument('-a', '--autojoin', action='store_true', help=_('join room on profile connection'))
def start(self):
if self.args.type == 'url' and (self.args.autojoin or self.args.nick is not None):
# XXX: Argparse doesn't seem to manage this case, any better way ?
print _(u"You can't use --autojoin or --nick with --type url")
print(_("You can't use --autojoin or --nick with --type url"))
self.host.quit(1)
data = {}
if self.args.autojoin:

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat.tools.common.ansi import ANSI as A
@ -31,11 +31,11 @@ class BridgeCommon(object):
def evalArgs(self):
if self.args.arg:
try:
return eval(u"[{}]".format(u",".join(self.args.arg)))
return eval("[{}]".format(",".join(self.args.arg)))
except SyntaxError as e:
self.disp(
u"Can't evaluate arguments: {mess}\n{text}\n{offset}^".format(
mess=e, text=e.text.decode("utf-8"), offset=u" " * (e.offset - 1)
"Can't evaluate arguments: {mess}\n{text}\n{offset}^".format(
mess=e, text=e.text, offset=" " * (e.offset - 1)
),
error=True,
)
@ -46,26 +46,26 @@ class BridgeCommon(object):
class Method(base.CommandBase, BridgeCommon):
def __init__(self, host):
base.CommandBase.__init__(self, host, "method", help=_(u"call a bridge method"))
base.CommandBase.__init__(self, host, "method", help=_("call a bridge method"))
BridgeCommon.__init__(self)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"method", type=str, help=_(u"name of the method to execute")
"method", type=str, help=_("name of the method to execute")
)
self.parser.add_argument(
"arg", type=base.unicode_decoder, nargs="*", help=_(u"argument of the method")
"arg", nargs="*", help=_("argument of the method")
)
def method_cb(self, ret=None):
if ret is not None:
self.disp(unicode(ret))
self.disp(str(ret))
self.host.quit()
def method_eb(self, failure):
self.disp(
_(u"Error while executing {}: {}".format(self.args.method, failure)),
_("Error while executing {}: {}".format(self.args.method, failure)),
error=True,
)
self.host.quit(C.EXIT_ERROR)
@ -85,22 +85,22 @@ class Method(base.CommandBase, BridgeCommon):
try:
method(*args, callback=self.method_cb, errback=self.method_eb)
except TypeError:
self.method_eb(_(u"bad arguments"))
self.method_eb(_("bad arguments"))
class Signal(base.CommandBase, BridgeCommon):
def __init__(self, host):
base.CommandBase.__init__(
self, host, "signal", help=_(u"send a fake signal from backend")
self, host, "signal", help=_("send a fake signal from backend")
)
BridgeCommon.__init__(self)
def add_parser_options(self):
self.parser.add_argument(
"signal", type=str, help=_(u"name of the signal to send")
"signal", type=str, help=_("name of the signal to send")
)
self.parser.add_argument(
"arg", type=base.unicode_decoder, nargs="*", help=_(u"argument of the signal")
"arg", nargs="*", help=_("argument of the signal")
)
def start(self):
@ -138,7 +138,7 @@ class Monitor(base.CommandBase):
"--direction",
choices=("in", "out", "both"),
default="both",
help=_(u"stream direction filter"),
help=_("stream direction filter"),
)
def printXML(self, direction, xml_data, profile):
@ -155,7 +155,7 @@ class Monitor(base.CommandBase):
whiteping = False
if verbosity:
profile_disp = u" ({})".format(profile) if verbosity > 1 else u""
profile_disp = " ({})".format(profile) if verbosity > 1 else ""
if direction == "IN":
self.disp(
A.color(
@ -180,7 +180,7 @@ class Monitor(base.CommandBase):
# but importing lxml directly here is not clean
# should be wrapped in a custom Exception
self.disp(xml_data)
self.disp(u"")
self.disp("")
def start(self):
self.host.bridge.register_signal("xmlLog", self.printXML, "plugin")

View file

@ -48,10 +48,10 @@ class EncryptionAlgorithms(base.CommandBase):
def default_output(self, plugins):
if not plugins:
self.disp(_(u"No encryption plugin registered!"))
self.disp(_("No encryption plugin registered!"))
self.host.quit(C.EXIT_NOT_FOUND)
else:
self.disp(_(u"Following encryption algorithms are available: {algos}").format(
self.disp(_("Following encryption algorithms are available: {algos}").format(
algos=', '.join([p['name'] for p in plugins])))
self.host.quit()
@ -60,7 +60,7 @@ class EncryptionAlgorithms(base.CommandBase):
callback=self.encryptionPluginsGetCb,
errback=partial(
self.errback,
msg=_(u"can't retrieve plugins: {}"),
msg=_("can't retrieve plugins: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -72,20 +72,20 @@ class EncryptionGet(base.CommandBase):
super(EncryptionGet, self).__init__(
host, "get",
use_output=C.OUTPUT_DICT,
help=_(u"get encryption session data"))
help=_("get encryption session data"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"jid", type=base.unicode_decoder,
help=_(u"jid of the entity to check")
"jid",
help=_("jid of the entity to check")
)
def messageEncryptionGetCb(self, serialised):
session_data = data_format.deserialise(serialised)
if session_data is None:
self.disp(
u"No encryption session found, the messages are sent in plain text.")
"No encryption session found, the messages are sent in plain text.")
self.host.quit(C.EXIT_NOT_FOUND)
self.output(session_data)
self.host.quit()
@ -98,7 +98,7 @@ class EncryptionGet(base.CommandBase):
callback=self.messageEncryptionGetCb,
errback=partial(
self.errback,
msg=_(u"can't get session: {}"),
msg=_("can't get session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -109,23 +109,23 @@ class EncryptionStart(base.CommandBase):
def __init__(self, host):
super(EncryptionStart, self).__init__(
host, "start",
help=_(u"start encrypted session with an entity"))
help=_("start encrypted session with an entity"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"--encrypt-noreplace",
action="store_true",
help=_(u"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=_(u"algorithm name (DEFAULT: choose automatically)"))
"-n", "--name", help=_("algorithm name (DEFAULT: choose automatically)"))
algorithm.add_argument(
"-N", "--namespace",
help=_(u"algorithm namespace (DEFAULT: choose automatically)"))
help=_("algorithm namespace (DEFAULT: choose automatically)"))
self.parser.add_argument(
"jid", type=base.unicode_decoder,
help=_(u"jid of the entity to stop encrypted session with")
"jid",
help=_("jid of the entity to stop encrypted session with")
)
def encryptionNamespaceGetCb(self, namespace):
@ -136,7 +136,7 @@ class EncryptionStart(base.CommandBase):
self.profile,
callback=self.host.quit,
errback=partial(self.errback,
msg=_(u"Can't start encryption session: {}"),
msg=_("Can't start encryption session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
@ -145,13 +145,13 @@ class EncryptionStart(base.CommandBase):
self.host.bridge.encryptionNamespaceGet(self.args.name,
callback=self.encryptionNamespaceGetCb,
errback=partial(self.errback,
msg=_(u"Can't get encryption namespace: {}"),
msg=_("Can't get encryption namespace: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
elif self.args.namespace is not None:
self.encryptionNamespaceGetCb(self.args.namespace)
else:
self.encryptionNamespaceGetCb(u"")
self.encryptionNamespaceGetCb("")
class EncryptionStop(base.CommandBase):
@ -159,13 +159,13 @@ class EncryptionStop(base.CommandBase):
def __init__(self, host):
super(EncryptionStop, self).__init__(
host, "stop",
help=_(u"stop encrypted session with an entity"))
help=_("stop encrypted session with an entity"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"jid", type=base.unicode_decoder,
help=_(u"jid of the entity to stop encrypted session with")
"jid",
help=_("jid of the entity to stop encrypted session with")
)
def start(self):
@ -176,7 +176,7 @@ class EncryptionStop(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
msg=_(u"can't end encrypted session: {}"),
msg=_("can't end encrypted session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -187,20 +187,20 @@ class TrustUI(base.CommandBase):
def __init__(self, host):
super(TrustUI, self).__init__(
host, "ui",
help=_(u"get UI to manage trust"))
help=_("get UI to manage trust"))
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"jid", type=base.unicode_decoder,
help=_(u"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=_(u"algorithm name (DEFAULT: current algorithm)"))
"-n", "--name", help=_("algorithm name (DEFAULT: current algorithm)"))
algorithm.add_argument(
"-N", "--namespace",
help=_(u"algorithm namespace (DEFAULT: current algorithm)"))
help=_("algorithm namespace (DEFAULT: current algorithm)"))
def encryptionTrustUIGetCb(self, xmlui_raw):
xmlui = xmlui_manager.create(self.host, xmlui_raw)
@ -215,7 +215,7 @@ class TrustUI(base.CommandBase):
callback=self.encryptionTrustUIGetCb,
errback=partial(
self.errback,
msg=_(u"can't end encrypted session: {}"),
msg=_("can't end encrypted session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -225,13 +225,13 @@ class TrustUI(base.CommandBase):
self.host.bridge.encryptionNamespaceGet(self.args.name,
callback=self.encryptionNamespaceGetCb,
errback=partial(self.errback,
msg=_(u"Can't get encryption namespace: {}"),
msg=_("Can't get encryption namespace: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
))
elif self.args.namespace is not None:
self.encryptionNamespaceGetCb(self.args.namespace)
else:
self.encryptionNamespaceGetCb(u"")
self.encryptionNamespaceGetCb("")
class EncryptionTrust(base.CommandBase):
@ -239,7 +239,7 @@ class EncryptionTrust(base.CommandBase):
def __init__(self, host):
super(EncryptionTrust, self).__init__(
host, "trust", use_profile=False, help=_(u"trust manangement")
host, "trust", use_profile=False, help=_("trust manangement")
)
@ -249,5 +249,5 @@ class Encryption(base.CommandBase):
def __init__(self, host):
super(Encryption, self).__init__(
host, "encryption", use_profile=False, help=_(u"encryption sessions handling")
host, "encryption", use_profile=False, help=_("encryption sessions handling")
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat.tools.common.ansi import ANSI as A
from sat_frontends.jp.constants import Const as C
@ -30,7 +30,7 @@ import time
__commands__ = ["Event"]
OUTPUT_OPT_TABLE = u"table"
OUTPUT_OPT_TABLE = "table"
# TODO: move date parsing to base, it may be useful for other commands
@ -45,7 +45,7 @@ class Get(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.SINGLE_ITEM},
use_verbose=True,
help=_(u"get event data"),
help=_("get event data"),
)
self.need_loop = True
@ -67,7 +67,7 @@ class Get(base.CommandBase):
callback=self.eventInviteeGetCb,
errback=partial(
self.errback,
msg=_(u"can't get event data: {}"),
msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -78,22 +78,20 @@ class EventBase(object):
self.parser.add_argument(
"-i",
"--id",
type=base.unicode_decoder,
default=u"",
help=_(u"ID of the PubSub Item"),
default="",
help=_("ID of the PubSub Item"),
)
self.parser.add_argument(
"-d", "--date", type=unicode, help=_(u"date of the event")
"-d", "--date", type=str, help=_("date of the event")
)
self.parser.add_argument(
"-f",
"--field",
type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
metavar=(u"KEY", u"VALUE"),
help=_(u"configuration field to set"),
metavar=("KEY", "VALUE"),
help=_("configuration field to set"),
)
def parseFields(self):
@ -106,10 +104,10 @@ class EventBase(object):
except ValueError:
try:
date_time = du_parser.parse(
self.args.date, dayfirst=not (u"-" in self.args.date)
self.args.date, dayfirst=not ("-" in self.args.date)
)
except ValueError as e:
self.parser.error(_(u"Can't parse date: {msg}").format(msg=e))
self.parser.error(_("Can't parse date: {msg}").format(msg=e))
if date_time.tzinfo is None:
date = calendar.timegm(date_time.timetuple())
else:
@ -131,7 +129,7 @@ class Create(EventBase, base.CommandBase):
self.need_loop = True
def eventCreateCb(self, node):
self.disp(_(u"Event created successfuly on node {node}").format(node=node))
self.disp(_("Event created successfuly on node {node}").format(node=node))
self.host.quit()
def start(self):
@ -147,7 +145,7 @@ class Create(EventBase, base.CommandBase):
callback=self.eventCreateCb,
errback=partial(
self.errback,
msg=_(u"can't create event: {}"),
msg=_("can't create event: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -178,7 +176,7 @@ class Modify(EventBase, base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
msg=_(u"can't update event data: {}"),
msg=_("can't update event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -194,7 +192,7 @@ class InviteeGet(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE, C.ITEM, C.SINGLE_ITEM},
use_verbose=True,
help=_(u"get event attendance"),
help=_("get event attendance"),
)
self.need_loop = True
@ -213,7 +211,7 @@ class InviteeGet(base.CommandBase):
callback=self.eventInviteeGetCb,
errback=partial(
self.errback,
msg=_(u"can't get event data: {}"),
msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -235,12 +233,11 @@ class InviteeSet(base.CommandBase):
self.parser.add_argument(
"-f",
"--field",
type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
metavar=(u"KEY", u"VALUE"),
help=_(u"configuration field to set"),
metavar=("KEY", "VALUE"),
help=_("configuration field to set"),
)
def start(self):
@ -253,7 +250,7 @@ class InviteeSet(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
msg=_(u"can't set event data: {}"),
msg=_("can't set event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -271,7 +268,7 @@ class InviteesList(base.CommandBase):
use_pubsub=True,
pubsub_flags={C.NODE},
use_verbose=True,
help=_(u"get event attendance"),
help=_("get event attendance"),
)
self.need_loop = True
@ -280,26 +277,26 @@ class InviteesList(base.CommandBase):
"-m",
"--missing",
action="store_true",
help=_(u"show missing people (invited but no R.S.V.P. so far)"),
help=_("show missing people (invited but no R.S.V.P. so far)"),
)
self.parser.add_argument(
"-R",
"--no-rsvp",
action="store_true",
help=_(u"don't show people which gave R.S.V.P."),
help=_("don't show people which gave R.S.V.P."),
)
def _attend_filter(self, attend, row):
if attend == u"yes":
if attend == "yes":
attend_color = C.A_SUCCESS
elif attend == u"no":
elif attend == "no":
attend_color = C.A_FAILURE
else:
attend_color = A.FG_WHITE
return A.color(attend_color, attend)
def _guests_filter(self, guests):
return u"(" + unicode(guests) + ")" if guests else u""
return "(" + str(guests) + ")" if guests else ""
def default_output(self, event_data):
data = []
@ -309,13 +306,13 @@ class InviteesList(base.CommandBase):
attendees_missing = 0
guests = 0
guests_maybe = 0
for jid_, jid_data in event_data.iteritems():
jid_data[u"jid"] = jid_
for jid_, jid_data in event_data.items():
jid_data["jid"] = jid_
try:
guests_int = int(jid_data["guests"])
except (ValueError, KeyError):
pass
attend = jid_data.get(u"attend", u"")
attend = jid_data.get("attend", "")
if attend == "yes":
attendees_yes += 1
guests += guests_int
@ -324,10 +321,10 @@ class InviteesList(base.CommandBase):
guests_maybe += guests_int
elif attend == "no":
attendees_no += 1
jid_data[u"guests"] = ""
jid_data["guests"] = ""
else:
attendees_missing += 1
jid_data[u"guests"] = ""
jid_data["guests"] = ""
data.append(jid_data)
show_table = OUTPUT_OPT_TABLE in self.args.output_opts
@ -335,60 +332,60 @@ class InviteesList(base.CommandBase):
table = common.Table.fromDict(
self.host,
data,
(u"nick",)
+ ((u"jid",) if self.host.verbosity else ())
+ (u"attend", "guests"),
("nick",)
+ (("jid",) if self.host.verbosity else ())
+ ("attend", "guests"),
headers=None,
filters={
u"nick": A.color(C.A_HEADER, u"{}" if show_table else u"{} "),
u"jid": u"{}" if show_table else u"{} ",
u"attend": self._attend_filter,
u"guests": u"{}" if show_table else self._guests_filter,
"nick": A.color(C.A_HEADER, "{}" if show_table else "{} "),
"jid": "{}" if show_table else "{} ",
"attend": self._attend_filter,
"guests": "{}" if show_table else self._guests_filter,
},
defaults={u"nick": u"", u"attend": u"", u"guests": 1},
defaults={"nick": "", "attend": "", "guests": 1},
)
if show_table:
table.display()
else:
table.display_blank(show_header=False, col_sep=u"")
table.display_blank(show_header=False, col_sep="")
if not self.args.no_rsvp:
self.disp(u"")
self.disp("")
self.disp(
A.color(
C.A_SUBHEADER,
_(u"Attendees: "),
_("Attendees: "),
A.RESET,
unicode(len(data)),
_(u" ("),
str(len(data)),
_(" ("),
C.A_SUCCESS,
_(u"yes: "),
unicode(attendees_yes),
_("yes: "),
str(attendees_yes),
A.FG_WHITE,
_(u", maybe: "),
unicode(attendees_maybe),
u", ",
_(", maybe: "),
str(attendees_maybe),
", ",
C.A_FAILURE,
_(u"no: "),
unicode(attendees_no),
_("no: "),
str(attendees_no),
A.RESET,
u")",
")",
)
)
self.disp(
A.color(C.A_SUBHEADER, _(u"confirmed guests: "), A.RESET, unicode(guests))
A.color(C.A_SUBHEADER, _("confirmed guests: "), A.RESET, str(guests))
)
self.disp(
A.color(
C.A_SUBHEADER,
_(u"unconfirmed guests: "),
_("unconfirmed guests: "),
A.RESET,
unicode(guests_maybe),
str(guests_maybe),
)
)
self.disp(
A.color(
C.A_SUBHEADER, _(u"total: "), A.RESET, unicode(guests + guests_maybe)
C.A_SUBHEADER, _("total: "), A.RESET, str(guests + guests_maybe)
)
)
if attendees_missing:
@ -396,9 +393,9 @@ class InviteesList(base.CommandBase):
self.disp(
A.color(
C.A_SUBHEADER,
_(u"missing people (no reply): "),
_("missing people (no reply): "),
A.RESET,
unicode(attendees_missing),
str(attendees_missing),
)
)
@ -420,9 +417,9 @@ class InviteesList(base.CommandBase):
prefilled_data.update(event_data)
# we get nicknames for everybody, make it easier for organisers
for jid_, data in prefilled_data.iteritems():
for jid_, data in prefilled_data.items():
id_data = self.host.bridge.identityGet(jid_, self.profile)
data[u"nick"] = id_data.get(u"nick", u"")
data["nick"] = id_data.get("nick", "")
self.output(prefilled_data)
self.host.quit()
@ -435,7 +432,7 @@ class InviteesList(base.CommandBase):
callback=partial(self.eventInviteesListCb, prefilled_data=prefilled_data),
errback=partial(
self.errback,
msg=_(u"can't get event data: {}"),
msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -446,14 +443,14 @@ class InviteesList(base.CommandBase):
# we only consider people with "publisher" affiliation as invited, creators are not, and members can just observe
prefilled = {
jid_: {}
for jid_, affiliation in affiliations.iteritems()
if affiliation in (u"publisher",)
for jid_, affiliation in affiliations.items()
if affiliation in ("publisher",)
}
self.getList(prefilled)
def start(self):
if self.args.no_rsvp and not self.args.missing:
self.parser.error(_(u"you need to use --missing if you use --no-rsvp"))
self.parser.error(_("you need to use --missing if you use --no-rsvp"))
if self.args.missing:
self.host.bridge.psNodeAffiliationsGet(
self.args.service,
@ -462,7 +459,7 @@ class InviteesList(base.CommandBase):
callback=self.psNodeAffiliationsGetCb,
errback=partial(
self.errback,
msg=_(u"can't get event data: {}"),
msg=_("can't get event data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -478,7 +475,7 @@ class InviteeInvite(base.CommandBase):
"invite",
use_pubsub=True,
pubsub_flags={C.NODE, C.SINGLE_ITEM},
help=_(u"invite someone to the event through email"),
help=_("invite someone to the event through email"),
)
self.need_loop = True
@ -487,49 +484,42 @@ class InviteeInvite(base.CommandBase):
"-e",
"--email",
action="append",
type=base.unicode_decoder,
default=[],
help="email(s) to send the invitation to",
)
self.parser.add_argument(
"-N",
"--name",
type=base.unicode_decoder,
default="",
help="name of the invitee",
)
self.parser.add_argument(
"-H",
"--host-name",
type=base.unicode_decoder,
default="",
help="name of the host",
)
self.parser.add_argument(
"-l",
"--lang",
type=base.unicode_decoder,
default="",
help="main language spoken by the invitee",
)
self.parser.add_argument(
"-U",
"--url-template",
type=base.unicode_decoder,
default="",
help="template to construct the URL",
)
self.parser.add_argument(
"-S",
"--subject",
type=base.unicode_decoder,
default="",
help="subject of the invitation email (default: generic subject)",
)
self.parser.add_argument(
"-b",
"--body",
type=base.unicode_decoder,
default="",
help="body of the invitation email (default: generic body)",
)
@ -554,7 +544,7 @@ class InviteeInvite(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
msg=_(u"can't create invitation: {}"),
msg=_("can't create invitation: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -565,7 +555,7 @@ class Invitee(base.CommandBase):
def __init__(self, host):
super(Invitee, self).__init__(
host, "invitee", use_profile=False, help=_(u"manage invities")
host, "invitee", use_profile=False, help=_("manage invities")
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
import sys
import os
import os.path
@ -50,32 +50,29 @@ class Send(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
"files", type=str, nargs="+", metavar="file", help=_(u"a list of file")
"files", type=str, nargs="+", metavar="file", help=_("a list of file")
)
self.parser.add_argument(
"jid", type=base.unicode_decoder, help=_(u"the destination jid")
"jid", help=_("the destination jid")
)
self.parser.add_argument(
"-b", "--bz2", action="store_true", help=_(u"make a bzip2 tarball")
"-b", "--bz2", action="store_true", help=_("make a bzip2 tarball")
)
self.parser.add_argument(
"-d",
"--path",
type=base.unicode_decoder,
help=(u"path to the directory where the file must be stored"),
help=("path to the directory where the file must be stored"),
)
self.parser.add_argument(
"-N",
"--namespace",
type=base.unicode_decoder,
help=(u"namespace of the file"),
help=("namespace of the file"),
)
self.parser.add_argument(
"-n",
"--name",
type=base.unicode_decoder,
default=u"",
help=(u"name to use (DEFAULT: use source file name)"),
default="",
help=("name to use (DEFAULT: use source file name)"),
)
def start(self):
@ -83,16 +80,16 @@ class Send(base.CommandBase):
self.send_files()
def onProgressStarted(self, metadata):
self.disp(_(u"File copy started"), 2)
self.disp(_("File copy started"), 2)
def onProgressFinished(self, metadata):
self.disp(_(u"File sent successfully"), 2)
self.disp(_("File sent successfully"), 2)
def onProgressError(self, error_msg):
if error_msg == C.PROGRESS_ERROR_DECLINED:
self.disp(_(u"The file has been refused by your contact"))
self.disp(_("The file has been refused by your contact"))
else:
self.disp(_(u"Error while sending file: {}").format(error_msg), error=True)
self.disp(_("Error while sending file: {}").format(error_msg), error=True)
def gotId(self, data, file_):
"""Called when a progress id has been received
@ -101,13 +98,13 @@ class Send(base.CommandBase):
@param file_(str): file path
"""
# FIXME: this show progress only for last progress_id
self.disp(_(u"File request sent to {jid}".format(jid=self.full_dest_jid)), 1)
self.disp(_("File request sent to {jid}".format(jid=self.full_dest_jid)), 1)
try:
self.progress_id = data["progress"]
except KeyError:
# TODO: if 'xmlui' key is present, manage xmlui message display
self.disp(
_(u"Can't send file to {jid}".format(jid=self.full_dest_jid)), error=True
_("Can't send file to {jid}".format(jid=self.full_dest_jid)), error=True
)
self.host.quit(2)
@ -121,12 +118,12 @@ class Send(base.CommandBase):
def send_files(self):
for file_ in self.args.files:
if not os.path.exists(file_):
self.disp(_(u"file [{}] doesn't exist !").format(file_), error=True)
self.disp(_("file [{}] doesn't exist !").format(file_), error=True)
self.host.quit(1)
if not self.args.bz2 and os.path.isdir(file_):
self.disp(
_(
u"[{}] is a dir ! Please send files inside or use compression"
"[{}] is a dir ! Please send files inside or use compression"
).format(file_)
)
self.host.quit(1)
@ -134,26 +131,26 @@ class Send(base.CommandBase):
self.full_dest_jid = self.host.get_full_jid(self.args.jid)
extra = {}
if self.args.path:
extra[u"path"] = self.args.path
extra["path"] = self.args.path
if self.args.namespace:
extra[u"namespace"] = self.args.namespace
extra["namespace"] = self.args.namespace
if self.args.bz2:
with tempfile.NamedTemporaryFile("wb", delete=False) as buf:
self.host.addOnQuitCallback(os.unlink, buf.name)
self.disp(_(u"bz2 is an experimental option, use with caution"))
self.disp(_("bz2 is an experimental option, use with caution"))
# FIXME: check free space
self.disp(_(u"Starting compression, please wait..."))
self.disp(_("Starting compression, please wait..."))
sys.stdout.flush()
bz2 = tarfile.open(mode="w:bz2", fileobj=buf)
archive_name = u"{}.tar.bz2".format(
os.path.basename(self.args.files[0]) or u"compressed_files"
archive_name = "{}.tar.bz2".format(
os.path.basename(self.args.files[0]) or "compressed_files"
)
for file_ in self.args.files:
self.disp(_(u"Adding {}").format(file_), 1)
self.disp(_("Adding {}").format(file_), 1)
bz2.add(file_)
bz2.close()
self.disp(_(u"Done !"), 1)
self.disp(_("Done !"), 1)
self.host.bridge.fileSend(
self.full_dest_jid,
@ -193,71 +190,65 @@ class Request(base.CommandBase):
@property
def filename(self):
return self.args.name or self.args.hash or u"output"
return self.args.name or self.args.hash or "output"
def add_parser_options(self):
self.parser.add_argument(
"jid", type=base.unicode_decoder, help=_(u"the destination jid")
"jid", help=_("the destination jid")
)
self.parser.add_argument(
"-D",
"--dest",
type=base.unicode_decoder,
help=_(
u"destination path where the file will be saved (default: [current_dir]/[name|hash])"
"destination path where the file will be saved (default: [current_dir]/[name|hash])"
),
)
self.parser.add_argument(
"-n",
"--name",
type=base.unicode_decoder,
default=u"",
help=_(u"name of the file"),
default="",
help=_("name of the file"),
)
self.parser.add_argument(
"-H",
"--hash",
type=base.unicode_decoder,
default=u"",
help=_(u"hash of the file"),
default="",
help=_("hash of the file"),
)
self.parser.add_argument(
"-a",
"--hash-algo",
type=base.unicode_decoder,
default=u"sha-256",
help=_(u"hash algorithm use for --hash (default: sha-256)"),
default="sha-256",
help=_("hash algorithm use for --hash (default: sha-256)"),
)
self.parser.add_argument(
"-d",
"--path",
type=base.unicode_decoder,
help=(u"path to the directory containing the file"),
help=("path to the directory containing the file"),
)
self.parser.add_argument(
"-N",
"--namespace",
type=base.unicode_decoder,
help=(u"namespace of the file"),
help=("namespace of the file"),
)
self.parser.add_argument(
"-f",
"--force",
action="store_true",
help=_(u"overwrite existing file without confirmation"),
help=_("overwrite existing file without confirmation"),
)
def onProgressStarted(self, metadata):
self.disp(_(u"File copy started"), 2)
self.disp(_("File copy started"), 2)
def onProgressFinished(self, metadata):
self.disp(_(u"File received successfully"), 2)
self.disp(_("File received successfully"), 2)
def onProgressError(self, error_msg):
if error_msg == C.PROGRESS_ERROR_DECLINED:
self.disp(_(u"The file request has been refused"))
self.disp(_("The file request has been refused"))
else:
self.disp(_(u"Error while requesting file: {}").format(error_msg), error=True)
self.disp(_("Error while requesting file: {}").format(error_msg), error=True)
def gotId(self, progress_id):
"""Called when a progress id has been received
@ -275,7 +266,7 @@ class Request(base.CommandBase):
def start(self):
if not self.args.name and not self.args.hash:
self.parser.error(_(u"at least one of --name or --hash must be provided"))
self.parser.error(_("at least one of --name or --hash must be provided"))
#  extra = dict(self.args.extra)
if self.args.dest:
path = os.path.abspath(os.path.expanduser(self.args.dest))
@ -285,32 +276,32 @@ class Request(base.CommandBase):
path = os.path.abspath(self.filename)
if os.path.exists(path) and not self.args.force:
message = _(u"File {path} already exists! Do you want to overwrite?").format(
message = _("File {path} already exists! Do you want to overwrite?").format(
path=path
)
confirm = raw_input(u"{} (y/N) ".format(message).encode("utf-8"))
if confirm not in (u"y", u"Y"):
self.disp(_(u"file request cancelled"))
confirm = input("{} (y/N) ".format(message).encode("utf-8"))
if confirm not in ("y", "Y"):
self.disp(_("file request cancelled"))
self.host.quit(2)
self.full_dest_jid = self.host.get_full_jid(self.args.jid)
extra = {}
if self.args.path:
extra[u"path"] = self.args.path
extra["path"] = self.args.path
if self.args.namespace:
extra[u"namespace"] = self.args.namespace
extra["namespace"] = self.args.namespace
self.host.bridge.fileJingleRequest(
self.full_dest_jid,
path,
self.args.name,
self.args.hash,
self.args.hash_algo if self.args.hash else u"",
self.args.hash_algo if self.args.hash else "",
extra,
self.profile,
callback=self.gotId,
errback=partial(
self.errback,
msg=_(u"can't request file: {}"),
msg=_("can't request file: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -332,25 +323,25 @@ class Receive(base.CommandAnswering):
}
def onProgressStarted(self, metadata):
self.disp(_(u"File copy started"), 2)
self.disp(_("File copy started"), 2)
def onProgressFinished(self, metadata):
self.disp(_(u"File received successfully"), 2)
self.disp(_("File received successfully"), 2)
if metadata.get("hash_verified", False):
try:
self.disp(
_(u"hash checked: {algo}:{checksum}").format(
_("hash checked: {algo}:{checksum}").format(
algo=metadata["hash_algo"], checksum=metadata["hash"]
),
1,
)
except KeyError:
self.disp(_(u"hash is checked but hash value is missing", 1), error=True)
self.disp(_("hash is checked but hash value is missing", 1), error=True)
else:
self.disp(_(u"hash can't be verified"), 1)
self.disp(_("hash can't be verified"), 1)
def onProgressError(self, error_msg):
self.disp(_(u"Error while receiving file: {}").format(error_msg), error=True)
self.disp(_("Error while receiving file: {}").format(error_msg), error=True)
def getXmluiId(self, action_data):
# FIXME: we temporarily use ElementTree, but a real XMLUI managing module
@ -359,12 +350,12 @@ class Receive(base.CommandAnswering):
try:
xml_ui = action_data["xmlui"]
except KeyError:
self.disp(_(u"Action has no XMLUI"), 1)
self.disp(_("Action has no XMLUI"), 1)
else:
ui = ET.fromstring(xml_ui.encode("utf-8"))
xmlui_id = ui.get("submit")
if not xmlui_id:
self.disp(_(u"Invalid XMLUI received"), error=True)
self.disp(_("Invalid XMLUI received"), error=True)
return xmlui_id
def onFileAction(self, action_data, action_id, security_limit, profile):
@ -374,17 +365,17 @@ class Receive(base.CommandAnswering):
try:
from_jid = jid.JID(action_data["meta_from_jid"])
except KeyError:
self.disp(_(u"Ignoring action without from_jid data"), 1)
self.disp(_("Ignoring action without from_jid data"), 1)
return
try:
progress_id = action_data["meta_progress_id"]
except KeyError:
self.disp(_(u"ignoring action without progress id"), 1)
self.disp(_("ignoring action without progress id"), 1)
return
if not self.bare_jids or from_jid.bare in self.bare_jids:
if self._overwrite_refused:
self.disp(_(u"File refused because overwrite is needed"), error=True)
self.disp(_("File refused because overwrite is needed"), error=True)
self.host.bridge.launchAction(
xmlui_id, {"cancelled": C.BOOL_TRUE}, profile_key=profile
)
@ -400,15 +391,15 @@ class Receive(base.CommandAnswering):
try:
progress_id = action_data["meta_progress_id"]
except KeyError:
self.disp(_(u"ignoring action without progress id"), 1)
self.disp(_("ignoring action without progress id"), 1)
return
self.disp(_(u"Overwriting needed"), 1)
self.disp(_("Overwriting needed"), 1)
if progress_id == self.progress_id:
if self.args.force:
self.disp(_(u"Overwrite accepted"), 2)
self.disp(_("Overwrite accepted"), 2)
else:
self.disp(_(u"Refused to overwrite"), 2)
self.disp(_("Refused to overwrite"), 2)
self._overwrite_refused = True
xmlui_data = {"answer": C.boolConst(self.args.force)}
@ -417,40 +408,39 @@ class Receive(base.CommandAnswering):
def add_parser_options(self):
self.parser.add_argument(
"jids",
type=base.unicode_decoder,
nargs="*",
help=_(u"jids accepted (accept everything if none is specified)"),
help=_("jids accepted (accept everything if none is specified)"),
)
self.parser.add_argument(
"-m",
"--multiple",
action="store_true",
help=_(u"accept multiple files (you'll have to stop manually)"),
help=_("accept multiple files (you'll have to stop manually)"),
)
self.parser.add_argument(
"-f",
"--force",
action="store_true",
help=_(
u"force overwritting of existing files (/!\\ name is choosed by sender)"
"force overwritting of existing files (/!\\ name is choosed by sender)"
),
)
self.parser.add_argument(
"--path",
default=".",
metavar="DIR",
help=_(u"destination path (default: working directory)"),
help=_("destination path (default: working directory)"),
)
def start(self):
self.bare_jids = [jid.JID(jid_).bare for jid_ in self.args.jids]
self.path = os.path.abspath(self.args.path)
if not os.path.isdir(self.path):
self.disp(_(u"Given path is not a directory !", error=True))
self.disp(_("Given path is not a directory !", error=True))
self.host.quit(2)
if self.args.multiple:
self.host.quit_on_progress_end = False
self.disp(_(u"waiting for incoming file request"), 2)
self.disp(_("waiting for incoming file request"), 2)
class Upload(base.CommandBase):
@ -464,7 +454,6 @@ class Upload(base.CommandBase):
self.parser.add_argument("file", type=str, help=_("file to upload"))
self.parser.add_argument(
"jid",
type=base.unicode_decoder,
nargs="?",
help=_("jid of upload component (nothing to autodetect)"),
)
@ -475,21 +464,21 @@ class Upload(base.CommandBase):
)
def onProgressStarted(self, metadata):
self.disp(_(u"File upload started"), 2)
self.disp(_("File upload started"), 2)
def onProgressFinished(self, metadata):
self.disp(_(u"File uploaded successfully"), 2)
self.disp(_("File uploaded successfully"), 2)
try:
url = metadata["url"]
except KeyError:
self.disp(u"download URL not found in metadata")
self.disp("download URL not found in metadata")
else:
self.disp(_(u"URL to retrieve the file:"), 1)
self.disp(_("URL to retrieve the file:"), 1)
# XXX: url is display alone on a line to make parsing easier
self.disp(url)
def onProgressError(self, error_msg):
self.disp(_(u"Error while uploading file: {}").format(error_msg), error=True)
self.disp(_("Error while uploading file: {}").format(error_msg), error=True)
def gotId(self, data, file_):
"""Called when a progress id has been received
@ -501,7 +490,7 @@ class Upload(base.CommandBase):
self.progress_id = data["progress"]
except KeyError:
# TODO: if 'xmlui' key is present, manage xmlui message display
self.disp(_(u"Can't upload file"), error=True)
self.disp(_("Can't upload file"), error=True)
self.host.quit(2)
def error(self, failure):
@ -514,10 +503,10 @@ class Upload(base.CommandBase):
def start(self):
file_ = self.args.file
if not os.path.exists(file_):
self.disp(_(u"file [{}] doesn't exist !").format(file_), error=True)
self.disp(_("file [{}] doesn't exist !").format(file_), error=True)
self.host.quit(1)
if os.path.isdir(file_):
self.disp(_(u"[{}] is a dir! Can't upload a dir").format(file_))
self.disp(_("[{}] is a dir! Can't upload a dir").format(file_))
self.host.quit(1)
self.full_dest_jid = (
@ -547,7 +536,7 @@ class ShareList(base.CommandBase):
"list",
use_output=C.OUTPUT_LIST_DICT,
extra_outputs=extra_outputs,
help=_(u"retrieve files shared by an entity"),
help=_("retrieve files shared by an entity"),
use_verbose=True,
)
self.need_loop = True
@ -556,12 +545,11 @@ class ShareList(base.CommandBase):
self.parser.add_argument(
"-d",
"--path",
default=u"",
help=_(u"path to the directory containing the files"),
default="",
help=_("path to the directory containing the files"),
)
self.parser.add_argument(
"jid",
type=base.unicode_decoder,
nargs="?",
default="",
help=_("jid of sharing entity (nothing to check our own jid)"),
@ -569,9 +557,9 @@ class ShareList(base.CommandBase):
def file_gen(self, files_data):
for file_data in files_data:
yield file_data[u"name"]
yield file_data.get(u"size", "")
yield file_data.get(u"hash", "")
yield file_data["name"]
yield file_data.get("size", "")
yield file_data.get("hash", "")
def _name_filter(self, name, row):
if row.type == C.FILE_TYPE_DIRECTORY:
@ -579,39 +567,39 @@ class ShareList(base.CommandBase):
elif row.type == C.FILE_TYPE_FILE:
return A.color(C.A_FILE, name)
else:
self.disp(_(u"unknown file type: {type}").format(type=row.type), error=True)
self.disp(_("unknown file type: {type}").format(type=row.type), error=True)
return name
def _size_filter(self, size, row):
if not size:
return u""
return ""
size = int(size)
#  cf. https://stackoverflow.com/a/1094933 (thanks)
suffix = u"o"
for unit in [u"", u"Ki", u"Mi", u"Gi", u"Ti", u"Pi", u"Ei", u"Zi"]:
suffix = "o"
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(size) < 1024.0:
return A.color(A.BOLD, u"{:.2f}".format(size), unit, suffix)
return A.color(A.BOLD, "{:.2f}".format(size), unit, suffix)
size /= 1024.0
return A.color(A.BOLD, u"{:.2f}".format(size), u"Yi", suffix)
return A.color(A.BOLD, "{:.2f}".format(size), "Yi", suffix)
def default_output(self, files_data):
"""display files a way similar to ls"""
files_data.sort(key=lambda d: d["name"].lower())
show_header = False
if self.verbosity == 0:
headers = (u"name", u"type")
headers = ("name", "type")
elif self.verbosity == 1:
headers = (u"name", u"type", u"size")
headers = ("name", "type", "size")
elif self.verbosity > 1:
show_header = True
headers = (u"name", u"type", u"size", u"hash")
headers = ("name", "type", "size", "hash")
table = common.Table.fromDict(
self.host,
files_data,
headers,
filters={u"name": self._name_filter, u"size": self._size_filter},
defaults={u"size": u"", u"hash": u""},
filters={"name": self._name_filter, "size": self._size_filter},
defaults={"size": "", "hash": ""},
)
table.display_blank(show_header=show_header, hide_cols=["type"])
@ -628,7 +616,7 @@ class ShareList(base.CommandBase):
callback=self._FISListCb,
errback=partial(
self.errback,
msg=_(u"can't retrieve shared files: {}"),
msg=_("can't retrieve shared files: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -637,7 +625,7 @@ class ShareList(base.CommandBase):
class SharePath(base.CommandBase):
def __init__(self, host):
super(SharePath, self).__init__(
host, "path", help=_(u"share a file or directory"), use_verbose=True
host, "path", help=_("share a file or directory"), use_verbose=True
)
self.need_loop = True
@ -645,47 +633,44 @@ class SharePath(base.CommandBase):
self.parser.add_argument(
"-n",
"--name",
type=base.unicode_decoder,
default=u"",
help=_(u"virtual name to use (default: use directory/file name)"),
default="",
help=_("virtual name to use (default: use directory/file name)"),
)
perm_group = self.parser.add_mutually_exclusive_group()
perm_group.add_argument(
"-j",
"--jid",
type=base.unicode_decoder,
action="append",
dest="jids",
default=[],
help=_(u"jid of contacts allowed to retrieve the files"),
help=_("jid of contacts allowed to retrieve the files"),
)
perm_group.add_argument(
"--public",
action="store_true",
help=_(
u"share publicly the file(s) (/!\\ *everybody* will be able to access them)"
"share publicly the file(s) (/!\\ *everybody* will be able to access them)"
),
)
self.parser.add_argument(
"path",
type=base.unicode_decoder,
help=_(u"path to a file or directory to share"),
help=_("path to a file or directory to share"),
)
def _FISSharePathCb(self, name):
self.disp(
_(u'{path} shared under the name "{name}"').format(path=self.path, name=name)
_('{path} shared under the name "{name}"').format(path=self.path, name=name)
)
self.host.quit()
def start(self):
self.path = os.path.abspath(self.args.path)
if self.args.public:
access = {u"read": {u"type": u"public"}}
access = {"read": {"type": "public"}}
else:
jids = self.args.jids
if jids:
access = {u"read": {u"type": "whitelist", u"jids": jids}}
access = {"read": {"type": "whitelist", "jids": jids}}
else:
access = {}
self.host.bridge.FISSharePath(
@ -696,7 +681,7 @@ class SharePath(base.CommandBase):
callback=self._FISSharePathCb,
errback=partial(
self.errback,
msg=_(u"can't share path: {}"),
msg=_("can't share path: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -705,7 +690,7 @@ class SharePath(base.CommandBase):
class ShareInvite(base.CommandBase):
def __init__(self, host):
super(ShareInvite, self).__init__(
host, "invite", help=_(u"send invitation for a shared repository")
host, "invite", help=_("send invitation for a shared repository")
)
self.need_loop = True
@ -713,61 +698,55 @@ class ShareInvite(base.CommandBase):
self.parser.add_argument(
"-n",
"--name",
type=base.unicode_decoder,
default=u"",
help=_(u"name of the repository"),
default="",
help=_("name of the repository"),
)
self.parser.add_argument(
"-N",
"--namespace",
type=base.unicode_decoder,
default=u"",
help=_(u"namespace of the repository"),
default="",
help=_("namespace of the repository"),
)
self.parser.add_argument(
"-P",
"--path",
type=base.unicode_decoder,
help=_(u"path to the repository"),
help=_("path to the repository"),
)
self.parser.add_argument(
"-t",
"--type",
choices=[u"files", u"photos"],
default=u"files",
help=_(u"type of the repository"),
choices=["files", "photos"],
default="files",
help=_("type of the repository"),
)
self.parser.add_argument(
"-T",
"--thumbnail",
type=base.unicode_decoder,
help=_(u"https URL of a image to use as thumbnail"),
help=_("https URL of a image to use as thumbnail"),
)
self.parser.add_argument(
"service",
type=base.unicode_decoder,
help=_(u"jid of the file sharing service hosting the repository"),
help=_("jid of the file sharing service hosting the repository"),
)
self.parser.add_argument(
"jid",
type=base.unicode_decoder,
help=_(u"jid of the person to invite"),
help=_("jid of the person to invite"),
)
def _FISInviteCb(self):
self.disp(
_(u'invitation sent to {entity}').format(entity=self.args.jid)
_('invitation sent to {entity}').format(entity=self.args.jid)
)
self.host.quit()
def start(self):
self.path = os.path.normpath(self.args.path) if self.args.path else u""
self.path = os.path.normpath(self.args.path) if self.args.path else ""
extra = {}
if self.args.thumbnail is not None:
if not self.args.thumbnail.startswith(u'http'):
self.parser.error(_(u"only http(s) links are allowed with --thumbnail"))
if not self.args.thumbnail.startswith('http'):
self.parser.error(_("only http(s) links are allowed with --thumbnail"))
else:
extra[u'thumb_url'] = self.args.thumbnail
extra['thumb_url'] = self.args.thumbnail
self.host.bridge.FISInvite(
self.args.jid,
self.args.service,
@ -780,7 +759,7 @@ class ShareInvite(base.CommandBase):
callback=self._FISInviteCb,
errback=partial(
self.errback,
msg=_(u"can't send invitation: {}"),
msg=_("can't send invitation: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -791,7 +770,7 @@ class Share(base.CommandBase):
def __init__(self, host):
super(Share, self).__init__(
host, "share", use_profile=False, help=_(u"files sharing management")
host, "share", use_profile=False, help=_("files sharing management")
)
@ -800,5 +779,5 @@ class File(base.CommandBase):
def __init__(self, host):
super(File, self).__init__(
host, "file", use_profile=False, help=_(u"files sending/receiving/management")
host, "file", use_profile=False, help=_("files sending/receiving/management")
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat_frontends.jp import common
@ -29,7 +29,7 @@ import json
__commands__ = ["Forums"]
FORUMS_TMP_DIR = u"forums"
FORUMS_TMP_DIR = "forums"
class Edit(base.CommandBase, common.BaseEdit):
@ -43,7 +43,7 @@ class Edit(base.CommandBase, common.BaseEdit):
use_pubsub=True,
use_draft=True,
use_verbose=True,
help=_(u"edit forums"),
help=_("edit forums"),
)
common.BaseEdit.__init__(self, self.host, FORUMS_TMP_DIR)
self.need_loop = True
@ -52,17 +52,16 @@ class Edit(base.CommandBase, common.BaseEdit):
self.parser.add_argument(
"-k",
"--key",
type=base.unicode_decoder,
default=u"",
help=_(u"forum key (DEFAULT: default forums)"),
default="",
help=_("forum key (DEFAULT: default forums)"),
)
def getTmpSuff(self):
"""return suffix used for content file"""
return u"json"
return "json"
def forumsSetCb(self):
self.disp(_(u"forums have been edited"), 1)
self.disp(_("forums have been edited"), 1)
self.host.quit()
def publish(self, forums_raw):
@ -75,7 +74,7 @@ class Edit(base.CommandBase, common.BaseEdit):
callback=self.forumsSetCb,
errback=partial(
self.errback,
msg=_(u"can't set forums: {}"),
msg=_("can't set forums: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -94,12 +93,12 @@ class Edit(base.CommandBase, common.BaseEdit):
def forumsGetEb(self, failure_):
# FIXME: error handling with bridge is broken, need to be properly fixed
if failure_.condition == u"item-not-found":
self.forumsGetCb(u"")
if failure_.condition == "item-not-found":
self.forumsGetCb("")
else:
self.errback(
failure_,
msg=_(u"can't get forums structure: {}"),
msg=_("can't get forums structure: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
)
@ -125,7 +124,7 @@ class Get(base.CommandBase):
extra_outputs=extra_outputs,
use_pubsub=True,
use_verbose=True,
help=_(u"get forums structure"),
help=_("get forums structure"),
)
self.need_loop = True
@ -133,9 +132,8 @@ class Get(base.CommandBase):
self.parser.add_argument(
"-k",
"--key",
type=base.unicode_decoder,
default=u"",
help=_(u"forum key (DEFAULT: default forums)"),
default="",
help=_("forum key (DEFAULT: default forums)"),
)
def default_output(self, forums, level=0):
@ -143,33 +141,33 @@ class Get(base.CommandBase):
keys = list(forum.keys())
keys.sort()
try:
keys.remove(u"title")
keys.remove("title")
except ValueError:
pass
else:
keys.insert(0, u"title")
keys.insert(0, "title")
try:
keys.remove(u"sub-forums")
keys.remove("sub-forums")
except ValueError:
pass
else:
keys.append(u"sub-forums")
keys.append("sub-forums")
for key in keys:
value = forum[key]
if key == "sub-forums":
self.default_output(value, level + 1)
else:
if self.host.verbosity < 1 and key != u"title":
if self.host.verbosity < 1 and key != "title":
continue
head_color = C.A_LEVEL_COLORS[level % len(C.A_LEVEL_COLORS)]
self.disp(
A.color(level * 4 * u" ", head_color, key, A.RESET, u": ", value)
A.color(level * 4 * " ", head_color, key, A.RESET, ": ", value)
)
def forumsGetCb(self, forums_raw):
if not forums_raw:
self.disp(_(u"no schema found"), 1)
self.disp(_("no schema found"), 1)
self.host.quit(1)
forums = json.loads(forums_raw)
self.output(forums)
@ -184,7 +182,7 @@ class Get(base.CommandBase):
callback=self.forumsGetCb,
errback=partial(
self.errback,
msg=_(u"can't get forums: {}"),
msg=_("can't get forums: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -195,5 +193,5 @@ class Forums(base.CommandBase):
def __init__(self, host):
super(Forums, self).__init__(
host, "forums", use_profile=False, help=_(u"Forums structure edition")
host, "forums", use_profile=False, help=_("Forums structure edition")
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from functools import partial
@ -36,13 +36,13 @@ class Get(base.CommandBase):
"get",
use_output=C.OUTPUT_DICT,
use_verbose=True,
help=_(u"get identity data"),
help=_("get identity data"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"jid", type=base.unicode_decoder, help=_(u"entity to check")
"jid", help=_("entity to check")
)
def identityGetCb(self, data):
@ -57,7 +57,7 @@ class Get(base.CommandBase):
callback=self.identityGetCb,
errback=partial(
self.errback,
msg=_(u"can't get identity data: {}"),
msg=_("can't get identity data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -71,13 +71,12 @@ class Set(base.CommandBase):
self.parser.add_argument(
"-f",
"--field",
type=base.unicode_decoder,
action="append",
nargs=2,
dest="fields",
metavar=(u"KEY", u"VALUE"),
metavar=("KEY", "VALUE"),
required=True,
help=_(u"identity field(s) to set"),
help=_("identity field(s) to set"),
)
self.need_loop = True
@ -89,7 +88,7 @@ class Set(base.CommandBase):
callback=self.host.quit,
errback=partial(
self.errback,
msg=_(u"can't set identity data data: {}"),
msg=_("can't set identity data data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat.tools.common.ansi import ANSI as A
from sat.tools.common import date_utils
@ -35,10 +35,10 @@ class Disco(base.CommandBase):
self.need_loop=True
def add_parser_options(self):
self.parser.add_argument(u"jid", type=base.unicode_decoder, help=_(u"entity to discover"))
self.parser.add_argument(u"-t", u"--type", type=str, choices=('infos', 'items', 'both'), default='both', help=_(u"type of data to discover"))
self.parser.add_argument(u"-n", u"--node", type=base.unicode_decoder, default=u'', help=_(u"node to use"))
self.parser.add_argument(u"-C", u"--no-cache", dest='use_cache', action="store_false", help=_(u"ignore cache"))
self.parser.add_argument("jid", help=_("entity to discover"))
self.parser.add_argument("-t", "--type", type=str, choices=('infos', 'items', 'both'), default='both', help=_("type of data to discover"))
self.parser.add_argument("-n", "--node", default='', help=_("node to use"))
self.parser.add_argument("-C", "--no-cache", dest='use_cache', action="store_false", help=_("ignore cache"))
def start(self):
self.get_infos = self.args.type in ('infos', 'both')
@ -51,7 +51,7 @@ class Disco(base.CommandBase):
self.host.bridge.discoInfos(jid, node=self.args.node, use_cache=self.args.use_cache, profile_key=self.host.profile, callback=lambda infos: self.gotInfos(infos, jid), errback=self.error)
def error(self, failure):
print (_("Error while doing discovery [%s]") % failure)
print((_("Error while doing discovery [%s]") % failure))
self.host.quit(1)
def gotInfos(self, infos, jid):
@ -68,78 +68,78 @@ class Disco(base.CommandBase):
features.sort()
identities.sort(key=lambda identity: identity[2])
data.update({
u'features': features,
u'identities': identities,
u'extensions': extensions})
'features': features,
'identities': identities,
'extensions': extensions})
if self.get_items:
items.sort(key=lambda item: item[2])
data[u'items'] = items
data['items'] = items
self.output(data)
self.host.quit()
def default_output(self, data):
features = data.get(u'features', [])
identities = data.get(u'identities', [])
extensions = data.get(u'extensions', {})
items = data.get(u'items', [])
features = data.get('features', [])
identities = data.get('identities', [])
extensions = data.get('extensions', {})
items = data.get('items', [])
identities_table = common.Table(self.host,
identities,
headers=(_(u'category'),
_(u'type'),
_(u'name')),
headers=(_('category'),
_('type'),
_('name')),
use_buffer=True)
extensions_tpl = []
extensions_types = extensions.keys()
extensions_types = list(extensions.keys())
extensions_types.sort()
for type_ in extensions_types:
fields = []
for field in extensions[type_]:
field_lines = []
data, values = field
data_keys = data.keys()
data_keys = list(data.keys())
data_keys.sort()
for key in data_keys:
field_lines.append(A.color(u'\t', C.A_SUBHEADER, key, A.RESET, u': ',
field_lines.append(A.color('\t', C.A_SUBHEADER, key, A.RESET, ': ',
data[key]))
if len(values) == 1:
field_lines.append(A.color(u'\t', C.A_SUBHEADER, u"value", A.RESET,
u': ', values[0] or (A.BOLD + u"UNSET")))
field_lines.append(A.color('\t', C.A_SUBHEADER, "value", A.RESET,
': ', values[0] or (A.BOLD + "UNSET")))
elif len(values) > 1:
field_lines.append(A.color(u'\t', C.A_SUBHEADER, u"values", A.RESET,
u': '))
field_lines.append(A.color('\t', C.A_SUBHEADER, "values", A.RESET,
': '))
for value in values:
field_lines.append(A.color(u'\t - ', A.BOLD, value))
fields.append(u'\n'.join(field_lines))
extensions_tpl.append(u'{type_}\n{fields}'.format(type_=type_,
field_lines.append(A.color('\t - ', A.BOLD, value))
fields.append('\n'.join(field_lines))
extensions_tpl.append('{type_}\n{fields}'.format(type_=type_,
fields='\n\n'.join(fields)))
items_table = common.Table(self.host,
items,
headers=(_(u'entity'),
_(u'node'),
_(u'name')),
headers=(_('entity'),
_('node'),
_('name')),
use_buffer=True)
template = []
if features:
template.append(A.color(C.A_HEADER, _(u"Features")) + u"\n\n{features}")
template.append(A.color(C.A_HEADER, _("Features")) + "\n\n{features}")
if identities:
template.append(A.color(C.A_HEADER, _(u"Identities")) + u"\n\n{identities}")
template.append(A.color(C.A_HEADER, _("Identities")) + "\n\n{identities}")
if extensions:
template.append(A.color(C.A_HEADER, _(u"Extensions")) + u"\n\n{extensions}")
template.append(A.color(C.A_HEADER, _("Extensions")) + "\n\n{extensions}")
if items:
template.append(A.color(C.A_HEADER, _(u"Items")) + u"\n\n{items}")
template.append(A.color(C.A_HEADER, _("Items")) + "\n\n{items}")
print u"\n\n".join(template).format(features = u'\n'.join(features),
print("\n\n".join(template).format(features = '\n'.join(features),
identities = identities_table.display().string,
extensions = u'\n'.join(extensions_tpl),
extensions = '\n'.join(extensions_tpl),
items = items_table.display().string,
)
))
class Version(base.CommandBase):
@ -157,7 +157,7 @@ class Version(base.CommandBase):
self.host.bridge.getSoftwareVersion(jid, self.host.profile, callback=self.gotVersion, errback=self.error)
def error(self, failure):
print (_("Error while trying to get version [%s]") % failure)
print((_("Error while trying to get version [%s]") % failure))
self.host.quit(1)
def gotVersion(self, data):
@ -170,7 +170,7 @@ class Version(base.CommandBase):
if os:
infos.append(_("Operating System: %s") % os)
print "\n".join(infos)
print("\n".join(infos))
self.host.quit()
@ -183,7 +183,7 @@ class Session(base.CommandBase):
def default_output(self, data):
started = data['started']
data['started'] = u'{short} (UTC, {relative})'.format(
data['started'] = '{short} (UTC, {relative})'.format(
short=date_utils.date_fmt(started),
relative=date_utils.date_fmt(started, 'relative'))
self.host.output(C.OUTPUT_DICT, 'simple', {}, data)
@ -199,7 +199,7 @@ class Session(base.CommandBase):
self.host.quit()
def _sessionInfoGetEb(self, error_data):
self.disp(_(u'Error getting session infos: {}').format(error_data), error=True)
self.disp(_('Error getting session infos: {}').format(error_data), error=True)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat.core import exceptions
from sat_frontends.jp.constants import Const as C
@ -56,7 +56,7 @@ class InputCommon(base.CommandBase):
def add_parser_options(self):
self.parser.add_argument(
"--encoding", default="utf-8", help=_(u"encoding of the input data")
"--encoding", default="utf-8", help=_("encoding of the input data")
)
self.parser.add_argument(
"-i",
@ -64,7 +64,7 @@ class InputCommon(base.CommandBase):
action="append_const",
const=(OPT_STDIN, None),
dest="arguments",
help=_(u"standard input"),
help=_("standard input"),
)
self.parser.add_argument(
"-s",
@ -72,7 +72,7 @@ class InputCommon(base.CommandBase):
type=self.opt(OPT_SHORT),
action="append",
dest="arguments",
help=_(u"short option"),
help=_("short option"),
)
self.parser.add_argument(
"-l",
@ -80,7 +80,7 @@ class InputCommon(base.CommandBase):
type=self.opt(OPT_LONG),
action="append",
dest="arguments",
help=_(u"long option"),
help=_("long option"),
)
self.parser.add_argument(
"-p",
@ -88,7 +88,7 @@ class InputCommon(base.CommandBase):
type=self.opt(OPT_POS),
action="append",
dest="arguments",
help=_(u"positional argument"),
help=_("positional argument"),
)
self.parser.add_argument(
"-x",
@ -96,19 +96,19 @@ class InputCommon(base.CommandBase):
action="append_const",
const=(OPT_IGNORE, None),
dest="arguments",
help=_(u"ignore value"),
help=_("ignore value"),
)
self.parser.add_argument(
"-D",
"--debug",
action="store_true",
help=_(u"don't actually run commands but echo what would be launched"),
help=_("don't actually run commands but echo what would be launched"),
)
self.parser.add_argument(
"--log", type=argparse.FileType("wb"), help=_(u"log stdout to FILE")
"--log", type=argparse.FileType("wb"), help=_("log stdout to FILE")
)
self.parser.add_argument(
"--log-err", type=argparse.FileType("wb"), help=_(u"log stderr to FILE")
"--log-err", type=argparse.FileType("wb"), help=_("log stderr to FILE")
)
self.parser.add_argument("command", nargs=argparse.REMAINDER)
@ -123,7 +123,7 @@ class InputCommon(base.CommandBase):
arg_type, arg_name = arguments[self.args_idx]
except IndexError:
self.disp(
_(u"arguments in input data and in arguments sequence don't match"),
_("arguments in input data and in arguments sequence don't match"),
error=True,
)
self.host.quit(C.EXIT_DATA_ERROR)
@ -150,13 +150,13 @@ class InputCommon(base.CommandBase):
self.disp(
A.color(
C.A_SUBHEADER,
_(u"values: "),
_("values: "),
A.RESET,
u", ".join(self._values_ori),
", ".join(self._values_ori),
),
2,
)
self.disp(A.color(A.BOLD, _(u"**SKIPPING**\n")))
self.disp(A.color(A.BOLD, _("**SKIPPING**\n")))
self.reset()
self.idx += 1
raise exceptions.CancelError
@ -180,7 +180,7 @@ class InputCommon(base.CommandBase):
else:
self.parser.error(
_(
u"Invalid argument, an option type is expected, got {type_}:{name}"
"Invalid argument, an option type is expected, got {type_}:{name}"
).format(type_=arg_type, name=arg_name)
)
@ -188,39 +188,39 @@ class InputCommon(base.CommandBase):
"""run requested command with parsed arguments"""
if self.args_idx != len(self.args.arguments):
self.disp(
_(u"arguments in input data and in arguments sequence don't match"),
_("arguments in input data and in arguments sequence don't match"),
error=True,
)
self.host.quit(C.EXIT_DATA_ERROR)
self.disp(
A.color(C.A_HEADER, _(u"command {idx}").format(idx=self.idx)),
A.color(C.A_HEADER, _("command {idx}").format(idx=self.idx)),
no_lf=not self.args.debug,
)
stdin = "".join(self._stdin)
if self.args.debug:
self.disp(
A.color(
C.A_SUBHEADER, _(u"values: "), A.RESET, u", ".join(self._values_ori)
C.A_SUBHEADER, _("values: "), A.RESET, ", ".join(self._values_ori)
),
2,
)
if stdin:
self.disp(A.color(C.A_SUBHEADER, u"--- STDIN ---"))
self.disp(stdin.decode("utf-8"))
self.disp(A.color(C.A_SUBHEADER, u"-------------"))
self.disp(A.color(C.A_SUBHEADER, "--- STDIN ---"))
self.disp(stdin)
self.disp(A.color(C.A_SUBHEADER, "-------------"))
self.disp(
u"{indent}{prog} {static} {options} {positionals}".format(
indent=4 * u" ",
"{indent}{prog} {static} {options} {positionals}".format(
indent=4 * " ",
prog=sys.argv[0],
static=" ".join(self.args.command).decode("utf-8"),
options=u" ".join([o.decode("utf-8") for o in self._opts]),
positionals=u" ".join([p.decode("utf-8") for p in self._pos]),
static=" ".join(self.args.command),
options=" ".join([o for o in self._opts]),
positionals=" ".join([p for p in self._pos]),
)
)
self.disp(u"\n")
self.disp("\n")
else:
self.disp(u" (" + u", ".join(self._values_ori) + u")", 2, no_lf=True)
self.disp(" (" + ", ".join(self._values_ori) + ")", 2, no_lf=True)
args = [sys.argv[0]] + self.args.command + self._opts + self._pos
p = subprocess.Popen(
args,
@ -238,9 +238,9 @@ class InputCommon(base.CommandBase):
log_err.write(log_tpl.format(command=" ".join(args), buff=stderr))
ret = p.wait()
if ret == 0:
self.disp(A.color(C.A_SUCCESS, _(u"OK")))
self.disp(A.color(C.A_SUCCESS, _("OK")))
else:
self.disp(A.color(C.A_FAILURE, _(u"FAILED")))
self.disp(A.color(C.A_FAILURE, _("FAILED")))
self.reset()
self.idx += 1
@ -260,7 +260,7 @@ class InputCommon(base.CommandBase):
class Csv(InputCommon):
def __init__(self, host):
super(Csv, self).__init__(host, "csv", _(u"comma-separated values"))
super(Csv, self).__init__(host, "csv", _("comma-separated values"))
def add_parser_options(self):
InputCommon.add_parser_options(self)
@ -269,7 +269,7 @@ class Csv(InputCommon):
"--row",
type=int,
default=0,
help=_(u"starting row (previous ones will be ignored)"),
help=_("starting row (previous ones will be ignored)"),
)
self.parser.add_argument(
"-S",
@ -277,7 +277,7 @@ class Csv(InputCommon):
action="append_const",
const=("split", None),
dest="arguments",
help=_(u"split value in several options"),
help=_("split value in several options"),
)
self.parser.add_argument(
"-E",
@ -285,8 +285,8 @@ class Csv(InputCommon):
action="append",
type=self.opt("empty"),
dest="arguments",
help=_(u"action to do on empty value ({choices})").format(
choices=u", ".join(OPT_EMPTY_CHOICES)
help=_("action to do on empty value ({choices})").format(
choices=", ".join(OPT_EMPTY_CHOICES)
),
)
@ -300,8 +300,8 @@ class Csv(InputCommon):
return value if value else False
else:
self.parser.error(
_(u"--empty value must be one of {choices}").format(
choices=u", ".join(OPT_EMPTY_CHOICES)
_("--empty value must be one of {choices}").format(
choices=", ".join(OPT_EMPTY_CHOICES)
)
)
@ -331,5 +331,5 @@ class Input(base.CommandBase):
host,
"input",
use_profile=False,
help=_(u"launch command with external input"),
help=_("launch command with external input"),
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat_frontends.jp.constants import Const as C
from sat.tools.common.ansi import ANSI as A
@ -36,7 +36,7 @@ class Create(base.CommandBase):
"create",
use_profile=False,
use_output=C.OUTPUT_DICT,
help=_(u"create and send an invitation"),
help=_("create and send an invitation"),
)
self.need_loop = True
@ -44,28 +44,24 @@ class Create(base.CommandBase):
self.parser.add_argument(
"-j",
"--jid",
type=base.unicode_decoder,
default="",
help="jid of the invitee (default: generate one)",
)
self.parser.add_argument(
"-P",
"--password",
type=base.unicode_decoder,
default="",
help="password of the invitee profile/XMPP account (default: generate one)",
)
self.parser.add_argument(
"-n",
"--name",
type=base.unicode_decoder,
default="",
help="name of the invitee",
)
self.parser.add_argument(
"-N",
"--host-name",
type=base.unicode_decoder,
default="",
help="name of the host",
)
@ -73,7 +69,6 @@ class Create(base.CommandBase):
"-e",
"--email",
action="append",
type=base.unicode_decoder,
default=[],
help="email(s) to send the invitation to (if --no-email is set, email will just be saved)",
)
@ -83,28 +78,24 @@ class Create(base.CommandBase):
self.parser.add_argument(
"-l",
"--lang",
type=base.unicode_decoder,
default="",
help="main language spoken by the invitee",
)
self.parser.add_argument(
"-u",
"--url",
type=base.unicode_decoder,
default="",
help="template to construct the URL",
)
self.parser.add_argument(
"-s",
"--subject",
type=base.unicode_decoder,
default="",
help="subject of the invitation email (default: generic subject)",
)
self.parser.add_argument(
"-b",
"--body",
type=base.unicode_decoder,
default="",
help="body of the invitation email (default: generic body)",
)
@ -112,7 +103,6 @@ class Create(base.CommandBase):
"-x",
"--extra",
metavar=("KEY", "VALUE"),
type=base.unicode_decoder,
action="append",
nargs=2,
default=[],
@ -121,7 +111,6 @@ class Create(base.CommandBase):
self.parser.add_argument(
"-p",
"--profile",
type=base.unicode_decoder,
default="",
help="profile doing the invitation (default: don't associate profile)",
)
@ -132,7 +121,7 @@ class Create(base.CommandBase):
def invitationCreateEb(self, failure_):
self.disp(
u"can't create invitation: {reason}".format(reason=failure_), error=True
"can't create invitation: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -143,11 +132,11 @@ class Create(base.CommandBase):
if self.args.no_email:
if email:
extra["email"] = email
data_format.iter2dict(u"emails_extra", emails_extra)
data_format.iter2dict("emails_extra", emails_extra)
else:
if not email:
self.parser.error(
_(u"you need to specify an email address to send email invitation")
_("you need to specify an email address to send email invitation")
)
self.host.bridge.invitationCreate(
@ -176,19 +165,19 @@ class Get(base.CommandBase):
"get",
use_profile=False,
use_output=C.OUTPUT_DICT,
help=_(u"get invitation data"),
help=_("get invitation data"),
)
self.need_loop = True
def add_parser_options(self):
self.parser.add_argument(
"id", type=base.unicode_decoder, help=_(u"invitation UUID")
"id", help=_("invitation UUID")
)
self.parser.add_argument(
"-j",
"--with-jid",
action="store_true",
help=_(u"start profile session and retrieve jid"),
help=_("start profile session and retrieve jid"),
)
def output_data(self, data, jid_=None):
@ -199,28 +188,28 @@ class Get(base.CommandBase):
def invitationGetCb(self, invitation_data):
if self.args.with_jid:
profile = invitation_data[u"guest_profile"]
profile = invitation_data["guest_profile"]
def session_started(__):
self.host.bridge.asyncGetParamA(
u"JabberID",
u"Connection",
"JabberID",
"Connection",
profile_key=profile,
callback=lambda jid_: self.output_data(invitation_data, jid_),
errback=partial(
self.errback,
msg=_(u"can't retrieve jid: {}"),
msg=_("can't retrieve jid: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
self.host.bridge.profileStartSession(
invitation_data[u"password"],
invitation_data["password"],
profile,
callback=session_started,
errback=partial(
self.errback,
msg=_(u"can't start session: {}"),
msg=_("can't start session: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -233,7 +222,7 @@ class Get(base.CommandBase):
callback=self.invitationGetCb,
errback=partial(
self.errback,
msg=_(u"can't get invitation data: {}"),
msg=_("can't get invitation data: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -242,7 +231,7 @@ class Get(base.CommandBase):
class Modify(base.CommandBase):
def __init__(self, host):
base.CommandBase.__init__(
self, host, "modify", use_profile=False, help=_(u"modify existing invitation")
self, host, "modify", use_profile=False, help=_("modify existing invitation")
)
self.need_loop = True
@ -253,21 +242,18 @@ class Modify(base.CommandBase):
self.parser.add_argument(
"-n",
"--name",
type=base.unicode_decoder,
default="",
help="name of the invitee",
)
self.parser.add_argument(
"-N",
"--host-name",
type=base.unicode_decoder,
default="",
help="name of the host",
)
self.parser.add_argument(
"-e",
"--email",
type=base.unicode_decoder,
default="",
help="email to send the invitation to (if --no-email is set, email will just be saved)",
)
@ -275,7 +261,6 @@ class Modify(base.CommandBase):
"-l",
"--lang",
dest="language",
type=base.unicode_decoder,
default="",
help="main language spoken by the invitee",
)
@ -283,7 +268,6 @@ class Modify(base.CommandBase):
"-x",
"--extra",
metavar=("KEY", "VALUE"),
type=base.unicode_decoder,
action="append",
nargs=2,
default=[],
@ -292,21 +276,20 @@ class Modify(base.CommandBase):
self.parser.add_argument(
"-p",
"--profile",
type=base.unicode_decoder,
default="",
help="profile doing the invitation (default: don't associate profile",
)
self.parser.add_argument(
"id", type=base.unicode_decoder, help=_(u"invitation UUID")
"id", help=_("invitation UUID")
)
def invitationModifyCb(self):
self.disp(_(u"invitations have been modified correctly"))
self.disp(_("invitations have been modified correctly"))
self.host.quit(C.EXIT_OK)
def invitationModifyEb(self, failure_):
self.disp(
u"can't create invitation: {reason}".format(reason=failure_), error=True
"can't create invitation: {reason}".format(reason=failure_), error=True
)
self.host.quit(C.EXIT_BRIDGE_ERRBACK)
@ -319,7 +302,7 @@ class Modify(base.CommandBase):
if arg_name in extra:
self.parser.error(
_(
u"you can't set {arg_name} in both optional argument and extra"
"you can't set {arg_name} in both optional argument and extra"
).format(arg_name=arg_name)
)
extra[arg_name] = value
@ -342,26 +325,26 @@ class List(base.CommandBase):
use_profile=False,
use_output=C.OUTPUT_COMPLEX,
extra_outputs=extra_outputs,
help=_(u"list invitations data"),
help=_("list invitations data"),
)
self.need_loop = True
def default_output(self, data):
for idx, datum in enumerate(data.iteritems()):
for idx, datum in enumerate(data.items()):
if idx:
self.disp(u"\n")
self.disp("\n")
key, invitation_data = datum
self.disp(A.color(C.A_HEADER, key))
indent = u" "
for k, v in invitation_data.iteritems():
self.disp(indent + A.color(C.A_SUBHEADER, k + u":") + u" " + unicode(v))
indent = " "
for k, v in invitation_data.items():
self.disp(indent + A.color(C.A_SUBHEADER, k + ":") + " " + str(v))
def add_parser_options(self):
self.parser.add_argument(
"-p",
"--profile",
default=C.PROF_KEY_NONE,
help=_(u"return only invitations linked to this profile"),
help=_("return only invitations linked to this profile"),
)
def invitationListCb(self, data):
@ -374,7 +357,7 @@ class List(base.CommandBase):
callback=self.invitationListCb,
errback=partial(
self.errback,
msg=_(u"can't list invitations: {}"),
msg=_("can't list invitations: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -388,5 +371,5 @@ class Invitation(base.CommandBase):
host,
"invitation",
use_profile=False,
help=_(u"invitation of user(s) without XMPP account"),
help=_("invitation of user(s) without XMPP account"),
)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base
from . import base
from sat.core.i18n import _
from sat.tools.common import data_format
from sat_frontends.jp.constants import Const as C
@ -37,8 +37,8 @@ class Set(base.CommandBase):
host,
"set",
use_pubsub=True,
pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
help=_(u"publish or update a merge request"),
pubsub_defaults={"service": _("auto"), "node": _("auto")},
help=_("publish or update a merge request"),
)
self.need_loop = True
@ -46,59 +46,56 @@ class Set(base.CommandBase):
self.parser.add_argument(
"-i",
"--item",
type=base.unicode_decoder,
default=u"",
help=_(u"id or URL of the request to update, or nothing for a new one"),
default="",
help=_("id or URL of the request to update, or nothing for a new one"),
)
self.parser.add_argument(
"-r",
"--repository",
metavar="PATH",
type=base.unicode_decoder,
default=u".",
help=_(u"path of the repository (DEFAULT: current directory)"),
default=".",
help=_("path of the repository (DEFAULT: current directory)"),
)
self.parser.add_argument(
"-f",
"--force",
action="store_true",
help=_(u"publish merge request without confirmation"),
help=_("publish merge request without confirmation"),
)
self.parser.add_argument(
"-l",
"--label",
dest="labels",
type=base.unicode_decoder,
action="append",
help=_(u"labels to categorize your request"),
help=_("labels to categorize your request"),
)
def mergeRequestSetCb(self, published_id):
if published_id:
self.disp(u"Merge request published at {pub_id}".format(pub_id=published_id))
self.disp("Merge request published at {pub_id}".format(pub_id=published_id))
else:
self.disp(u"Merge request published")
self.disp("Merge request published")
self.host.quit(C.EXIT_OK)
def sendRequest(self):
extra = {"update": True} if self.args.item else {}
values = {}
if self.args.labels is not None:
values[u"labels"] = self.args.labels
values["labels"] = self.args.labels
self.host.bridge.mergeRequestSet(
self.args.service,
self.args.node,
self.repository,
u"auto",
"auto",
values,
u"",
"",
self.args.item,
data_format.serialise(extra),
self.profile,
callback=self.mergeRequestSetCb,
errback=partial(
self.errback,
msg=_(u"can't create merge request: {}"),
msg=_("can't create merge request: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -106,9 +103,9 @@ class Set(base.CommandBase):
def askConfirmation(self):
if not self.args.force:
message = _(
u"You are going to publish your changes to service [{service}], are you sure ?"
"You are going to publish your changes to service [{service}], are you sure ?"
).format(service=self.args.service)
self.host.confirmOrQuit(message, _(u"merge request publication cancelled"))
self.host.confirmOrQuit(message, _("merge request publication cancelled"))
self.sendRequest()
def start(self):
@ -125,8 +122,8 @@ class Get(base.CommandBase):
use_verbose=True,
use_pubsub=True,
pubsub_flags={C.MULTI_ITEMS},
pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
help=_(u"get a merge request"),
pubsub_defaults={"service": _("auto"), "node": _("auto")},
help=_("get a merge request"),
)
self.need_loop = True
@ -141,7 +138,7 @@ class Get(base.CommandBase):
for request_xmlui in requests_data[0]:
xmlui = xmlui_manager.create(self.host, request_xmlui, whitelist=whitelist)
xmlui.show(values_only=True)
self.disp(u"")
self.disp("")
self.host.quit(C.EXIT_OK)
def getRequests(self):
@ -151,13 +148,13 @@ class Get(base.CommandBase):
self.args.node,
self.args.max,
self.args.items,
u"",
"",
extra,
self.profile,
callback=self.mergeRequestGetCb,
errback=partial(
self.errback,
msg=_(u"can't get merge request: {}"),
msg=_("can't get merge request: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)
@ -176,8 +173,8 @@ class Import(base.CommandBase):
"import",
use_pubsub=True,
pubsub_flags={C.SINGLE_ITEM, C.ITEM},
pubsub_defaults={u"service": _(u"auto"), u"node": _(u"auto")},
help=_(u"import a merge request"),
pubsub_defaults={"service": _("auto"), "node": _("auto")},
help=_("import a merge request"),
)
self.need_loop = True
@ -186,9 +183,8 @@ class Import(base.CommandBase):
"-r",
"--repository",
metavar="PATH",
type=base.unicode_decoder,
default=u".",
help=_(u"path of the repository (DEFAULT: current directory)"),
default=".",
help=_("path of the repository (DEFAULT: current directory)"),
)
def mergeRequestImportCb(self):
@ -206,7 +202,7 @@ class Import(base.CommandBase):
callback=self.mergeRequestImportCb,
errback=partial(
self.errback,
msg=_(u"can't import merge request: {}"),
msg=_("can't import merge request: {}"),
exit_code=C.EXIT_BRIDGE_ERRBACK,
),
)

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