code style reformatting using black

This commit is contained in:
Goffi 2018-06-27 20:14:46 +02:00
commit 744cb0c503
13 changed files with 21394 additions and 10488 deletions

View file

@ -24,11 +24,15 @@ from collections import OrderedDict # only available from python 2.7
class Const(constants.Const):
PRESENCE = OrderedDict([("", _("Online")),
("chat", _("Free for chat")),
("away", _("Away from keyboard")),
("dnd", _("Do not disturb")),
("xa", _("Extended away"))])
PRESENCE = OrderedDict(
[
("", _("Online")),
("chat", _("Free for chat")),
("away", _("Away from keyboard")),
("dnd", _("Do not disturb")),
("xa", _("Extended away")),
]
)
# from plugin_misc_text_syntaxes
SYNTAX_XHTML = "XHTML"
@ -42,27 +46,32 @@ class Const(constants.Const):
XMLUI_STATUS_CANCELLED = constants.Const.XMLUI_DATA_CANCELLED
# Roster
CONTACT_GROUPS = 'groups'
CONTACT_RESOURCES = 'resources'
CONTACT_MAIN_RESOURCE = 'main_resource'
CONTACT_SPECIAL = 'special'
CONTACT_SPECIAL_GROUP = 'group' # group chat special entity
CONTACT_SELECTED = 'selected'
CONTACT_GROUPS = "groups"
CONTACT_RESOURCES = "resources"
CONTACT_MAIN_RESOURCE = "main_resource"
CONTACT_SPECIAL = "special"
CONTACT_SPECIAL_GROUP = "group" # group chat special entity
CONTACT_SELECTED = "selected"
# used in handler to track where the contact is coming from
CONTACT_PROFILE = 'profile'
CONTACT_PROFILE = "profile"
CONTACT_SPECIAL_ALLOWED = (CONTACT_SPECIAL_GROUP,) # allowed values for special flag
# set of forbidden names for contact data
CONTACT_DATA_FORBIDDEN = {CONTACT_GROUPS, CONTACT_RESOURCES, CONTACT_MAIN_RESOURCE,
CONTACT_SELECTED, CONTACT_PROFILE}
CONTACT_DATA_FORBIDDEN = {
CONTACT_GROUPS,
CONTACT_RESOURCES,
CONTACT_MAIN_RESOURCE,
CONTACT_SELECTED,
CONTACT_PROFILE,
}
# Chats
CHAT_STATE_ICON = {
"": u" ",
"active": u'✔',
"inactive": u'☄',
"gone": u'✈',
"composing": u'✎',
"paused": u"…"
"active": u"✔",
"inactive": u"☄",
"gone": u"✈",
"composing": u"✎",
"paused": u"…",
}
# Blogs
@ -72,26 +81,36 @@ class Const(constants.Const):
# Widgets management
# FIXME: should be in quick_frontend.constant, but Libervia doesn't inherit from it
WIDGET_NEW = 'NEW'
WIDGET_KEEP = 'KEEP'
WIDGET_RAISE = 'RAISE'
WIDGET_RECREATE = 'RECREATE'
WIDGET_NEW = "NEW"
WIDGET_KEEP = "KEEP"
WIDGET_RAISE = "RAISE"
WIDGET_RECREATE = "RECREATE"
# Updates (generic)
UPDATE_DELETE = 'DELETE'
UPDATE_MODIFY = 'MODIFY'
UPDATE_ADD = 'ADD'
UPDATE_SELECTION = 'SELECTION'
UPDATE_DELETE = "DELETE"
UPDATE_MODIFY = "MODIFY"
UPDATE_ADD = "ADD"
UPDATE_SELECTION = "SELECTION"
# high level update (i.e. not item level but organisation of items)
UPDATE_STRUCTURE = 'STRUCTURE'
UPDATE_STRUCTURE = "STRUCTURE"
LISTENERS = {'avatar', 'nick', 'presence', 'profilePlugged', 'disconnect', 'gotMenus',
'menu', 'notification', 'notificationsClear', 'progressFinished',
'progressError'}
LISTENERS = {
"avatar",
"nick",
"presence",
"profilePlugged",
"disconnect",
"gotMenus",
"menu",
"notification",
"notificationsClear",
"progressFinished",
"progressError",
}
# Notifications
NOTIFY_MESSAGE = 'MESSAGE' # a message has been received
NOTIFY_MENTION = 'MENTION' # user has been mentionned
NOTIFY_PROGRESS_END = 'PROGRESS_END' # a progression has finised
NOTIFY_GENERIC = 'GENERIC' # a notification which has not its own type
NOTIFY_MESSAGE = "MESSAGE" # a message has been received
NOTIFY_MENTION = "MENTION" # user has been mentionned
NOTIFY_PROGRESS_END = "PROGRESS_END" # a progression has finised
NOTIFY_GENERIC = "GENERIC" # a notification which has not its own type
NOTIFY_ALL = (NOTIFY_MESSAGE, NOTIFY_MENTION, NOTIFY_PROGRESS_END, NOTIFY_GENERIC)

View file

@ -18,6 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core.i18n import _
@ -39,13 +40,17 @@ import time
try:
# FIXME: to be removed when an acceptable solution is here
unicode('') # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
unicode("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
unicode = str
class ProfileManager(object):
"""Class managing all data relative to one profile, and plugging in mechanism"""
# TODO: handle waiting XMLUI requests: getWaitingConf doesn't exist anymore
# and a way to keep some XMLUI request between sessions is expected in backend
host = None
@ -69,8 +74,13 @@ class ProfileManager(object):
def plug(self):
"""Plug the profile to the host"""
# we get the essential params
self.bridge.asyncGetParamA("JabberID", "Connection", profile_key=self.profile,
callback=self._plug_profile_jid, errback=self._getParamError)
self.bridge.asyncGetParamA(
"JabberID",
"Connection",
profile_key=self.profile,
callback=self._plug_profile_jid,
errback=self._getParamError,
)
def _plug_profile_jid(self, jid_s):
self.whoami = jid.JID(jid_s) # resource might change after the connection
@ -78,24 +88,40 @@ class ProfileManager(object):
def _autodisconnectEb(self, failure_):
# XXX: we ignore error on this parameter, as Libervia can't access it
log.warning(_("Error while trying to get autodisconnect param, ignoring: {}").format(failure_))
log.warning(
_("Error while trying to get autodisconnect param, ignoring: {}").format(
failure_
)
)
self._plug_profile_autodisconnect("false")
def _plug_profile_isconnected(self, connected):
self.connected = connected
self.bridge.asyncGetParamA("autodisconnect", "Connection", profile_key=self.profile,
callback=self._plug_profile_autodisconnect, errback=self._autodisconnectEb)
self.bridge.asyncGetParamA(
"autodisconnect",
"Connection",
profile_key=self.profile,
callback=self._plug_profile_autodisconnect,
errback=self._autodisconnectEb,
)
def _plug_profile_autodisconnect(self, autodisconnect):
if C.bool(autodisconnect):
self._autodisconnect = True
self.bridge.asyncGetParamA("autoconnect", "Connection", profile_key=self.profile,
callback=self._plug_profile_autoconnect, errback=self._getParamError)
self.bridge.asyncGetParamA(
"autoconnect",
"Connection",
profile_key=self.profile,
callback=self._plug_profile_autoconnect,
errback=self._getParamError,
)
def _plug_profile_autoconnect(self, value_str):
autoconnect = C.bool(value_str)
if autoconnect and not self.connected:
self.host.connect(self.profile, callback=lambda dummy: self._plug_profile_afterconnect())
self.host.connect(
self.profile, callback=lambda dummy: self._plug_profile_afterconnect()
)
else:
self._plug_profile_afterconnect()
@ -103,7 +129,11 @@ class ProfileManager(object):
# Profile can be connected or not
# we get cached data
self.connected = True
self.host.bridge.getFeatures(profile_key=self.profile, callback=self._plug_profile_getFeaturesCb, errback=self._plug_profile_getFeaturesEb)
self.host.bridge.getFeatures(
profile_key=self.profile,
callback=self._plug_profile_getFeaturesCb,
errback=self._plug_profile_getFeaturesEb,
)
def _plug_profile_getFeaturesEb(self, failure):
log.error(u"Couldn't get features: {}".format(failure))
@ -129,42 +159,60 @@ class ProfileManager(object):
self.host.entityDataUpdatedHandler(entity_s, key, value, self.profile)
if not self.connected:
self.host.setPresenceStatus(C.PRESENCE_UNAVAILABLE, '', profile=self.profile)
self.host.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "", profile=self.profile)
else:
contact_list.fill()
self.host.setPresenceStatus(profile=self.profile)
#The waiting subscription requests
self.bridge.getWaitingSub(self.profile, callback=self._plug_profile_gotWaitingSub)
# The waiting subscription requests
self.bridge.getWaitingSub(
self.profile, callback=self._plug_profile_gotWaitingSub
)
def _plug_profile_gotWaitingSub(self, waiting_sub):
for sub in waiting_sub:
self.host.subscribeHandler(waiting_sub[sub], sub, self.profile)
self.bridge.mucGetRoomsJoined(self.profile, callback=self._plug_profile_gotRoomsJoined)
self.bridge.mucGetRoomsJoined(
self.profile, callback=self._plug_profile_gotRoomsJoined
)
def _plug_profile_gotRoomsJoined(self, rooms_args):
#Now we open the MUC window where we already are:
# Now we open the MUC window where we already are:
for room_args in rooms_args:
self.host.mucRoomJoinedHandler(*room_args, profile=self.profile)
#Presence must be requested after rooms are filled
self.host.bridge.getPresenceStatuses(self.profile, callback=self._plug_profile_gotPresences)
# Presence must be requested after rooms are filled
self.host.bridge.getPresenceStatuses(
self.profile, callback=self._plug_profile_gotPresences
)
def _plug_profile_gotPresences(self, presences):
def gotEntityData(data, contact):
for key in ('avatar', 'nick'):
for key in ("avatar", "nick"):
if key in data:
self.host.entityDataUpdatedHandler(contact, key, data[key], self.profile)
self.host.entityDataUpdatedHandler(
contact, key, data[key], self.profile
)
for contact in presences:
for res in presences[contact]:
jabber_id = (u'%s/%s' % (jid.JID(contact).bare, res)) if res else contact
jabber_id = (u"%s/%s" % (jid.JID(contact).bare, res)) if res else contact
show = presences[contact][res][0]
priority = presences[contact][res][1]
statuses = presences[contact][res][2]
self.host.presenceUpdateHandler(jabber_id, show, priority, statuses, self.profile)
self.host.bridge.getEntityData(contact, ['avatar', 'nick'], self.profile, callback=lambda data, contact=contact: gotEntityData(data, contact), errback=lambda failure, contact=contact: log.debug(u"No cache data for {}".format(contact)))
self.host.presenceUpdateHandler(
jabber_id, show, priority, statuses, self.profile
)
self.host.bridge.getEntityData(
contact,
["avatar", "nick"],
self.profile,
callback=lambda data, contact=contact: gotEntityData(data, contact),
errback=lambda failure, contact=contact: log.debug(
u"No cache data for {}".format(contact)
),
)
# At this point, profile should be fully plugged
# and we launch frontend specific method
@ -200,13 +248,15 @@ class ProfilesManager(object):
def plug(self, profile):
if profile in self._profiles:
raise exceptions.ConflictError('A profile of the name [{}] is already plugged'.format(profile))
raise exceptions.ConflictError(
"A profile of the name [{}] is already plugged".format(profile)
)
self._profiles[profile] = ProfileManager(profile)
self._profiles[profile].plug()
def unplug(self, profile):
if profile not in self._profiles:
raise ValueError('The profile [{}] is not plugged'.format(profile))
raise ValueError("The profile [{}] is not plugged".format(profile))
# remove the contact list and its listener
host = self._profiles[profile].host
@ -220,6 +270,7 @@ class ProfilesManager(object):
class QuickApp(object):
"""This class contain the main methods needed for the frontend"""
MB_HANDLER = True # Set to False if the frontend doesn't manage microblog
AVATARS_HANDLER = True # set to False if avatars are not used
@ -234,9 +285,11 @@ class QuickApp(object):
self.menus = quick_menus.QuickMenusManager(self)
ProfileManager.host = self
self.profiles = ProfilesManager()
self._plugs_in_progress = set() # profiles currently being plugged, used to (un)lock contact list updates
self.ready_profiles = set() # profiles which are connected and ready
self.signals_cache = {} # used to keep signal received between start of plug_profile and when the profile is actualy ready
self._plugs_in_progress = (
set()
) # profiles currently being plugged, used to (un)lock contact list updates
self.ready_profiles = set() # profiles which are connected and ready
self.signals_cache = {} # used to keep signal received between start of plug_profile and when the profile is actualy ready
self.contact_lists = quick_contact_list.QuickContactListHandler(self)
self.widgets = quick_widgets.QuickWidgetsManager(self)
if check_options is not None:
@ -245,13 +298,17 @@ class QuickApp(object):
self.options = None
# widgets
self.selected_widget = None # widget currently selected (must be filled by frontend)
self.selected_widget = (
None
) # widget currently selected (must be filled by frontend)
# listeners
self._listeners = {} # key: listener type ("avatar", "selected", etc), value: list of callbacks
self._listeners = {} # key: listener type ("avatar", "selected", etc), value: list of callbacks
# triggers
self.trigger = trigger.TriggerManager() # trigger are used to change the default behaviour
self.trigger = (
trigger.TriggerManager()
) # trigger are used to change the default behaviour
## bridge ##
self.bridge = bridge_factory()
@ -274,8 +331,9 @@ class QuickApp(object):
log.error(_(u"Can't get namespaces map: {msg}").format(msg=failure_))
def onBridgeConnected(self):
self.bridge.namespacesGet(callback=self._namespacesGetCb,
errback=self._namespacesGetEb)
self.bridge.namespacesGet(
callback=self._namespacesGetCb, errback=self._namespacesGetEb
)
def _bridgeCb(self):
self.registerSignal("connected")
@ -331,7 +389,9 @@ class QuickApp(object):
"""
raise NotImplementedError
def registerSignal(self, function_name, handler=None, iface="core", with_profile=True):
def registerSignal(
self, function_name, handler=None, iface="core", with_profile=True
):
"""Register a handler for a signal
@param function_name (str): name of the signal to handle
@ -339,15 +399,15 @@ class QuickApp(object):
@param iface (str): interface of the bridge to use ('core' or 'plugin')
@param with_profile (boolean): True if the signal concerns a specific profile, in that case the profile name has to be passed by the caller
"""
log.debug(u"registering signal {name}".format(name = function_name))
log.debug(u"registering signal {name}".format(name=function_name))
if handler is None:
handler = getattr(self, "{}{}".format(function_name, 'Handler'))
handler = getattr(self, "{}{}".format(function_name, "Handler"))
if not with_profile:
self.bridge.register_signal(function_name, handler, iface)
return
def signalReceived(*args, **kwargs):
profile = kwargs.get('profile')
profile = kwargs.get("profile")
if profile is None:
if not args:
raise exceptions.ProfileNotSetError
@ -356,9 +416,12 @@ class QuickApp(object):
if not self.check_profile(profile):
if profile in self.profiles:
# profile is not ready but is in self.profiles, that's mean that it's being connecting and we need to cache the signal
self.signals_cache.setdefault(profile, []).append((function_name, handler, args, kwargs))
self.signals_cache.setdefault(profile, []).append(
(function_name, handler, args, kwargs)
)
return # we ignore signal for profiles we don't manage
handler(*args, **kwargs)
self.bridge.register_signal(function_name, signalReceived, iface)
def addListener(self, type_, callback, profiles_filter=None):
@ -449,10 +512,13 @@ class QuickApp(object):
# profile is ready, we can call send signals that where is cache
cached_signals = self.signals_cache.pop(profile, [])
for function_name, handler, args, kwargs in cached_signals:
log.debug(u"Calling cached signal [%s] with args %s and kwargs %s" % (function_name, args, kwargs))
log.debug(
u"Calling cached signal [%s] with args %s and kwargs %s"
% (function_name, args, kwargs)
)
handler(*args, **kwargs)
self.callListeners('profilePlugged', profile=profile)
self.callListeners("profilePlugged", profile=profile)
if not self._plugs_in_progress:
self.contact_lists.lockUpdate(False)
@ -460,24 +526,29 @@ class QuickApp(object):
if not callback:
callback = lambda dummy: None
if not errback:
def errback(failure):
log.error(_(u"Can't connect profile [%s]") % failure)
try:
module = failure.module
except AttributeError:
module = ''
module = ""
try:
message = failure.message
except AttributeError:
message = 'error'
message = "error"
try:
fullname = failure.fullname
except AttributeError:
fullname = 'error'
if module.startswith('twisted.words.protocols.jabber') and failure.condition == "not-authorized":
fullname = "error"
if (
module.startswith("twisted.words.protocols.jabber")
and failure.condition == "not-authorized"
):
self.launchAction(C.CHANGE_XMPP_PASSWD_ID, {}, profile=profile)
else:
self.showDialog(message, fullname, 'error')
self.showDialog(message, fullname, "error")
self.bridge.connect(profile, callback=callback, errback=errback)
def plug_profiles(self, profiles):
@ -527,7 +598,7 @@ class QuickApp(object):
"""called when the connection is closed"""
log.debug(_("Disconnected"))
self.contact_lists[profile].disconnect()
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, '', profile=profile)
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "", profile=profile)
def actionNewHandler(self, action_data, id_, security_limit, profile):
self.actionManager(action_data, user_action=False, profile=profile)
@ -537,10 +608,23 @@ class QuickApp(object):
groups = list(groups)
self.contact_lists[profile].setContact(entity, groups, attributes, in_roster=True)
def messageNewHandler(self, uid, timestamp, from_jid_s, to_jid_s, msg, subject, type_, extra, profile):
def messageNewHandler(
self, uid, timestamp, from_jid_s, to_jid_s, msg, subject, type_, extra, profile
):
from_jid = jid.JID(from_jid_s)
to_jid = jid.JID(to_jid_s)
if not self.trigger.point("messageNewTrigger", uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile=profile):
if not self.trigger.point(
"messageNewTrigger",
uid,
timestamp,
from_jid,
to_jid,
msg,
subject,
type_,
extra,
profile=profile,
):
return
from_me = from_jid.bare == self.profiles[profile].whoami.bare
@ -550,66 +634,137 @@ class QuickApp(object):
# we avoid resource locking, but we must keep resource for private MUC messages
target = target.bare
# we want to be sure to have at least one QuickChat instance
self.widgets.getOrCreateWidget(quick_chat.QuickChat, target, type_=C.CHAT_ONE2ONE, on_new_widget=None, profile=profile)
self.widgets.getOrCreateWidget(
quick_chat.QuickChat,
target,
type_=C.CHAT_ONE2ONE,
on_new_widget=None,
profile=profile,
)
if not from_jid in contact_list and from_jid.bare != self.profiles[profile].whoami.bare:
#XXX: needed to show entities which haven't sent any
if (
not from_jid in contact_list
and from_jid.bare != self.profiles[profile].whoami.bare
):
# XXX: needed to show entities which haven't sent any
# presence information and which are not in roster
contact_list.setContact(from_jid)
# we dispatch the message in the widgets
for widget in self.widgets.getWidgets(quick_chat.QuickChat, target=target, profiles=(profile,)):
widget.messageNew(uid, timestamp, from_jid, target, msg, subject, type_, extra, profile)
for widget in self.widgets.getWidgets(
quick_chat.QuickChat, target=target, profiles=(profile,)
):
widget.messageNew(
uid, timestamp, from_jid, target, msg, subject, type_, extra, profile
)
def messageStateHandler(self, uid, status, profile):
for widget in self.widgets.getWidgets(quick_chat.QuickChat, profiles=(profile,)):
widget.onMessageState(uid, status, profile)
def messageSend(self, to_jid, message, subject=None, mess_type="auto", extra=None, callback=None, errback=None, profile_key=C.PROF_KEY_NONE):
def messageSend(
self,
to_jid,
message,
subject=None,
mess_type="auto",
extra=None,
callback=None,
errback=None,
profile_key=C.PROF_KEY_NONE,
):
if subject is None:
subject = {}
if extra is None:
extra = {}
if callback is None:
callback = lambda dummy=None: None # FIXME: optional argument is here because pyjamas doesn't support callback without arg with json proxy
callback = (
lambda dummy=None: None
) # FIXME: optional argument is here because pyjamas doesn't support callback without arg with json proxy
if errback is None:
errback = lambda failure: self.showDialog(failure.fullname, failure.message, "error")
errback = lambda failure: self.showDialog(
failure.fullname, failure.message, "error"
)
if not self.trigger.point("messageSendTrigger", to_jid, message, subject, mess_type, extra, callback, errback, profile_key=profile_key):
if not self.trigger.point(
"messageSendTrigger",
to_jid,
message,
subject,
mess_type,
extra,
callback,
errback,
profile_key=profile_key,
):
return
self.bridge.messageSend(unicode(to_jid), message, subject, mess_type, extra, profile_key, callback=callback, errback=errback)
self.bridge.messageSend(
unicode(to_jid),
message,
subject,
mess_type,
extra,
profile_key,
callback=callback,
errback=errback,
)
def setPresenceStatus(self, show='', status=None, profile=C.PROF_KEY_NONE):
def setPresenceStatus(self, show="", status=None, profile=C.PROF_KEY_NONE):
raise NotImplementedError
def presenceUpdateHandler(self, entity_s, show, priority, statuses, profile):
log.debug(_(u"presence update for %(entity)s (show=%(show)s, priority=%(priority)s, statuses=%(statuses)s) [profile:%(profile)s]")
% {'entity': entity_s, C.PRESENCE_SHOW: show, C.PRESENCE_PRIORITY: priority, C.PRESENCE_STATUSES: statuses, 'profile': profile})
log.debug(
_(
u"presence update for %(entity)s (show=%(show)s, priority=%(priority)s, statuses=%(statuses)s) [profile:%(profile)s]"
)
% {
"entity": entity_s,
C.PRESENCE_SHOW: show,
C.PRESENCE_PRIORITY: priority,
C.PRESENCE_STATUSES: statuses,
"profile": profile,
}
)
entity = jid.JID(entity_s)
if entity == self.profiles[profile].whoami:
if show == C.PRESENCE_UNAVAILABLE:
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, '', profile=profile)
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "", profile=profile)
else:
# FIXME: try to retrieve user language status before fallback to default
status = statuses.get(C.PRESENCE_STATUSES_DEFAULT, None)
self.setPresenceStatus(show, status, profile=profile)
return
self.callListeners('presence', entity, show, priority, statuses, profile=profile)
self.callListeners("presence", entity, show, priority, statuses, profile=profile)
def mucRoomJoinedHandler(self, room_jid_s, occupants, user_nick, subject, profile):
"""Called when a MUC room is joined"""
log.debug(u"Room [{room_jid}] joined by {profile}, users presents:{users}".format(room_jid=room_jid_s, profile=profile, users=occupants.keys()))
log.debug(
u"Room [{room_jid}] joined by {profile}, users presents:{users}".format(
room_jid=room_jid_s, profile=profile, users=occupants.keys()
)
)
room_jid = jid.JID(room_jid_s)
self.widgets.getOrCreateWidget(quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, nick=user_nick, occupants=occupants, subject=subject, profile=profile)
self.widgets.getOrCreateWidget(
quick_chat.QuickChat,
room_jid,
type_=C.CHAT_GROUP,
nick=user_nick,
occupants=occupants,
subject=subject,
profile=profile,
)
self.contact_lists[profile].setSpecial(room_jid, C.CONTACT_SPECIAL_GROUP)
# chat_widget.update()
def mucRoomLeftHandler(self, room_jid_s, profile):
"""Called when a MUC room is left"""
log.debug(u"Room [%(room_jid)s] left by %(profile)s" % {'room_jid': room_jid_s, 'profile': profile})
log.debug(
u"Room [%(room_jid)s] left by %(profile)s"
% {"room_jid": room_jid_s, "profile": profile}
)
room_jid = jid.JID(room_jid_s)
chat_widget = self.widgets.getWidget(quick_chat.QuickChat, room_jid, profile)
if chat_widget:
@ -619,16 +774,26 @@ class QuickApp(object):
def mucRoomUserChangedNickHandler(self, room_jid_s, old_nick, new_nick, profile):
"""Called when an user joined a MUC room"""
room_jid = jid.JID(room_jid_s)
chat_widget = self.widgets.getOrCreateWidget(quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile)
chat_widget = self.widgets.getOrCreateWidget(
quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile
)
chat_widget.changeUserNick(old_nick, new_nick)
log.debug(u"user [%(old_nick)s] is now known as [%(new_nick)s] in room [%(room_jid)s]" % {'old_nick': old_nick, 'new_nick': new_nick, 'room_jid': room_jid})
log.debug(
u"user [%(old_nick)s] is now known as [%(new_nick)s] in room [%(room_jid)s]"
% {"old_nick": old_nick, "new_nick": new_nick, "room_jid": room_jid}
)
def mucRoomNewSubjectHandler(self, room_jid_s, subject, profile):
"""Called when subject of MUC room change"""
room_jid = jid.JID(room_jid_s)
chat_widget = self.widgets.getOrCreateWidget(quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile)
chat_widget = self.widgets.getOrCreateWidget(
quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile
)
chat_widget.setSubject(subject)
log.debug(u"new subject for room [%(room_jid)s]: %(subject)s" % {'room_jid': room_jid, "subject": subject})
log.debug(
u"new subject for room [%(room_jid)s]: %(subject)s"
% {"room_jid": room_jid, "subject": subject}
)
def chatStateReceivedHandler(self, from_jid_s, state, profile):
"""Called when a new chat state (XEP-0085) is received.
@ -641,7 +806,17 @@ class QuickApp(object):
for widget in self.widgets.getWidgets(quick_chat.QuickChat, profiles=(profile,)):
widget.onChatState(from_jid, state, profile)
def notify(self, type_, entity=None, message=None, subject=None, callback=None, cb_args=None, widget=None, profile=C.PROF_KEY_NONE):
def notify(
self,
type_,
entity=None,
message=None,
subject=None,
callback=None,
cb_args=None,
widget=None,
profile=C.PROF_KEY_NONE,
):
"""Trigger an event notification
@param type_(unicode): notifation kind,
@ -656,22 +831,22 @@ class QuickApp(object):
"""
assert type_ in C.NOTIFY_ALL
notif_dict = self.profiles[profile].notifications
key = '' if entity is None else entity.bare
key = "" if entity is None else entity.bare
type_notifs = notif_dict.setdefault(key, {}).setdefault(type_, [])
notif_data = {
'id': self._notif_id,
'time': time.time(),
'entity': entity,
'callback': callback,
'cb_args': cb_args,
'message': message,
'subject': subject,
}
"id": self._notif_id,
"time": time.time(),
"entity": entity,
"callback": callback,
"cb_args": cb_args,
"message": message,
"subject": subject,
}
if widget is not None:
notif_data[widget] = widget
type_notifs.append(notif_data)
self._notifications[self._notif_id] = notif_data
self.callListeners('notification', entity, notif_data, profile=profile)
self.callListeners("notification", entity, notif_data, profile=profile)
def getNotifs(self, entity=None, type_=None, exact_jid=None, profile=C.PROF_KEY_NONE):
"""return notifications for given entity
@ -696,7 +871,7 @@ class QuickApp(object):
exact_jid = False
else:
if entity is None:
key = ''
key = ""
exact_jid = False
else:
key = entity.bare
@ -713,7 +888,7 @@ class QuickApp(object):
for notifs in type_notifs:
for notif in notifs:
if exact_jid and notif['entity'] != entity:
if exact_jid and notif["entity"] != entity:
continue
yield notif
@ -727,7 +902,7 @@ class QuickApp(object):
@return (list[dict]): list of notifications
"""
notif_dict = self.profiles[profile].notifications
key = '' if entity is None else entity.bare
key = "" if entity is None else entity.bare
try:
if type_ is None:
del notif_dict[key]
@ -735,7 +910,7 @@ class QuickApp(object):
del notif_dict[key][type_]
except KeyError:
return
self.callListeners('notificationsClear', entity, type_, profile=profile)
self.callListeners("notificationsClear", entity, type_, profile=profile)
def psEventHandler(self, category, service_s, node, event_type, data, profile):
"""Called when a PubSub event is received.
@ -750,23 +925,35 @@ class QuickApp(object):
if category == C.PS_MICROBLOG and self.MB_HANDLER:
if event_type == C.PS_PUBLISH:
if not 'content' in data:
if not "content" in data:
log.warning("No content found in microblog data")
return
_groups = set(data_format.dict2iter('group', data)) or None # FIXME: check if [] make sense (instead of None)
_groups = (
set(data_format.dict2iter("group", data)) or None
) # FIXME: check if [] make sense (instead of None)
for wid in self.widgets.getWidgets(quick_blog.QuickBlog):
wid.addEntryIfAccepted(service_s, node, data, _groups, profile)
try:
comments_node, comments_service = data['comments_node'], data['comments_service']
comments_node, comments_service = (
data["comments_node"],
data["comments_service"],
)
except KeyError:
pass
else:
self.bridge.mbGet(comments_service, comments_node, C.NO_LIMIT, [], {"subscribe":C.BOOL_TRUE}, profile=profile)
self.bridge.mbGet(
comments_service,
comments_node,
C.NO_LIMIT,
[],
{"subscribe": C.BOOL_TRUE},
profile=profile,
)
elif event_type == C.PS_RETRACT:
for wid in self.widgets.getWidgets(quick_blog.QuickBlog):
wid.deleteEntryIfPresent(service_s, node, data['id'], profile)
wid.deleteEntryIfPresent(service_s, node, data["id"], profile)
pass
else:
log.warning("Unmanaged PubSub event type {}".format(event_type))
@ -776,11 +963,11 @@ class QuickApp(object):
def progressFinishedHandler(self, pid, metadata, profile):
log.info(u"Progress {} finished".format(pid))
self.callListeners('progressFinished', pid, metadata, profile=profile)
self.callListeners("progressFinished", pid, metadata, profile=profile)
def progressErrorHandler(self, pid, err_msg, profile):
log.warning(u"Progress {pid} error: {err_msg}".format(pid=pid, err_msg=err_msg))
self.callListeners('progressError', pid, err_msg, profile=profile)
self.callListeners("progressError", pid, err_msg, profile=profile)
def _subscribe_cb(self, answer, data):
entity, profile = data
@ -793,23 +980,34 @@ class QuickApp(object):
if type == "subscribed":
# this is a subscription confirmation, we just have to inform user
# TODO: call self.getEntityMBlog to add the new contact blogs
self.showDialog(_(u"The contact {contact} has accepted your subscription")
.format(contact=entity.bare), _(u'Subscription confirmation'))
self.showDialog(
_(u"The contact {contact} has accepted your subscription").format(
contact=entity.bare
),
_(u"Subscription confirmation"),
)
elif type == "unsubscribed":
# this is a subscription refusal, we just have to inform user
self.showDialog(_(u"The contact {contact} has refused your subscription")
.format(contact=entity.bare),
_(u'Subscription refusal'),
'error')
self.showDialog(
_(u"The contact {contact} has refused your subscription").format(
contact=entity.bare
),
_(u"Subscription refusal"),
"error",
)
elif type == "subscribe":
# this is a subscriptionn request, we have to ask for user confirmation
# TODO: use sat.stdui.ui_contact_list to display the groups selector
self.showDialog(_(u"The contact {contact} wants to subscribe to your presence"
u".\nDo you accept ?").format(contact=entity.bare),
_('Subscription confirmation'),
'yes/no',
answer_cb=self._subscribe_cb,
answer_data=(entity, profile))
self.showDialog(
_(
u"The contact {contact} wants to subscribe to your presence"
u".\nDo you accept ?"
).format(contact=entity.bare),
_("Subscription confirmation"),
"yes/no",
answer_cb=self._subscribe_cb,
answer_data=(entity, profile),
)
def showDialog(self, message, title, type="info", answer_cb=None, answer_data=None):
"""Show a dialog to user
@ -832,7 +1030,7 @@ class QuickApp(object):
def showAlert(self, message):
# FIXME: doesn't seems used anymore, to remove?
pass #FIXME
pass # FIXME
def dialogFailure(self, failure):
log.warning(u"Failure: {}".format(failure))
@ -849,13 +1047,16 @@ class QuickApp(object):
raise NotImplementedError
def paramUpdateHandler(self, name, value, namespace, profile):
log.debug(_(u"param update: [%(namespace)s] %(name)s = %(value)s") % {'namespace': namespace, 'name': name, 'value': value})
log.debug(
_(u"param update: [%(namespace)s] %(name)s = %(value)s")
% {"namespace": namespace, "name": name, "value": value}
)
if (namespace, name) == ("Connection", "JabberID"):
log.debug(_(u"Changing JID to %s") % value)
self.profiles[profile].whoami = jid.JID(value)
elif (namespace, name) == ('General', C.SHOW_OFFLINE_CONTACTS):
elif (namespace, name) == ("General", C.SHOW_OFFLINE_CONTACTS):
self.contact_lists[profile].showOfflineContacts(C.bool(value))
elif (namespace, name) == ('General', C.SHOW_EMPTY_GROUPS):
elif (namespace, name) == ("General", C.SHOW_EMPTY_GROUPS):
self.contact_lists[profile].showEmptyGroups(C.bool(value))
def contactDeletedHandler(self, jid_s, profile):
@ -866,13 +1067,20 @@ class QuickApp(object):
entity = jid.JID(entity_s)
if key == "nick": # this is the roster nick, not the MUC nick
if entity in self.contact_lists[profile]:
self.contact_lists[profile].setCache(entity, 'nick', value)
self.callListeners('nick', entity, value, profile=profile)
self.contact_lists[profile].setCache(entity, "nick", value)
self.callListeners("nick", entity, value, profile=profile)
elif key == "avatar" and self.AVATARS_HANDLER:
if value and entity in self.contact_lists[profile]:
self.getAvatar(entity, ignore_cache=True, profile=profile)
def actionManager(self, action_data, callback=None, ui_show_cb=None, user_action=True, profile=C.PROF_KEY_NONE):
def actionManager(
self,
action_data,
callback=None,
ui_show_cb=None,
user_action=True,
profile=C.PROF_KEY_NONE,
):
"""Handle backend action
@param action_data(dict): action dict as sent by launchAction or returned by an UI action
@ -882,29 +1090,40 @@ class QuickApp(object):
else the action come from backend direclty (i.e. actionNew)
"""
try:
xmlui = action_data.pop('xmlui')
xmlui = action_data.pop("xmlui")
except KeyError:
pass
else:
ui = self.xmlui.create(self, xml_data=xmlui, flags=("FROM_BACKEND",) if not user_action else None, callback=callback, profile=profile)
ui = self.xmlui.create(
self,
xml_data=xmlui,
flags=("FROM_BACKEND",) if not user_action else None,
callback=callback,
profile=profile,
)
if ui_show_cb is None:
ui.show()
else:
ui_show_cb(ui)
try:
progress_id = action_data.pop('progress')
progress_id = action_data.pop("progress")
except KeyError:
pass
else:
self.progressIdHandler(progress_id, profile)
# we ignore metadata
action_data = {k:v for k,v in action_data.iteritems() if not k.startswith("meta_")}
action_data = {
k: v for k, v in action_data.iteritems() if not k.startswith("meta_")
}
if action_data:
raise exceptions.DataError(u"Not all keys in action_data are managed ({keys})".format(keys=', '.join(action_data.keys())))
raise exceptions.DataError(
u"Not all keys in action_data are managed ({keys})".format(
keys=", ".join(action_data.keys())
)
)
def _actionCb(self, data, callback, callback_id, profile):
if callback is None:
@ -912,7 +1131,9 @@ class QuickApp(object):
else:
callback(data=data, cb_id=callback_id, profile=profile)
def launchAction(self, callback_id, data=None, callback=None, profile=C.PROF_KEY_NONE):
def launchAction(
self, callback_id, data=None, callback=None, profile=C.PROF_KEY_NONE
):
"""Launch a dynamic action
@param callback_id: id of the action to launch
@ -929,9 +1150,19 @@ class QuickApp(object):
if data is None:
data = dict()
action_cb = lambda data: self._actionCb(data, callback, callback_id, profile)
self.bridge.launchAction(callback_id, data, profile, callback=action_cb, errback=self.dialogFailure)
self.bridge.launchAction(
callback_id, data, profile, callback=action_cb, errback=self.dialogFailure
)
def launchMenu(self, menu_type, path, data=None, callback=None, security_limit=C.SECURITY_LIMIT_MAX, profile=C.PROF_KEY_NONE):
def launchMenu(
self,
menu_type,
path,
data=None,
callback=None,
security_limit=C.SECURITY_LIMIT_MAX,
profile=C.PROF_KEY_NONE,
):
"""Launch a menu manually
@param menu_type(unicode): type of the menu to launch
@ -948,19 +1179,36 @@ class QuickApp(object):
"""
if data is None:
data = dict()
action_cb = lambda data: self._actionCb(data, callback, (menu_type, path), profile)
self.bridge.menuLaunch(menu_type, path, data, security_limit, profile, callback=action_cb, errback=self.dialogFailure)
action_cb = lambda data: self._actionCb(
data, callback, (menu_type, path), profile
)
self.bridge.menuLaunch(
menu_type,
path,
data,
security_limit,
profile,
callback=action_cb,
errback=self.dialogFailure,
)
def _avatarGetCb(self, avatar_path, entity, contact_list, profile):
path = avatar_path or self.getDefaultAvatar(entity)
contact_list.setCache(entity, "avatar", path)
self.callListeners('avatar', entity, path, profile=profile)
self.callListeners("avatar", entity, path, profile=profile)
def _avatarGetEb(self, failure, entity, contact_list):
log.warning(u"Can't get avatar: {}".format(failure))
contact_list.setCache(entity, "avatar", self.getDefaultAvatar(entity))
def getAvatar(self, entity, cache_only=True, hash_only=False, ignore_cache=False, profile=C.PROF_KEY_NONE):
def getAvatar(
self,
entity,
cache_only=True,
hash_only=False,
ignore_cache=False,
profile=C.PROF_KEY_NONE,
):
"""return avatar path for an entity
@param entity(jid.JID): entity to get avatar from
@ -982,8 +1230,11 @@ class QuickApp(object):
cache_only,
hash_only,
profile=profile,
callback=lambda path: self._avatarGetCb(path, entity, contact_list, profile),
errback=lambda failure: self._avatarGetEb(failure, entity, contact_list))
callback=lambda path: self._avatarGetCb(
path, entity, contact_list, profile
),
errback=lambda failure: self._avatarGetEb(failure, entity, contact_list),
)
# we set avatar to empty string to avoid requesting several time the same avatar
# while we are waiting for avatarGet result
contact_list.setCache(entity, "avatar", "")
@ -999,7 +1250,7 @@ class QuickApp(object):
def disconnect(self, profile):
log.info("disconnecting")
self.callListeners('disconnect', profile=profile)
self.callListeners("disconnect", profile=profile)
self.bridge.disconnect(profile)
def onExit(self):
@ -1007,7 +1258,7 @@ class QuickApp(object):
to_unplug = []
for profile, profile_manager in self.profiles.iteritems():
if profile_manager.connected and profile_manager.autodisconnect:
#The user wants autodisconnection
# The user wants autodisconnection
self.disconnect(profile)
to_unplug.append(profile)
for profile in to_unplug:

View file

@ -19,6 +19,7 @@
# from sat.core.i18n import _, D_
from sat.core.log import getLogger
log = getLogger(__name__)
@ -29,8 +30,11 @@ from sat.tools.common import data_format
try:
# FIXME: to be removed when an acceptable solution is here
unicode('') # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
unicode("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
unicode = str
ENTRY_CLS = None
@ -45,42 +49,46 @@ class Item(object):
@param data(dict): microblog data as return by bridge methods
if data values are not defined, set default values
"""
self.id = data['id']
self.title = data.get('title')
self.id = data["id"]
self.title = data.get("title")
self.title_rich = None
self.title_xhtml = data.get('title_xhtml')
self.tags = list(data_format.dict2iter('tag', data))
self.content = data.get('content')
self.title_xhtml = data.get("title_xhtml")
self.tags = list(data_format.dict2iter("tag", data))
self.content = data.get("content")
self.content_rich = None
self.content_xhtml = data.get('content_xhtml')
self.author = data['author']
self.content_xhtml = data.get("content_xhtml")
self.author = data["author"]
try:
author_jid = data['author_jid']
author_jid = data["author_jid"]
self.author_jid = jid.JID(author_jid) if author_jid else None
except KeyError:
self.author_jid = None
try:
self.author_verified = C.bool(data['author_jid_verified'])
self.author_verified = C.bool(data["author_jid_verified"])
except KeyError:
self.author_verified = False
try:
self.updated = float(data['updated']) # XXX: int doesn't work here (pyjamas bug)
self.updated = float(
data["updated"]
) # XXX: int doesn't work here (pyjamas bug)
except KeyError:
self.updated = None
try:
self.published = float(data['published']) # XXX: int doesn't work here (pyjamas bug)
self.published = float(
data["published"]
) # XXX: int doesn't work here (pyjamas bug)
except KeyError:
self.published = None
self.comments = data.get('comments')
self.comments = data.get("comments")
try:
self.comments_service = jid.JID(data['comments_service'])
self.comments_service = jid.JID(data["comments_service"])
except KeyError:
self.comments_service = None
self.comments_node = data.get('comments_node')
self.comments_node = data.get("comments_node")
# def loadComments(self):
# """Load all the comments"""
@ -140,7 +148,16 @@ class EntriesManager(object):
for item, comments in items:
self.addEntry(item, comments, service=service, node=node, with_update=False)
def addEntry(self, item=None, comments=None, service=None, node=None, with_update=True, editable=False, edit_entry=False):
def addEntry(
self,
item=None,
comments=None,
service=None,
node=None,
with_update=True,
editable=False,
edit_entry=False,
):
"""Add a microblog entry
@param editable (bool): True if the entry can be modified
@ -178,7 +195,9 @@ class Entry(EntriesManager):
"""Graphical representation of an Item
This class must be overriden by frontends"""
def __init__(self, manager, item_data=None, comments_data=None, service=None, node=None):
def __init__(
self, manager, item_data=None, comments_data=None, service=None, node=None
):
"""
@param blog(QuickBlog): the parent QuickBlog
@param manager(EntriesManager): the parent EntriesManager
@ -194,7 +213,7 @@ class Entry(EntriesManager):
self.blog.id2entries[self.item.id] = self
if self.item.comments:
node_tuple = (self.item.comments_service, self.item.comments_node)
self.blog.node2entries.setdefault(node_tuple,[]).append(self)
self.blog.node2entries.setdefault(node_tuple, []).append(self)
def reset(self, item_data):
"""Reset the entry with given data
@ -205,17 +224,20 @@ class Entry(EntriesManager):
"""
if item_data is None:
self.new = True
item_data = {'id': None,
# TODO: find a best author value
'author': self.blog.host.whoami.node
}
item_data = {
"id": None,
# TODO: find a best author value
"author": self.blog.host.whoami.node,
}
else:
self.new = False
self.item = Item(item_data)
self.author_jid = self.blog.host.whoami.bare if self.new else self.item.author_jid
self.author_jid = self.blog.host.whoami.bare if self.new else self.item.author_jid
if self.author_jid is None and self.service and self.service.node:
self.author_jid = self.service
self.mode = C.ENTRY_MODE_TEXT if self.item.content_xhtml is None else C.ENTRY_MODE_XHTML
self.mode = (
C.ENTRY_MODE_TEXT if self.item.content_xhtml is None else C.ENTRY_MODE_XHTML
)
def refresh(self):
"""Refresh the display when data have been modified"""
@ -226,7 +248,7 @@ class Entry(EntriesManager):
@param editable(bool): True if the entry can be edited
"""
#XXX: we don't use @property as property setter doesn't play well with pyjamas
# XXX: we don't use @property as property setter doesn't play well with pyjamas
raise NotImplementedError
def addComments(self, comments_data):
@ -249,7 +271,7 @@ class Entry(EntriesManager):
# keys to keep other than content*, title* and tag*
# FIXME: see how to avoid comments node hijacking (someone could bind his post to another post's comments node)
keys_to_keep = ('id', 'comments', 'author', 'author_jid', 'published')
keys_to_keep = ("id", "comments", "author", "author_jid", "published")
mb_data = {}
for key in keys_to_keep:
@ -257,14 +279,14 @@ class Entry(EntriesManager):
if value is not None:
mb_data[key] = unicode(value)
for prefix in ('content', 'title'):
for suffix in ('', '_rich', '_xhtml'):
name = '{}{}'.format(prefix, suffix)
for prefix in ("content", "title"):
for suffix in ("", "_rich", "_xhtml"):
name = "{}{}".format(prefix, suffix)
value = getattr(self.item, name)
if value is not None:
mb_data[name] = value
data_format.iter2dict('tag', self.item.tags, mb_data)
data_format.iter2dict("tag", self.item.tags, mb_data)
if self.blog.new_message_target not in (C.PUBLIC, C.GROUP):
raise NotImplementedError
@ -273,13 +295,14 @@ class Entry(EntriesManager):
mb_data["allow_comments"] = C.BOOL_TRUE
if self.blog.new_message_target == C.GROUP:
data_format.iter2dict('group', self.blog.targets, mb_data)
data_format.iter2dict("group", self.blog.targets, mb_data)
self.blog.host.bridge.mbSend(
unicode(self.service or ''),
self.node or '',
unicode(self.service or ""),
self.node or "",
mb_data,
profile=self.blog.profile)
profile=self.blog.profile,
)
def delete(self):
"""Remove this Entry from parent manager
@ -288,7 +311,7 @@ class Entry(EntriesManager):
all children entries will be recursively removed too
"""
# XXX: named delete and not remove to avoid conflict with pyjamas
log.debug(u"deleting entry {}".format('EDIT ENTRY' if self.new else self.item.id))
log.debug(u"deleting entry {}".format("EDIT ENTRY" if self.new else self.item.id))
for child in self.entries:
child.delete()
try:
@ -303,8 +326,7 @@ class Entry(EntriesManager):
# in QuickBlog's dictionary
del self.blog.id2entries[self.item.id]
if self.item.comments:
comments_tuple = (self.item.comments_service,
self.item.comments_node)
comments_tuple = (self.item.comments_service, self.item.comments_node)
other_entries = self.blog.node2entries[comments_tuple].remove(self)
if not other_entries:
del self.blog.node2entries[comments_tuple]
@ -316,12 +338,20 @@ class Entry(EntriesManager):
"""
# TODO: manage several comments nodes case.
if self.item.comments:
self.blog.host.bridge.psNodeDelete(unicode(self.item.comments_service) or "", self.item.comments_node, profile=self.blog.profile)
self.blog.host.bridge.mbRetract(unicode(self.service or ""), self.node or "", self.item.id, profile=self.blog.profile)
self.blog.host.bridge.psNodeDelete(
unicode(self.item.comments_service) or "",
self.item.comments_node,
profile=self.blog.profile,
)
self.blog.host.bridge.mbRetract(
unicode(self.service or ""),
self.node or "",
self.item.id,
profile=self.blog.profile,
)
class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
def __init__(self, host, targets, profiles=None):
"""Panel used to show microblog
@ -330,12 +360,12 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
to know where to send new messages.
"""
EntriesManager.__init__(self, None)
self.id2entries = {} # used to find an entry with it's item id
# must be kept up-to-date by Entry
self.node2entries = {} # same as above, values are lists in case of
# two entries link to the same comments node
self.id2entries = {} # used to find an entry with it's item id
# must be kept up-to-date by Entry
self.node2entries = {} # same as above, values are lists in case of
# two entries link to the same comments node
if not targets:
targets = () # XXX: we use empty tuple instead of None to workaround a pyjamas bug
targets = () # XXX: we use empty tuple instead of None to workaround a pyjamas bug
quick_widgets.QuickWidget.__init__(self, host, targets, C.PROF_KEY_NONE)
self._targets_type = C.ALL
else:
@ -356,11 +386,17 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
raise ValueError("Unkown targets type")
def __str__(self):
return u"Blog Widget [target: {}, profile: {}]".format(', '.join(self.targets), self.profile)
return u"Blog Widget [target: {}, profile: {}]".format(
", ".join(self.targets), self.profile
)
def _getResultsCb(self, data, rt_session):
remaining, results = data
log.debug("Got {got_len} results, {rem_len} remaining".format(got_len=len(results), rem_len=remaining))
log.debug(
"Got {got_len} results, {rem_len} remaining".format(
got_len=len(results), rem_len=remaining
)
)
for result in results:
service, node, failure, items, metadata = result
if not failure:
@ -378,22 +414,46 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
@param rt_session(str): session id as returned by mbGetFromMany
"""
self.host.bridge.mbGetFromManyWithCommentsRTResult(rt_session, profile=self.profile,
callback=lambda data:self._getResultsCb(data, rt_session),
errback=self._getResultsEb)
self.host.bridge.mbGetFromManyWithCommentsRTResult(
rt_session,
profile=self.profile,
callback=lambda data: self._getResultsCb(data, rt_session),
errback=self._getResultsEb,
)
def getAll(self):
"""Get all (micro)blogs from self.targets"""
def gotSession(rt_session):
self._getResults(rt_session)
if self._targets_type in (C.ALL, C.GROUP):
targets = tuple(self.targets) if self._targets_type is C.GROUP else ()
self.host.bridge.mbGetFromManyWithComments(self._targets_type, targets, 10, 10, {}, {"subscribe":C.BOOL_TRUE}, profile=self.profile, callback=gotSession)
self.host.bridge.mbGetFromManyWithComments(
self._targets_type,
targets,
10,
10,
{},
{"subscribe": C.BOOL_TRUE},
profile=self.profile,
callback=gotSession,
)
own_pep = self.host.whoami.bare
self.host.bridge.mbGetFromManyWithComments(C.JID, (unicode(own_pep),), 10, 10, {}, {}, profile=self.profile, callback=gotSession)
self.host.bridge.mbGetFromManyWithComments(
C.JID,
(unicode(own_pep),),
10,
10,
{},
{},
profile=self.profile,
callback=gotSession,
)
else:
raise NotImplementedError(u'{} target type is not managed'.format(self._targets_type))
raise NotImplementedError(
u"{} target type is not managed".format(self._targets_type)
)
def isJidAccepted(self, jid_):
"""Tell if a jid is actepted and must be shown in this panel
@ -403,7 +463,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
"""
if self._targets_type == C.ALL:
return True
assert self._targets_type is C.GROUP # we don't manage other types for now
assert self._targets_type is C.GROUP # we don't manage other types for now
for group in self.targets:
if self.host.contact_lists[self.profile].isEntityInGroup(jid_, group):
return True
@ -422,7 +482,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
@param profile: %(doc_profile)s
"""
try:
entry = self.id2entries[mb_data['id']]
entry = self.id2entries[mb_data["id"]]
except KeyError:
# The entry is new
try:
@ -430,9 +490,14 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
except:
# The node is unknown,
# we need to check that we can accept the entry
if (self.isJidAccepted(service)
or (groups is None and service == self.host.profiles[self.profile].whoami.bare)
or (groups and groups.intersection(self.targets))):
if (
self.isJidAccepted(service)
or (
groups is None
and service == self.host.profiles[self.profile].whoami.bare
)
or (groups and groups.intersection(self.targets))
):
self.addEntry(mb_data, service=service, node=node)
else:
# the entry is a comment in a known node

View file

@ -19,6 +19,7 @@
from sat.core.i18n import _
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from sat_frontends.quick_frontend import quick_widgets
@ -26,31 +27,48 @@ from sat_frontends.quick_frontend.constants import Const as C
from collections import OrderedDict
from sat_frontends.tools import jid
import time
try:
from locale import getlocale
except ImportError:
# FIXME: pyjamas workaround
getlocale = lambda x: (None, 'utf-8')
getlocale = lambda x: (None, "utf-8")
ROOM_USER_JOINED = 'ROOM_USER_JOINED'
ROOM_USER_LEFT = 'ROOM_USER_LEFT'
ROOM_USER_JOINED = "ROOM_USER_JOINED"
ROOM_USER_LEFT = "ROOM_USER_LEFT"
ROOM_USER_MOVED = (ROOM_USER_JOINED, ROOM_USER_LEFT)
# from datetime import datetime
try:
# FIXME: to be removed when an acceptable solution is here
unicode('') # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
unicode("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
unicode = str
# FIXME: day_format need to be settable (i18n)
class Message(object):
"""Message metadata"""
def __init__(self, parent, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile):
def __init__(
self,
parent,
uid,
timestamp,
from_jid,
to_jid,
msg,
subject,
type_,
extra,
profile,
):
self.parent = parent
self.profile = profile
self.uid = uid
@ -64,7 +82,11 @@ class Message(object):
self.nick = self.getNick(from_jid)
self._status = None
# own_mess is True if message was sent by profile's jid
self.own_mess = (from_jid.resource == self.parent.nick) if self.parent.type == C.CHAT_GROUP else (from_jid.bare == self.host.profiles[profile].whoami.bare)
self.own_mess = (
(from_jid.resource == self.parent.nick)
if self.parent.type == C.CHAT_GROUP
else (from_jid.bare == self.host.profiles[profile].whoami.bare)
)
# is user mentioned here ?
if self.parent.type == C.CHAT_GROUP and not self.own_mess:
for m in msg.itervalues():
@ -80,7 +102,7 @@ class Message(object):
@property
def info_type(self):
return self.extra.get('info_type')
return self.extra.get("info_type")
@property
def mention(self):
@ -92,7 +114,7 @@ class Message(object):
@property
def history(self):
"""True if message come from history"""
return self.extra.get('history', False)
return self.extra.get("history", False)
@property
def main_message(self):
@ -101,8 +123,8 @@ class Message(object):
self.selected_lang = self.parent.lang
return self.message[self.parent.lang]
try:
self.selected_lang = ''
return self.message['']
self.selected_lang = ""
return self.message[""]
except KeyError:
try:
lang, mess = self.message.iteritems().next()
@ -110,24 +132,23 @@ class Message(object):
return mess
except StopIteration:
log.error(u"Can't find message for uid {}".format(self.uid))
return ''
return ""
@property
def main_message_xhtml(self):
"""rich message"""
xhtml = {k:v for k,v in self.extra.iteritems() if 'html' in k}
xhtml = {k: v for k, v in self.extra.iteritems() if "html" in k}
if xhtml:
# FIXME: we only return first found value for now
return next(xhtml.itervalues())
@property
def time_text(self):
"""Return timestamp in a nicely formatted way"""
# if the message was sent before today, we print the full date
timestamp = time.localtime(self.timestamp)
time_format = u"%c" if timestamp < self.parent.day_change else u"%H:%M"
return time.strftime(time_format, timestamp).decode(getlocale()[1] or 'utf-8')
return time.strftime(time_format, timestamp).decode(getlocale()[1] or "utf-8")
@property
def avatar(self):
@ -140,15 +161,22 @@ class Message(object):
contact_list = self.host.contact_lists[self.profile]
if self.type == C.MESS_TYPE_INFO and self.info_type in ROOM_USER_MOVED:
try:
return self.extra['user_nick']
return self.extra["user_nick"]
except KeyError:
log.error(u"extra data is missing user nick for uid {}".format(self.uid))
return ""
# FIXME: converted getSpecials to list for pyjamas
if self.parent.type == C.CHAT_GROUP or entity in list(contact_list.getSpecials(C.CONTACT_SPECIAL_GROUP)):
if self.parent.type == C.CHAT_GROUP or entity in list(
contact_list.getSpecials(C.CONTACT_SPECIAL_GROUP)
):
return entity.resource or ""
if entity.bare in contact_list:
return contact_list.getCache(entity, 'nick') or contact_list.getCache(entity, 'name') or entity.node or entity
return (
contact_list.getCache(entity, "nick")
or contact_list.getCache(entity, "name")
or entity.node
or entity
)
return entity.node or entity
@property
@ -178,7 +206,7 @@ class Message(object):
break
if me:
self.type = C.MESS_TYPE_INFO
self.extra['info_type'] = 'me'
self.extra["info_type"] = "me"
nick = self.nick
for lang, mess in self.message.iteritems():
self.message[lang] = u"* " + nick + mess[3:]
@ -190,10 +218,10 @@ class Occupant(object):
def __init__(self, parent, data, profile):
self.parent = parent
self.profile = profile
self.nick = data['nick']
self._entity = data.get('entity')
self.affiliation = data['affiliation']
self.role = data['role']
self.nick = data["nick"]
self._entity = data.get("entity")
self.affiliation = data["affiliation"]
self.role = data["role"]
self.widgets = set() # widgets linked to this occupant
self._state = None
@ -201,11 +229,11 @@ class Occupant(object):
def data(self):
"""reconstruct data dict from attributes"""
data = {}
data['nick'] = self.nick
data["nick"] = self.nick
if self._entity is not None:
data['entity'] = self._entity
data['affiliation'] = self.affiliation
data['role'] = self.role
data["entity"] = self._entity
data["affiliation"] = self.affiliation
data["role"] = self.role
return data
@property
@ -239,23 +267,34 @@ class Occupant(object):
class QuickChat(quick_widgets.QuickWidget):
visible_states = ['chat_state'] # FIXME: to be removed, used only in quick_games
visible_states = ["chat_state"] # FIXME: to be removed, used only in quick_games
def __init__(self, host, target, type_=C.CHAT_ONE2ONE, nick=None, occupants=None, subject=None, profiles=None):
def __init__(
self,
host,
target,
type_=C.CHAT_ONE2ONE,
nick=None,
occupants=None,
subject=None,
profiles=None,
):
"""
@param type_: can be C.CHAT_ONE2ONE for single conversation or C.CHAT_GROUP for chat à la IRC
"""
self.lang = '' # default language to use for messages
self.lang = "" # default language to use for messages
quick_widgets.QuickWidget.__init__(self, host, target, profiles=profiles)
self._locked = True # True when we are waiting for history/search
# messageNew signals are cached when locked
self._locked = True # True when we are waiting for history/search
# messageNew signals are cached when locked
self._cache = OrderedDict()
assert type_ in (C.CHAT_ONE2ONE, C.CHAT_GROUP)
self.current_target = target
self.type = type_
if type_ == C.CHAT_GROUP:
if target.resource:
raise exceptions.InternalError(u"a group chat entity can't have a resource")
raise exceptions.InternalError(
u"a group chat entity can't have a resource"
)
if nick is None:
raise exceptions.InternalError(u"nick must not be None for group chat")
@ -264,14 +303,26 @@ class QuickChat(quick_widgets.QuickWidget):
self.setOccupants(occupants)
else:
if occupants is not None or nick is not None:
raise exceptions.InternalError(u"only group chat can have occupants or nick")
raise exceptions.InternalError(
u"only group chat can have occupants or nick"
)
self.messages = OrderedDict() # key: uid, value: Message instance
self.games = {} # key=game name (unicode), value=instance of quick_games.RoomGame
self.subject = subject
lt = time.localtime()
self.day_change = (lt.tm_year, lt.tm_mon, lt.tm_mday, 0, 0, 0, lt.tm_wday, lt.tm_yday, lt.tm_isdst) # struct_time of day changing time
self.day_change = (
lt.tm_year,
lt.tm_mon,
lt.tm_mday,
0,
0,
0,
lt.tm_wday,
lt.tm_yday,
lt.tm_isdst,
) # struct_time of day changing time
if self.host.AVATARS_HANDLER:
self.host.addListener('avatar', self.onAvatar, profiles)
self.host.addListener("avatar", self.onAvatar, profiles)
def postInit(self):
"""Method to be called by frontend after widget is initialised
@ -284,7 +335,7 @@ class QuickChat(quick_widgets.QuickWidget):
def onDelete(self):
if self.host.AVATARS_HANDLER:
self.host.removeListener('avatar', self.onAvatar)
self.host.removeListener("avatar", self.onAvatar)
@property
def contact_list(self):
@ -293,7 +344,9 @@ class QuickChat(quick_widgets.QuickWidget):
## Widget management ##
def __str__(self):
return u"Chat Widget [target: {}, type: {}, profile: {}]".format(self.target, self.type, self.profile)
return u"Chat Widget [target: {}, type: {}, profile: {}]".format(
self.target, self.type, self.profile
)
@staticmethod
def getWidgetHash(target, profiles):
@ -311,16 +364,18 @@ class QuickChat(quick_widgets.QuickWidget):
def addTarget(self, target):
super(QuickChat, self).addTarget(target)
if target.resource:
self.current_target = target # FIXME: tmp, must use resource priority throught contactList instead
self.current_target = (
target
) # FIXME: tmp, must use resource priority throught contactList instead
def recreateArgs(self, args, kwargs):
"""copy important attribute for a new widget"""
kwargs['type_'] = self.type
kwargs["type_"] = self.type
if self.type == C.CHAT_GROUP:
kwargs['occupants'] = {o.nick: o.data for o in self.occupants.itervalues()}
kwargs['subject'] = self.subject
kwargs["occupants"] = {o.nick: o.data for o in self.occupants.itervalues()}
kwargs["subject"] = self.subject
try:
kwargs['nick'] = self.nick
kwargs["nick"] = self.nick
except AttributeError:
pass
@ -333,7 +388,14 @@ class QuickChat(quick_widgets.QuickWidget):
@param entity: full jid of the target
"""
return self.host.widgets.getOrCreateWidget(QuickChat, entity, type_=C.CHAT_ONE2ONE, force_hash=self.getPrivateHash(self.profile, entity), on_new_widget=self.onPrivateCreated, profile=self.profile) # we force hash to have a new widget, not this one again
return self.host.widgets.getOrCreateWidget(
QuickChat,
entity,
type_=C.CHAT_ONE2ONE,
force_hash=self.getPrivateHash(self.profile, entity),
on_new_widget=self.onPrivateCreated,
profile=self.profile,
) # we force hash to have a new widget, not this one again
@property
def target(self):
@ -347,25 +409,17 @@ class QuickChat(quick_widgets.QuickWidget):
"""set the whole list of occupants"""
assert len(self.occupants) == 0
for nick, data in occupants.iteritems():
self.occupants[nick] = Occupant(
self,
data,
self.profile
)
self.occupants[nick] = Occupant(self, data, self.profile)
def addUser(self, occupant_data):
"""Add user if it is not in the group list"""
occupant = Occupant(
self,
occupant_data,
self.profile
)
occupant = Occupant(self, occupant_data, self.profile)
self.occupants[occupant.nick] = occupant
return occupant
def removeUser(self, occupant_data):
"""Remove a user from the group list"""
nick = occupant_data['nick']
nick = occupant_data["nick"]
try:
occupant = self.occupants.pop(nick)
except KeyError:
@ -391,14 +445,17 @@ class QuickChat(quick_widgets.QuickWidget):
@return (bool): True if this Chat Widget manage this couple
"""
if self.type == C.CHAT_GROUP:
if mess_type in (C.MESS_TYPE_GROUPCHAT, C.MESS_TYPE_INFO) and self.target == entity.bare:
if (
mess_type in (C.MESS_TYPE_GROUPCHAT, C.MESS_TYPE_INFO)
and self.target == entity.bare
):
return True
else:
if mess_type != C.MESS_TYPE_GROUPCHAT and entity in self.targets:
return True
return False
def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile='@NONE@'):
def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
"""Called when history need to be recreated
Remove all message from history then call historyPrint
@ -423,7 +480,7 @@ class QuickChat(quick_widgets.QuickWidget):
self.messageNew(*data)
del self._cache
def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile='@NONE@'):
def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
"""Print the current history
@param size (int): number of messages
@ -442,21 +499,23 @@ class QuickChat(quick_widgets.QuickWidget):
log.debug(log_msg)
if self.type == C.CHAT_ONE2ONE:
special = self.host.contact_lists[self.profile].getCache(self.target, C.CONTACT_SPECIAL)
special = self.host.contact_lists[self.profile].getCache(
self.target, C.CONTACT_SPECIAL
)
if special == C.CONTACT_SPECIAL_GROUP:
# we have a private conversation
# so we need full jid for the history
# (else we would get history from group itself)
# and to filter out groupchat message
target = self.target
filters['not_types'] = C.MESS_TYPE_GROUPCHAT
filters["not_types"] = C.MESS_TYPE_GROUPCHAT
else:
target = self.target.bare
else:
# groupchat
target = self.target.bare
# FIXME: info not handled correctly
filters['types'] = C.MESS_TYPE_GROUPCHAT
filters["types"] = C.MESS_TYPE_GROUPCHAT
def _historyGetCb(history):
# day_format = "%A, %d %b %Y" # to display the day change
@ -476,42 +535,80 @@ class QuickChat(quick_widgets.QuickWidget):
# if ((self.type == C.CHAT_GROUP and type_ != C.MESS_TYPE_GROUPCHAT) or
# (self.type == C.CHAT_ONE2ONE and type_ == C.MESS_TYPE_GROUPCHAT)):
# continue
extra['history'] = True
self.messages[uid] = Message(self, uid, timestamp, from_jid, to_jid, message, subject, type_, extra, profile)
extra["history"] = True
self.messages[uid] = Message(
self,
uid,
timestamp,
from_jid,
to_jid,
message,
subject,
type_,
extra,
profile,
)
self._onHistoryPrinted()
def _historyGetEb(err):
log.error(_(u"Can't get history: {}").format(err))
self._onHistoryPrinted()
self.host.bridge.historyGet(unicode(self.host.profiles[profile].whoami.bare), unicode(target), size, True, filters, profile, callback=_historyGetCb, errback=_historyGetEb)
self.host.bridge.historyGet(
unicode(self.host.profiles[profile].whoami.bare),
unicode(target),
size,
True,
filters,
profile,
callback=_historyGetCb,
errback=_historyGetEb,
)
def messageNew(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile):
def messageNew(
self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
):
if self._locked:
self._cache[uid] = (uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile)
self._cache[uid] = (
uid,
timestamp,
from_jid,
to_jid,
msg,
subject,
type_,
extra,
profile,
)
return
if self.type == C.CHAT_GROUP:
if to_jid.resource and type_ != C.MESS_TYPE_GROUPCHAT:
# we have a private message, we forward it to a private conversation widget
chat_widget = self.getOrCreatePrivateWidget(to_jid)
chat_widget.messageNew(uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile)
chat_widget.messageNew(
uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
)
return
if type_ == C.MESS_TYPE_INFO:
try:
info_type = extra['info_type']
info_type = extra["info_type"]
except KeyError:
pass
else:
user_data = {k[5:]:v for k,v in extra.iteritems() if k.startswith('user_')}
user_data = {
k[5:]: v for k, v in extra.iteritems() if k.startswith("user_")
}
if info_type == ROOM_USER_JOINED:
self.addUser(user_data)
elif info_type == ROOM_USER_LEFT:
self.removeUser(user_data)
message = Message(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile)
message = Message(
self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
)
self.messages[uid] = message
if 'received_timestamp' in extra:
if "received_timestamp" in extra:
log.warning(u"Delayed message received after history, this should not happen")
self.createMessage(message)
@ -537,7 +634,9 @@ class QuickChat(quick_widgets.QuickWidget):
def setSubject(self, subject):
"""Set title for a group chat"""
if self.type != C.CHAT_GROUP:
raise exceptions.InternalError("trying to set subject for a non group chat window")
raise exceptions.InternalError(
"trying to set subject for a non group chat window"
)
self.subject = subject
def changeSubject(self, new_subject):
@ -579,8 +678,11 @@ class QuickChat(quick_widgets.QuickWidget):
try:
self.occupants[nick].state = state
except KeyError:
log.warning(u"{nick} not found in {room}, ignoring new chat state".format(
nick=nick, room=self.target.bare))
log.warning(
u"{nick} not found in {room}, ignoring new chat state".format(
nick=nick, room=self.target.bare
)
)
def onMessageState(self, uid, status, profile):
try:
@ -594,7 +696,7 @@ class QuickChat(quick_widgets.QuickWidget):
if self.type == C.CHAT_GROUP:
if entity.bare == self.target:
try:
self.occupants[entity.resource].update({'avatar': filename})
self.occupants[entity.resource].update({"avatar": filename})
except KeyError:
# can happen for a message in history where the
# entity is not here anymore
@ -603,14 +705,17 @@ class QuickChat(quick_widgets.QuickWidget):
for m in self.messages.values():
if m.nick == entity.resource:
for w in m.widgets:
w.update({'avatar': filename})
w.update({"avatar": filename})
else:
if entity.bare == self.target.bare or entity.bare == self.host.profiles[profile].whoami.bare:
if (
entity.bare == self.target.bare
or entity.bare == self.host.profiles[profile].whoami.bare
):
log.info(u"avatar updated for {}".format(entity))
for m in self.messages.values():
if m.from_jid.bare == entity.bare:
for w in m.widgets:
w.update({'avatar': filename})
w.update({"avatar": filename})
quick_widgets.register(QuickChat)

View file

@ -22,6 +22,7 @@
from sat.core.i18n import _
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from sat_frontends.quick_frontend.quick_widgets import QuickWidget
@ -32,9 +33,9 @@ from collections import OrderedDict
try:
# FIXME: to be removed when an acceptable solution is here
unicode('') # XXX: unicode doesn't exist in pyjamas
unicode("") # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on
# pyjsbuild options
# pyjsbuild options
# XXX: pyjamas' max doesn't support key argument, so we implement it ourself
pyjamas_max = max
@ -95,27 +96,31 @@ class ProfileContactList(object):
# (e.g. not in contact list) if they have notifications attached
self.show_entities_with_notifs = True
self.host.bridge.asyncGetParamA(C.SHOW_EMPTY_GROUPS,
"General",
profile_key=profile,
callback=self._showEmptyGroups)
self.host.bridge.asyncGetParamA(
C.SHOW_EMPTY_GROUPS,
"General",
profile_key=profile,
callback=self._showEmptyGroups,
)
self.host.bridge.asyncGetParamA(C.SHOW_OFFLINE_CONTACTS,
"General",
profile_key=profile,
callback=self._showOfflineContacts)
self.host.bridge.asyncGetParamA(
C.SHOW_OFFLINE_CONTACTS,
"General",
profile_key=profile,
callback=self._showOfflineContacts,
)
# FIXME: workaround for a pyjamas issue: calling hash on a class method always
# return a different value if that method is defined directly within the
# class (with the "def" keyword)
self.presenceListener = self.onPresenceUpdate
self.host.addListener('presence', self.presenceListener, [self.profile])
self.host.addListener("presence", self.presenceListener, [self.profile])
self.nickListener = self.onNickUpdate
self.host.addListener('nick', self.nickListener, [self.profile])
self.host.addListener("nick", self.nickListener, [self.profile])
self.notifListener = self.onNotification
self.host.addListener('notification', self.notifListener, [self.profile])
self.host.addListener("notification", self.notifListener, [self.profile])
# notifListener only update the entity, so we can re-use it
self.host.addListener('notificationsClear', self.notifListener, [self.profile])
self.host.addListener("notificationsClear", self.notifListener, [self.profile])
def _showEmptyGroups(self, show_str):
# Called only by __init__
@ -155,8 +160,13 @@ class ProfileContactList(object):
@return (set[jid.JID])
"""
return set([entity for entity in self._roster
if self.getCache(entity, C.PRESENCE_SHOW) is not None])
return set(
[
entity
for entity in self._roster
if self.getCache(entity, C.PRESENCE_SHOW) is not None
]
)
@property
def roster_entities_by_group(self):
@ -165,7 +175,7 @@ class ProfileContactList(object):
This also includes the empty group (None key).
@return (dict[unicode,set(jid.JID)])
"""
return {group: self._groups[group]['jids'] for group in self._groups}
return {group: self._groups[group]["jids"] for group in self._groups}
@property
def roster_groups_by_entities(self):
@ -175,7 +185,7 @@ class ProfileContactList(object):
"""
result = {}
for group, data in self._groups.iteritems():
for entity in data['jids']:
for entity in data["jids"]:
result.setdefault(entity, set()).add(group)
return result
@ -195,7 +205,6 @@ class ProfileContactList(object):
"""
return self._cache.iteritems()
@property
def items(self):
"""Return item representation for all visible entities in cache
@ -203,9 +212,11 @@ class ProfileContactList(object):
entities are not sorted
key: bare jid, value: data
"""
return {jid_:cache for jid_, cache in self._cache.iteritems()
if self.entityVisible(jid_)}
return {
jid_: cache
for jid_, cache in self._cache.iteritems()
if self.entityVisible(jid_)
}
def getItem(self, entity):
"""Return item representation of requested entity
@ -275,7 +286,7 @@ class ProfileContactList(object):
# full cache is requested
return cache
if name in ('status', C.PRESENCE_STATUSES, C.PRESENCE_PRIORITY, C.PRESENCE_SHOW):
if name in ("status", C.PRESENCE_STATUSES, C.PRESENCE_PRIORITY, C.PRESENCE_SHOW):
# these data are related to the resource
if not entity.resource:
main_resource = cache[C.CONTACT_MAIN_RESOURCE]
@ -287,9 +298,9 @@ class ProfileContactList(object):
else:
cache = cache[C.CONTACT_RESOURCES].setdefault(entity.resource, {})
if name == 'status': # XXX: we get the first status for 'status' key
if name == "status": # XXX: we get the first status for 'status' key
# TODO: manage main language for statuses
return cache[C.PRESENCE_STATUSES].get(C.PRESENCE_STATUSES_DEFAULT, '')
return cache[C.PRESENCE_STATUSES].get(C.PRESENCE_STATUSES_DEFAULT, "")
elif entity.resource:
try:
@ -332,7 +343,7 @@ class ProfileContactList(object):
@param name: name of the data (can't be "jids")
@param value: value to set
"""
assert name is not 'jids'
assert name is not "jids"
self._groups[group][name] = value
def getGroupData(self, group, name=None):
@ -388,8 +399,10 @@ class ProfileContactList(object):
for entity in self._specials:
if bare and entity.resource:
continue
if (special_type is not None
and self.getCache(entity, C.CONTACT_SPECIAL) != special_type):
if (
special_type is not None
and self.getCache(entity, C.CONTACT_SPECIAL) != special_type
):
continue
yield entity
@ -440,9 +453,14 @@ class ProfileContactList(object):
if in_roster:
self._roster.add(entity_bare)
cache = self._cache.setdefault(entity_bare, {C.CONTACT_RESOURCES: {},
C.CONTACT_MAIN_RESOURCE: None,
C.CONTACT_SELECTED: set()})
cache = self._cache.setdefault(
entity_bare,
{
C.CONTACT_RESOURCES: {},
C.CONTACT_MAIN_RESOURCE: None,
C.CONTACT_SELECTED: set(),
},
)
# we don't want forbidden data in attributes
assert not C.CONTACT_DATA_FORBIDDEN.intersection(attributes)
@ -454,13 +472,15 @@ class ProfileContactList(object):
if C.CONTACT_GROUPS in cache:
# XXX: don't use set(cache[C.CONTACT_GROUPS]).difference(groups) because
# it won't work in Pyjamas if None is in cache[C.CONTACT_GROUPS]
for group in [group for group in cache[C.CONTACT_GROUPS]
if group not in groups]:
self._groups[group]['jids'].remove(entity_bare)
for group in [
group for group in cache[C.CONTACT_GROUPS] if group not in groups
]:
self._groups[group]["jids"].remove(entity_bare)
cache[C.CONTACT_GROUPS] = groups
for group in groups:
self._groups.setdefault(group, {}).setdefault('jids', set()).add(
entity_bare)
self._groups.setdefault(group, {}).setdefault("jids", set()).add(
entity_bare
)
# special entities management
if C.CONTACT_SPECIAL in attributes:
@ -473,8 +493,11 @@ class ProfileContactList(object):
# now the attributes we keep in cache
# XXX: if entity is a full jid, we store the value for the resource only
cache_attr = (cache[C.CONTACT_RESOURCES].setdefault(entity.resource, {})
if entity.resource else cache)
cache_attr = (
cache[C.CONTACT_RESOURCES].setdefault(entity.resource, {})
if entity.resource
else cache
)
for attribute, value in attributes.iteritems():
if value is None:
# XXX: pyjamas hack: we need to use pop instead of del
@ -483,7 +506,9 @@ class ProfileContactList(object):
except KeyError:
pass
else:
if attribute == 'nick' and self.isSpecial(entity, C.CONTACT_SPECIAL_GROUP):
if attribute == "nick" and self.isSpecial(
entity, C.CONTACT_SPECIAL_GROUP
):
# we don't want to keep nick for MUC rooms
# FIXME: this is here as plugin XEP-0054 can link resource's nick
# with bare jid which in the case of MUC
@ -518,12 +543,15 @@ class ProfileContactList(object):
selected = self._selected
else:
selected = {selected.bare for selected in self._selected}
return ((show is not None and show != C.PRESENCE_UNAVAILABLE)
or self.show_disconnected
or entity in selected
or (self.show_entities_with_notifs
and next(self.host.getNotifs(entity.bare, profile=self.profile), None))
)
return (
(show is not None and show != C.PRESENCE_UNAVAILABLE)
or self.show_disconnected
or entity in selected
or (
self.show_entities_with_notifs
and next(self.host.getNotifs(entity.bare, profile=self.profile), None)
)
)
def anyEntityVisible(self, entities, check_resources=False):
"""Tell if in a list of entities, at least one should be shown
@ -564,8 +592,8 @@ class ProfileContactList(object):
pass
del self._cache[entity_bare]
for group in groups:
self._groups[group]['jids'].remove(entity_bare)
if not self._groups[group]['jids']:
self._groups[group]["jids"].remove(entity_bare)
if not self._groups[group]["jids"]:
# FIXME: we use pop because of pyjamas:
# http://wiki.goffi.org/wiki/Issues_with_Pyjamas/en
self._groups.pop(group)
@ -599,14 +627,20 @@ class ProfileContactList(object):
try:
del cache[C.CONTACT_RESOURCES][entity.resource]
except KeyError:
log.error(u"Presence unavailable received "
u"for an unknown resource [{}]".format(entity))
log.error(
u"Presence unavailable received "
u"for an unknown resource [{}]".format(entity)
)
if not cache[C.CONTACT_RESOURCES]:
cache[C.CONTACT_MAIN_RESOURCE] = None
else:
if not entity.resource:
log.warning(_(u"received presence from entity "
u"without resource: {}".format(entity)))
log.warning(
_(
u"received presence from entity "
u"without resource: {}".format(entity)
)
)
resources_data = cache[C.CONTACT_RESOURCES]
resource_data = resources_data.setdefault(entity.resource, {})
resource_data[C.PRESENCE_SHOW] = show
@ -616,9 +650,12 @@ class ProfileContactList(object):
if entity.bare not in self._specials:
# we may have resources with no priority
# (when a cached value is added for a not connected resource)
priority_resource = max(resources_data,
key=lambda res: resources_data[res].get(
C.PRESENCE_PRIORITY, -2**32))
priority_resource = max(
resources_data,
key=lambda res: resources_data[res].get(
C.PRESENCE_PRIORITY, -2 ** 32
),
)
cache[C.CONTACT_MAIN_RESOURCE] = priority_resource
if self.entityVisible(entity.bare):
update_type = C.UPDATE_MODIFY if was_visible else C.UPDATE_ADD
@ -634,7 +671,7 @@ class ProfileContactList(object):
@param profile: %(doc_profile)s
"""
assert profile == self.profile
self.setCache(entity, 'nick', new_nick)
self.setCache(entity, "nick", new_nick)
def onNotification(self, entity, notif, profile):
"""Update entity with notification
@ -723,18 +760,18 @@ class ProfileContactList(object):
class QuickContactListHandler(object):
def __init__(self, host):
super(QuickContactListHandler, self).__init__()
self.host = host
global handler
if handler is not None:
raise exceptions.InternalError(u"QuickContactListHandler must be "
u"instanciated only once")
raise exceptions.InternalError(
u"QuickContactListHandler must be " u"instanciated only once"
)
handler = self
self._clist = {} # key: profile, value: ProfileContactList
self._clist = {} # key: profile, value: ProfileContactList
self._widgets = set()
self._update_locked = False # se to True to ignore updates
self._update_locked = False # se to True to ignore updates
def __getitem__(self, profile):
"""Return ProfileContactList instance for the requested profile"""
@ -845,16 +882,16 @@ class QuickContactListHandler(object):
return self.items_sort(self.items)
def items_sort(self, items):
"""sort items
"""sort items
@param items(dict): items to sort (will be emptied !)
@return (OrderedDict): sorted items
"""
ordered_items = OrderedDict()
bare_jids = sorted(items.keys())
for jid_ in bare_jids:
ordered_items[jid_] = items.pop(jid_)
return ordered_items
ordered_items = OrderedDict()
bare_jids = sorted(items.keys())
for jid_ in bare_jids:
ordered_items[jid_] = items.pop(jid_)
return ordered_items
def register(self, widget):
"""Register a QuickContactList widget
@ -940,8 +977,11 @@ class QuickContactListHandler(object):
remaining = to_fill.difference(filled)
if remaining != to_fill:
log.debug(u"Not re-filling already filled contact list(s) for {}".format(
u', '.join(to_fill.intersection(filled))))
log.debug(
u"Not re-filling already filled contact list(s) for {}".format(
u", ".join(to_fill.intersection(filled))
)
)
for profile in remaining:
self._clist[profile]._fill()
@ -973,8 +1013,11 @@ class QuickContactListHandler(object):
if set to False, widget state can be inconsistent, be sure to know
what youa re doing!
"""
log.debug(u"Contact lists updates are now {}".format(
u"LOCKED" if locked else u"UNLOCKED"))
log.debug(
u"Contact lists updates are now {}".format(
u"LOCKED" if locked else u"UNLOCKED"
)
)
self._update_locked = locked
if not locked and do_update:
self.update()
@ -987,10 +1030,11 @@ class QuickContactListHandler(object):
class QuickContactList(QuickWidget):
"""This class manage the visual representation of contacts"""
SINGLE=False
PROFILES_MULTIPLE=True
SINGLE = False
PROFILES_MULTIPLE = True
# Can be linked to no profile (e.g. at the early frontend start)
PROFILES_ALLOW_NONE=True
PROFILES_ALLOW_NONE = True
def __init__(self, host, profiles):
super(QuickContactList, self).__init__(host, None, profiles)
@ -998,10 +1042,10 @@ class QuickContactList(QuickWidget):
# options
# for next values, None means use indivual value per profile
# True or False mean override these values for all profiles
self.show_disconnected = None # TODO
self.show_empty_groups = None # TODO
self.show_resources = None # TODO
self.show_status = None # TODO
self.show_disconnected = None # TODO
self.show_empty_groups = None # TODO
self.show_resources = None # TODO
self.show_status = None # TODO
def postInit(self):
"""Method to be called by frontend after widget is initialised"""

View file

@ -19,12 +19,14 @@
from sat.core.i18n import _
from sat.core.log import getLogger
log = getLogger(__name__)
from sat_frontends.tools.jid import JID
from sat_frontends.tools.jid import JID
class QuickContactManagement(object):
"""This helper class manage the contacts and ease the use of nicknames and shortcuts"""
### FIXME: is SàT a better place for all this stuff ??? ###
def __init__(self):
@ -40,19 +42,19 @@ class QuickContactManagement(object):
def add(self, entity):
"""Add contact to the list, update resources"""
if not self.__contactlist.has_key(entity.bare):
self.__contactlist[entity.bare] = {'resources':[]}
self.__contactlist[entity.bare] = {"resources": []}
if not entity.resource:
return
if entity.resource in self.__contactlist[entity.bare]['resources']:
self.__contactlist[entity.bare]['resources'].remove(entity.resource)
self.__contactlist[entity.bare]['resources'].append(entity.resource)
if entity.resource in self.__contactlist[entity.bare]["resources"]:
self.__contactlist[entity.bare]["resources"].remove(entity.resource)
self.__contactlist[entity.bare]["resources"].append(entity.resource)
def getContFromGroup(self, group):
"""Return all contacts which are in given group"""
result = []
for contact in self.__contactlist:
if self.__contactlist[contact].has_key('groups'):
if group in self.__contactlist[contact]['groups']:
if self.__contactlist[contact].has_key("groups"):
if group in self.__contactlist[contact]["groups"]:
result.append(JID(contact))
return result
@ -62,13 +64,13 @@ class QuickContactManagement(object):
@param name: name of the attribute
@return: asked attribute"""
if self.__contactlist.has_key(entity.bare):
if name == 'status': #FIXME: for the moment, we only use the first status
if self.__contactlist[entity.bare]['statuses']:
return self.__contactlist[entity.bare]['statuses'].values()[0]
if name == "status": # FIXME: for the moment, we only use the first status
if self.__contactlist[entity.bare]["statuses"]:
return self.__contactlist[entity.bare]["statuses"].values()[0]
if self.__contactlist[entity.bare].has_key(name):
return self.__contactlist[entity.bare][name]
else:
log.debug(_('Trying to get attribute for an unknown contact'))
log.debug(_("Trying to get attribute for an unknown contact"))
return None
def isConnected(self, entity):
@ -79,12 +81,12 @@ class QuickContactManagement(object):
"""remove resource. If no more resource is online or is no resource is specified, contact is deleted"""
try:
if entity.resource:
self.__contactlist[entity.bare]['resources'].remove(entity.resource)
if not entity.resource or not self.__contactlist[entity.bare]['resources']:
#no more resource available: the contact seems really disconnected
self.__contactlist[entity.bare]["resources"].remove(entity.resource)
if not entity.resource or not self.__contactlist[entity.bare]["resources"]:
# no more resource available: the contact seems really disconnected
del self.__contactlist[entity.bare]
except KeyError:
log.error(_('INTERNAL ERROR: Key log.error'))
log.error(_("INTERNAL ERROR: Key log.error"))
raise
def update(self, entity, key, value):
@ -96,8 +98,7 @@ class QuickContactManagement(object):
if self.__contactlist.has_key(entity.bare):
self.__contactlist[entity.bare][key] = value
else:
log.debug (_('Trying to update an unknown contact: %s') % entity.bare)
log.debug(_("Trying to update an unknown contact: %s") % entity.bare)
def get_full(self, entity):
return entity.bare+'/'+self.__contactlist[entity.bare]['resources'][-1]
return entity.bare + "/" + self.__contactlist[entity.bare]["resources"][-1]

View file

@ -18,14 +18,14 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
from sat_frontends.tools.jid import JID
class QuickTarotGame(object):
def __init__(self, parent, referee, players):
self._autoplay = None #XXX: use 0 to activate fake play, None else
self._autoplay = None # XXX: use 0 to activate fake play, None else
self.parent = parent
self.referee = referee
self.players = players
@ -42,8 +42,8 @@ class QuickTarotGame(object):
idx = (idx + 1) % len(self.players)
self.left_nick = unicode(self.players[idx])
self.bottom_nick = unicode(self.player_nick)
self.selected = [] #Card choosed by the player (e.g. during ecart)
self.hand_size = 13 #number of cards in a hand
self.selected = [] # Card choosed by the player (e.g. during ecart)
self.hand_size = 13 # number of cards in a hand
self.hand = []
self.to_show = []
self.state = None
@ -59,25 +59,27 @@ class QuickTarotGame(object):
def getPlayerLocation(self, nick):
"""return player location (top,bottom,left or right)"""
for location in ['top','left','bottom','right']:
if getattr(self,'%s_nick' % location) == nick:
for location in ["top", "left", "bottom", "right"]:
if getattr(self, "%s_nick" % location) == nick:
return location
assert(False)
assert False
def loadCards(self):
"""Load all the cards in memory
@param dir: directory where the PNG files are"""
self.cards={}
self.deck=[]
self.cards["atout"]={} #As Tarot is a french game, it's more handy & logical to keep french names
self.cards["pique"]={} #spade
self.cards["coeur"]={} #heart
self.cards["carreau"]={} #diamond
self.cards["trefle"]={} #club
self.cards = {}
self.deck = []
self.cards[
"atout"
] = {} # As Tarot is a french game, it's more handy & logical to keep french names
self.cards["pique"] = {} # spade
self.cards["coeur"] = {} # heart
self.cards["carreau"] = {} # diamond
self.cards["trefle"] = {} # club
def tarotGameNewHandler(self, hand):
"""Start a new game, with given hand"""
assert (len(self.hand) == 0)
assert len(self.hand) == 0
for suit, value in hand:
self.hand.append(self.cards[suit, value])
self.hand.sort()
@ -93,7 +95,7 @@ class QuickTarotGame(object):
self.to_show = []
for suit, value in cards:
self.to_show.append(self.cards[suit, value])
if game_stage == "chien" and data['attaquant'] == self.player_nick:
if game_stage == "chien" and data["attaquant"] == self.player_nick:
self.state = "wait_for_ecart"
else:
self.state = "chien"
@ -113,10 +115,12 @@ class QuickTarotGame(object):
if self._autoplay >= len(self.hand):
self._autoplay = 0
card = self.hand[self._autoplay]
self.parent.host.bridge.tarotGamePlayCards(self.player_nick, self.referee, [(card.suit, card.value)], self.parent.profile)
self.parent.host.bridge.tarotGamePlayCards(
self.player_nick, self.referee, [(card.suit, card.value)], self.parent.profile
)
del self.hand[self._autoplay]
self.state = "wait"
self._autoplay+=1
self._autoplay += 1
def tarotGameScoreHandler(self, xml_data, winners, loosers):
"""Called at the end of a game
@ -130,7 +134,7 @@ class QuickTarotGame(object):
if self.to_show:
self.to_show = []
pl_cards = []
if self.played[player] != None: #FIXME
if self.played[player] != None: # FIXME
for pl in self.played:
self.played[pl] = None
for suit, value in cards:
@ -148,11 +152,10 @@ class QuickTarotGame(object):
elif phase == "ecart":
self.state = "ecart"
else:
log.error ('INTERNAL ERROR: unmanaged game phase')
log.error("INTERNAL ERROR: unmanaged game phase")
for suit, value in played_cards:
self.hand.append(self.cards[suit, value])
self.hand.sort()
self.__fakePlay()

View file

@ -18,6 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core.i18n import _
@ -36,23 +37,27 @@ class RoomGame(object):
@classmethod
def registerSignals(cls, host):
def make_handler(suffix, signal):
def handler(*args):
if suffix in ("Started", "Players"):
return cls.startedHandler(host, suffix, *args)
return cls.genericHandler(host, signal, *args)
return handler
for suffix in cls._signal_suffixes:
signal = cls._signal_prefix + suffix
host.registerSignal(signal, handler=make_handler(suffix, signal), iface="plugin")
host.registerSignal(
signal, handler=make_handler(suffix, signal), iface="plugin"
)
@classmethod
def startedHandler(cls, host, suffix, *args):
room_jid, args, profile = jid.JID(args[0]), args[1:-1], args[-1]
referee, players, args = args[0], args[1], args[2:]
chat_widget = host.widgets.getOrCreateWidget(quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile)
chat_widget = host.widgets.getOrCreateWidget(
quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile
)
# update symbols
if cls._game_name not in chat_widget.visible_states:
@ -62,7 +67,11 @@ class RoomGame(object):
contact_list = host.contact_lists[profile]
for occupant in chat_widget.occupants:
occupant_jid = jid.newResource(room_jid, occupant)
contact_list.setCache(occupant_jid, cls._game_name, symbols[index % len(symbols)] if occupant in players else None)
contact_list.setCache(
occupant_jid,
cls._game_name,
symbols[index % len(symbols)] if occupant in players else None,
)
chat_widget.update(occupant_jid)
if suffix == "Players" or chat_widget.nick not in players:
@ -71,8 +80,12 @@ class RoomGame(object):
return # game panel is already there
real_class = host.widgets.getRealClass(cls)
if real_class == cls:
host.showDialog(_(u"A {game} activity between {players} has been started, but you couldn't take part because your client doesn't support it.").format(game=cls._game_name, players=', '.join(players)),
_(u"{game} Game").format(game=cls._game_name))
host.showDialog(
_(
u"A {game} activity between {players} has been started, but you couldn't take part because your client doesn't support it."
).format(game=cls._game_name, players=", ".join(players)),
_(u"{game} Game").format(game=cls._game_name),
)
return
panel = real_class(chat_widget, referee, players, *args)
chat_widget.games[cls._game_name] = panel
@ -86,7 +99,10 @@ class RoomGame(object):
try:
game_panel = chat_widget.games[cls._game_name]
except KeyError:
log.error("TODO: better game synchronisation - received signal %s but no panel is found" % signal)
log.error(
"TODO: better game synchronisation - received signal %s but no panel is found"
% signal
)
return
else:
getattr(game_panel, "%sHandler" % signal)(*args)
@ -95,23 +111,43 @@ class RoomGame(object):
class Tarot(RoomGame):
_game_name = "Tarot"
_signal_prefix = "tarotGame"
_signal_suffixes = ("Started", "Players", "New", "ChooseContrat",
"ShowCards", "YourTurn", "Score", "CardsPlayed",
"InvalidCards",
)
_signal_suffixes = (
"Started",
"Players",
"New",
"ChooseContrat",
"ShowCards",
"YourTurn",
"Score",
"CardsPlayed",
"InvalidCards",
)
class Quiz(RoomGame):
_game_name = "Quiz"
_signal_prefix = "quizGame"
_signal_suffixes = ("Started", "New", "Question", "PlayerBuzzed",
"PlayerSays", "AnswerResult", "TimerExpired",
"TimerRestarted",
)
_signal_suffixes = (
"Started",
"New",
"Question",
"PlayerBuzzed",
"PlayerSays",
"AnswerResult",
"TimerExpired",
"TimerRestarted",
)
class Radiocol(RoomGame):
_game_name = "Radiocol"
_signal_prefix = "radiocol"
_signal_suffixes = ("Started", "Players", "SongRejected", "Preload",
"Play", "NoUpload", "UploadOk")
_signal_suffixes = (
"Started",
"Players",
"SongRejected",
"Preload",
"Play",
"NoUpload",
"UploadOk",
)

View file

@ -25,10 +25,14 @@ class QuickTagList(object):
"""
@param items (list): the suggested list of non tagged items
"""
"""
self.tagged = []
self.original = items[:] if items else [] # XXX: copy the list! It will be modified
self.untagged = items[:] if items else [] # XXX: copy the list! It will be modified
self.original = (
items[:] if items else []
) # XXX: copy the list! It will be modified
self.untagged = (
items[:] if items else []
) # XXX: copy the list! It will be modified
self.untagged.sort()
@property

View file

@ -19,12 +19,16 @@
try:
# FIXME: to be removed when an acceptable solution is here
unicode('') # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
unicode("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
unicode = str
from sat.core.log import getLogger
from sat.core.i18n import _, languageSwitch
log = getLogger(__name__)
from sat_frontends.quick_frontend.constants import Const as C
from collections import OrderedDict
@ -32,8 +36,9 @@ from collections import OrderedDict
## items ##
class MenuBase(object):
ACTIVE=True
ACTIVE = True
def __init__(self, name, extra=None):
"""
@ -61,7 +66,8 @@ class MenuBase(object):
class MenuItem(MenuBase):
"""A callable item in the menu"""
CALLABLE=False
CALLABLE = False
def __init__(self, name, name_i18n, extra=None, type_=None):
"""
@ -83,7 +89,7 @@ class MenuItem(MenuBase):
@param caller: Menu caller
"""
assert self.type is not None # if data collector are used, type must be set
assert self.type is not None # if data collector are used, type must be set
data_collector = QuickMenusManager.getDataCollector(self.type)
if data_collector is None:
@ -101,7 +107,6 @@ class MenuItem(MenuBase):
data[data_key] = unicode(getattr(caller, caller_attr))
return data
def call(self, caller, profile=C.PROF_KEY_NONE):
"""Execute the menu item
@ -113,7 +118,8 @@ class MenuItem(MenuBase):
class MenuItemDistant(MenuItem):
"""A MenuItem with a distant callback"""
CALLABLE=True
CALLABLE = True
def __init__(self, host, type_, name, name_i18n, id_, extra=None):
"""
@ -129,14 +135,15 @@ class MenuItemDistant(MenuItem):
self.id = id_
def call(self, caller, profile=C.PROF_KEY_NONE):
data = self.collectData(caller)
data = self.collectData(caller)
log.debug("data collected: %s" % data)
self.host.launchAction(self.id, data, profile=profile)
class MenuItemLocal(MenuItem):
"""A MenuItem with a local callback"""
CALLABLE=True
CALLABLE = True
def __init__(self, type_, name, name_i18n, callback, extra=None):
"""
@ -162,12 +169,14 @@ class MenuItemLocal(MenuItem):
class MenuHook(MenuItemLocal):
"""A MenuItem which replace an expected item from backend"""
pass
class MenuPlaceHolder(MenuItem):
"""A non existant menu which is used to keep a position"""
ACTIVE=False
ACTIVE = False
def __init__(self, name):
MenuItem.__init__(self, name, name)
@ -175,10 +184,11 @@ class MenuPlaceHolder(MenuItem):
class MenuSeparator(MenuItem):
"""A separation between items/categories"""
SEP_IDX=0
SEP_IDX = 0
def __init__(self):
MenuSeparator.SEP_IDX +=1
MenuSeparator.SEP_IDX += 1
name = u"___separator_{}".format(MenuSeparator.SEP_IDX)
MenuItem.__init__(self, name, name)
@ -187,7 +197,6 @@ class MenuSeparator(MenuItem):
class MenuContainer(MenuBase):
def __init__(self, name, extra=None):
MenuBase.__init__(self, name, extra)
self._items = OrderedDict()
@ -208,7 +217,10 @@ class MenuContainer(MenuBase):
raise KeyError(item)
def getOrCreate(self, item):
log.debug(u"MenuContainer getOrCreate: item=%s name=%s\nlist=%s" % (item, item.canonical, self._items.keys()))
log.debug(
u"MenuContainer getOrCreate: item=%s name=%s\nlist=%s"
% (item, item.canonical, self._items.keys())
)
try:
return self[item]
except KeyError:
@ -255,6 +267,7 @@ class MenuCategory(MenuContainer):
class MenuType(MenuContainer):
"""A type which can hold other menus or categories"""
pass
@ -263,7 +276,10 @@ class MenuType(MenuContainer):
class QuickMenusManager(object):
"""Manage all the menus"""
_data_collectors={C.MENU_GLOBAL: None} # No data is associated with C.MENU_GLOBAL items
_data_collectors = {
C.MENU_GLOBAL: None
} # No data is associated with C.MENU_GLOBAL items
def __init__(self, host, menus=None, language=None):
"""
@ -358,15 +374,28 @@ class QuickMenusManager(object):
menu_container.replace(item)
elif isinstance(container_item, MenuHook):
# MenuHook must not be replaced
log.debug(u"ignoring menu at path [{}] because a hook is already in place".format(path))
log.debug(
u"ignoring menu at path [{}] because a hook is already in place".format(
path
)
)
else:
log.error(u"Conflicting menus at path [{}]".format(path))
else:
log.debug(u"Adding menu [{type_}] {path}".format(type_=type_, path=path))
menu_container.append(item)
self.host.callListeners('menu', type_, path, path_i18n, item)
self.host.callListeners("menu", type_, path, path_i18n, item)
def addMenu(self, type_, path, path_i18n=None, extra=None, top_extra=None, id_=None, callback=None):
def addMenu(
self,
type_,
path,
path_i18n=None,
extra=None,
top_extra=None,
id_=None,
callback=None,
):
"""Add a menu item
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@ -379,11 +408,15 @@ class QuickMenusManager(object):
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
assert bool(id_) ^ bool(callback) # we must have id_ xor callback defined
assert bool(id_) ^ bool(callback) # we must have id_ xor callback defined
if id_:
menu_item = MenuItemDistant(self.host, type_, path[-1], path_i18n[-1], id_=id_, extra=extra)
menu_item = MenuItemDistant(
self.host, type_, path[-1], path_i18n[-1], id_=id_, extra=extra
)
else:
menu_item = MenuItemLocal(type_, path[-1], path_i18n[-1], callback=callback, extra=extra)
menu_item = MenuItemLocal(
type_, path[-1], path_i18n[-1], callback=callback, extra=extra
)
self.addMenuItem(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
def addMenus(self, menus, top_extra=None):
@ -401,11 +434,17 @@ class QuickMenusManager(object):
# TODO: manage icons
for id_, type_, path, path_i18n, extra in menus:
if callable(id_):
self.addMenu(type_, path, path_i18n, callback=id_, extra=extra, top_extra=top_extra)
self.addMenu(
type_, path, path_i18n, callback=id_, extra=extra, top_extra=top_extra
)
else:
self.addMenu(type_, path, path_i18n, id_=id_, extra=extra, top_extra=top_extra)
self.addMenu(
type_, path, path_i18n, id_=id_, extra=extra, top_extra=top_extra
)
def addMenuHook(self, type_, path, path_i18n=None, extra=None, top_extra=None, callback=None):
def addMenuHook(
self, type_, path, path_i18n=None, extra=None, top_extra=None, callback=None
):
"""Helper method to add a menu hook
Menu hooks are local menus which override menu given by backend
@ -418,7 +457,9 @@ class QuickMenusManager(object):
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
menu_item = MenuHook(type_, path[-1], path_i18n[-1], callback=callback, extra=extra)
menu_item = MenuHook(
type_, path[-1], path_i18n[-1], callback=callback, extra=extra
)
self.addMenuItem(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
log.info(u"Menu hook set on {path} ({type_})".format(path=path, type_=type_))
@ -434,7 +475,9 @@ class QuickMenusManager(object):
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
last_container = self._createCategories(type_, path, path_i18n, top_extra=top_extra)
last_container = self._createCategories(
type_, path, path_i18n, top_extra=top_extra
)
last_container.setExtra(extra)
return last_container

View file

@ -19,6 +19,7 @@
from sat.core.i18n import _
from sat.core import log as logging
log = logging.getLogger(__name__)
from sat_frontends.primitivus.constants import Const as C
@ -85,10 +86,9 @@ class QuickProfileManager(object):
log.warning("No profile given to autoconnect")
return
self._autoconnect = True
self._autoconnect_profiles=[]
self._autoconnect_profiles = []
self._do_autoconnect(profile_keys)
def _do_autoconnect(self, profile_keys):
"""Connect automatically given profiles
@ -98,36 +98,39 @@ class QuickProfileManager(object):
def authenticate_cb(data, cb_id, profile):
if C.bool(data.pop('validated', C.BOOL_FALSE)):
if C.bool(data.pop("validated", C.BOOL_FALSE)):
self._autoconnect_profiles.append(profile)
if len(self._autoconnect_profiles) == len(profile_keys):
# all the profiles have been validated
self.host.plug_profiles(self._autoconnect_profiles)
else:
# a profile is not validated, we go to manual mode
self._autoconnect=False
self._autoconnect = False
self.host.actionManager(data, callback=authenticate_cb, profile=profile)
def getProfileNameCb(profile):
if not profile:
# FIXME: this method is not handling manual mode correclty anymore
# must be thought to be handled asynchronously
self._autoconnect = False # manual mode
self._autoconnect = False # manual mode
msg = _("Trying to plug an unknown profile key ({})".format(profile_key))
log.warning(msg)
self.host.showDialog(_("Profile plugging in error"), msg, 'error')
self.host.showDialog(_("Profile plugging in error"), msg, "error")
else:
self.host.launchAction(C.AUTHENTICATE_PROFILE_ID, callback=authenticate_cb, profile=profile)
self.host.launchAction(
C.AUTHENTICATE_PROFILE_ID, callback=authenticate_cb, profile=profile
)
def getProfileNameEb(failure):
log.error(u"Can't retrieve profile name: {}".format(failure))
for profile_key in profile_keys:
self.host.bridge.profileNameGet(profile_key, callback=getProfileNameCb, errback=getProfileNameEb)
self.host.bridge.profileNameGet(
profile_key, callback=getProfileNameCb, errback=getProfileNameEb
)
def getParamError(self, dummy):
self.host.showDialog(_(u"Error"), _("Can't get profile parameter"), 'error')
self.host.showDialog(_(u"Error"), _("Can't get profile parameter"), "error")
## Helping methods ##
@ -142,7 +145,9 @@ class QuickProfileManager(object):
elif reason == "CancelError":
message = _("Profile creation cancelled by backend")
elif reason == "ValueError":
message = _("You profile name is not valid") # TODO: print a more informative message (empty name, name starting with '@')
message = _(
"You profile name is not valid"
) # TODO: print a more informative message (empty name, name starting with '@')
else:
message = _("Can't create profile ({})").format(reason)
return message
@ -150,7 +155,9 @@ class QuickProfileManager(object):
def _deleteProfile(self):
"""Delete the currently selected profile"""
if self.current.profile:
self.host.bridge.asyncDeleteProfile(self.current.profile, callback=self.refillProfiles)
self.host.bridge.asyncDeleteProfile(
self.current.profile, callback=self.refillProfiles
)
self.resetFields()
## workflow methods (events occuring during the profiles selection) ##
@ -160,12 +167,20 @@ class QuickProfileManager(object):
def _onConnectProfiles(self):
"""Connect the profiles and start the main widget"""
if self._autoconnect:
self.host.showDialog(_('Internal error'), _("You can't connect manually and automatically at the same time"), 'error')
self.host.showDialog(
_("Internal error"),
_("You can't connect manually and automatically at the same time"),
"error",
)
return
self.updateConnectionParams()
profiles = self.getProfiles()
if not profiles:
self.host.showDialog(_('No profile selected'), _('You need to create and select at least one profile before connecting'), 'error')
self.host.showDialog(
_("No profile selected"),
_("You need to create and select at least one profile before connecting"),
"error",
)
else:
# All profiles in the list are already validated, so we can plug them directly
self.host.plug_profiles(profiles)
@ -175,8 +190,20 @@ class QuickProfileManager(object):
@param profile: %(doc_profile)s
"""
self.host.bridge.asyncGetParamA("JabberID", "Connection", profile_key=profile, callback=self.setJID, errback=self.getParamError)
self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile, callback=self.setPassword, errback=self.getParamError)
self.host.bridge.asyncGetParamA(
"JabberID",
"Connection",
profile_key=profile,
callback=self.setJID,
errback=self.getParamError,
)
self.host.bridge.asyncGetParamA(
"Password",
"Connection",
profile_key=profile,
callback=self.setPassword,
errback=self.getParamError,
)
def updateConnectionParams(self):
"""Check if connection parameters have changed, and update them if so"""
@ -185,18 +212,24 @@ class QuickProfileManager(object):
password = self.getPassword()
if login != self.current.login and self.current.login is not None:
self.current.login = login
self.host.bridge.setParam("JabberID", login, "Connection", profile_key=self.current.profile)
self.host.bridge.setParam(
"JabberID", login, "Connection", profile_key=self.current.profile
)
log.info(u"login updated for profile [{}]".format(self.current.profile))
if password != self.current.password and self.current.password is not None:
self.current.password = password
self.host.bridge.setParam("Password", password, "Connection", profile_key=self.current.profile)
log.info(u"password updated for profile [{}]".format(self.current.profile))
self.host.bridge.setParam(
"Password", password, "Connection", profile_key=self.current.profile
)
log.info(
u"password updated for profile [{}]".format(self.current.profile)
)
## graphic updates (should probably be overriden in frontends) ##
def resetFields(self):
"""Set profile to None, and reset fields"""
self.current.profile=None
self.current.profile = None
self.setJID("")
self.setPassword("")
@ -222,7 +255,6 @@ class QuickProfileManager(object):
"""Update the list of profiles"""
raise NotImplementedError
def getJID(self):
"""Get current jid

View file

@ -21,6 +21,7 @@ from sat.core.i18n import _
from os.path import exists, splitext
from optparse import OptionParser
def getNewPath(path):
""" Check if path exists, and find a non existant path if needed """
idx = 2
@ -31,21 +32,23 @@ def getNewPath(path):
new_path = "%s_%d%s" % (root, idx, ext)
if not exists(new_path):
return new_path
idx+=1
idx += 1
def check_options():
"""Check command line options"""
usage = _("""
usage = _(
"""
%prog [options]
%prog --help for options list
""")
parser = OptionParser(usage=usage) # TODO: use argparse
"""
)
parser = OptionParser(usage=usage) # TODO: use argparse
parser.add_option("-p", "--profile", help=_("Select the profile to use"))
(options, args) = parser.parse_args()
if options.profile:
options.profile = options.profile.decode('utf-8')
options.profile = options.profile.decode("utf-8")
return options

View file

@ -18,19 +18,23 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from sat_frontends.quick_frontend.constants import Const as C
NEW_INSTANCE_SUFF = '_new_instance_'
NEW_INSTANCE_SUFF = "_new_instance_"
classes_map = {}
try:
# FIXME: to be removed when an acceptable solution is here
unicode('') # XXX: unicode doesn't exist in pyjamas
except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
unicode("") # XXX: unicode doesn't exist in pyjamas
except (
TypeError,
AttributeError,
): # Error raised is not the same depending on pyjsbuild options
unicode = str
@ -77,7 +81,9 @@ class QuickWidgetsManager(object):
except KeyError:
cls = class_
if cls is None:
raise exceptions.InternalError("There is not class registered for {}".format(class_))
raise exceptions.InternalError(
"There is not class registered for {}".format(class_)
)
return cls
def getRootHash(self, hash_):
@ -109,7 +115,10 @@ class QuickWidgetsManager(object):
filter_hash = None
for w_hash, w in widgets_map.iteritems():
if profiles is None or w.profiles.intersection(profiles):
if filter_hash is not None and self.getRootHash(w_hash) != filter_hash:
if (
filter_hash is not None
and self.getRootHash(w_hash) != filter_hash
):
continue
yield w
@ -161,39 +170,45 @@ class QuickWidgetsManager(object):
cls = self.getRealClass(class_)
## arguments management ##
_args = [self.host, target] + list(args) or [] # FIXME: check if it's really necessary to use optional args
_args = [self.host, target] + list(
args
) or [] # FIXME: check if it's really necessary to use optional args
_kwargs = kwargs or {}
if 'profiles' in _kwargs and 'profile' in _kwargs:
raise ValueError("You can't have 'profile' and 'profiles' keys at the same time")
if "profiles" in _kwargs and "profile" in _kwargs:
raise ValueError(
"You can't have 'profile' and 'profiles' keys at the same time"
)
try:
_kwargs['profiles'] = [_kwargs.pop('profile')]
_kwargs["profiles"] = [_kwargs.pop("profile")]
except KeyError:
if not 'profiles' in _kwargs:
_kwargs['profiles'] = None
if not "profiles" in _kwargs:
_kwargs["profiles"] = None
#on_new_widget tell what to do for the new widget creation
# on_new_widget tell what to do for the new widget creation
try:
on_new_widget = _kwargs.pop('on_new_widget')
on_new_widget = _kwargs.pop("on_new_widget")
except KeyError:
on_new_widget = C.WIDGET_NEW
#on_existing_widget tell what to do when the widget already exists
# on_existing_widget tell what to do when the widget already exists
try:
on_existing_widget = _kwargs.pop('on_existing_widget')
on_existing_widget = _kwargs.pop("on_existing_widget")
except KeyError:
on_existing_widget = C.WIDGET_KEEP
## we get the hash ##
try:
hash_ = _kwargs.pop('force_hash')
hash_ = _kwargs.pop("force_hash")
except KeyError:
hash_ = cls.getWidgetHash(target, _kwargs['profiles'])
hash_ = cls.getWidgetHash(target, _kwargs["profiles"])
## widget creation or retrieval ##
widgets_map = self._widgets.setdefault(cls.__name__, {}) # we sorts widgets by classes
widgets_map = self._widgets.setdefault(
cls.__name__, {}
) # we sorts widgets by classes
if not cls.SINGLE:
widget = None # if the class is not SINGLE, we always create a new widget
widget = None # if the class is not SINGLE, we always create a new widget
else:
try:
widget = widgets_map[hash_]
@ -225,16 +240,20 @@ class QuickWidgetsManager(object):
# we need to get rid of kwargs special options
new_kwargs = kwargs.copy()
try:
new_kwargs.pop('force_hash') # FIXME: we use pop instead of del here because pyjamas doesn't raise error on del
new_kwargs.pop(
"force_hash"
) # FIXME: we use pop instead of del here because pyjamas doesn't raise error on del
except KeyError:
pass
else:
raise ValueError("force_hash option can't be used with on_existing_widget=RECREATE")
raise ValueError(
"force_hash option can't be used with on_existing_widget=RECREATE"
)
new_kwargs['on_new_widget'] = on_new_widget
new_kwargs["on_new_widget"] = on_new_widget
# XXX: keep up-to-date if new special kwargs are added (i.e.: delete these keys here)
new_kwargs['on_existing_widget'] = C.WIDGET_RAISE
new_kwargs["on_existing_widget"] = C.WIDGET_RAISE
try:
recreateArgs = widget.recreateArgs
except AttributeError:
@ -243,18 +262,28 @@ class QuickWidgetsManager(object):
recreateArgs(args, new_kwargs)
hash_idx = 1
while True:
new_kwargs['force_hash'] = "{}{}{}".format(hash_, NEW_INSTANCE_SUFF, hash_idx)
new_kwargs["force_hash"] = "{}{}{}".format(
hash_, NEW_INSTANCE_SUFF, hash_idx
)
try:
widget = self.getOrCreateWidget(class_, target, *args, **new_kwargs)
widget = self.getOrCreateWidget(
class_, target, *args, **new_kwargs
)
except WidgetAlreadyExistsError:
hash_idx += 1
else:
log.debug(u"Widget already exists, a new one has been recreated with hash {}".format(new_kwargs['force_hash']))
log.debug(
u"Widget already exists, a new one has been recreated with hash {}".format(
new_kwargs["force_hash"]
)
)
break
elif callable(on_existing_widget):
on_existing_widget(widget)
else:
raise exceptions.InternalError("Unexpected on_existing_widget value ({})".format(on_existing_widget))
raise exceptions.InternalError(
"Unexpected on_existing_widget value ({})".format(on_existing_widget)
)
return widget
@ -286,9 +315,10 @@ class QuickWidgetsManager(object):
class QuickWidget(object):
"""generic widget base"""
SINGLE=True # if True, there can be only one widget per target(s)
PROFILES_MULTIPLE=False # If True, this widget can handle several profiles at once
PROFILES_ALLOW_NONE=False # If True, this widget can be used without profile
SINGLE = True # if True, there can be only one widget per target(s)
PROFILES_MULTIPLE = False # If True, this widget can handle several profiles at once
PROFILES_ALLOW_NONE = False # If True, this widget can be used without profile
def __init__(self, host, target, profiles=None):
"""
@ -317,7 +347,11 @@ class QuickWidget(object):
@property
def profile(self):
assert len(self.profiles) == 1 and not self.PROFILES_MULTIPLE and not self.PROFILES_ALLOW_NONE
assert (
len(self.profiles) == 1
and not self.PROFILES_MULTIPLE
and not self.PROFILES_ALLOW_NONE
)
return list(self.profiles)[0]
def addTarget(self, target):
@ -350,7 +384,7 @@ class QuickWidget(object):
@param profiles: profile(s) associated to target, see __init__ docstring
@return: a hash (can correspond to one or many targets or profiles, depending of widget class)
"""
return unicode(target) # by defaut, there is one hash for one target
return unicode(target) # by defaut, there is one hash for one target
def onDelete(self, *args, **kwargs):
"""Called when a widget is being deleted
@ -360,4 +394,3 @@ class QuickWidget(object):
"""
log.debug(u"widget {} deleted".format(self))
return True