core, setup: huge cleaning:
- moved directories from src and frontends/src to sat and sat_frontends, which is the recommanded naming convention - move twisted directory to root - removed all hacks from setup.py, and added missing dependencies, it is now clean - use https URL for website in setup.py - removed "Environment :: X11 Applications :: GTK", as wix is deprecated and removed - renamed sat.sh to sat and fixed its installation - added python_requires to specify Python version needed - replaced glib2reactor which use deprecated code by gtk3reactor sat can now be installed directly from virtualenv without using --system-site-packages anymore \o/
This commit is contained in:
parent
4afd2ff26f
commit
80ef13612b
14 changed files with 42 additions and 269 deletions
0
sat_frontends/quick_frontend/__init__.py
Normal file
0
sat_frontends/quick_frontend/__init__.py
Normal file
91
sat_frontends/quick_frontend/constants.py
Normal file
91
sat_frontends/quick_frontend/constants.py
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Primitivus: a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from sat.core import constants
|
||||
from sat.core.i18n import _
|
||||
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"))])
|
||||
|
||||
# from plugin_misc_text_syntaxes
|
||||
SYNTAX_XHTML = "XHTML"
|
||||
SYNTAX_CURRENT = "@CURRENT@"
|
||||
SYNTAX_TEXT = "text"
|
||||
|
||||
# XMLUI
|
||||
SAT_FORM_PREFIX = "SAT_FORM_"
|
||||
SAT_PARAM_SEPARATOR = "_XMLUI_PARAM_" # used to have unique elements names
|
||||
XMLUI_STATUS_VALIDATED = "validated"
|
||||
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_PROFILE = 'profile' # used in handler to track where the contact is coming from
|
||||
CONTACT_SPECIAL_ALLOWED = (CONTACT_SPECIAL_GROUP,) # allowed values for special flag
|
||||
CONTACT_DATA_FORBIDDEN = {CONTACT_GROUPS, CONTACT_RESOURCES, CONTACT_MAIN_RESOURCE, CONTACT_SELECTED, CONTACT_PROFILE} # set of forbidden names for contact data
|
||||
|
||||
# Chats
|
||||
CHAT_STATE_ICON = {
|
||||
"": u" ",
|
||||
"active": u'✔',
|
||||
"inactive": u'☄',
|
||||
"gone": u'✈',
|
||||
"composing": u'✎',
|
||||
"paused": u"…"
|
||||
}
|
||||
|
||||
# Blogs
|
||||
ENTRY_MODE_TEXT = "text"
|
||||
ENTRY_MODE_RICH = "rich"
|
||||
ENTRY_MODE_XHTML = "xhtml"
|
||||
|
||||
# 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'
|
||||
|
||||
# Updates (generic)
|
||||
UPDATE_DELETE = 'DELETE'
|
||||
UPDATE_MODIFY = 'MODIFY'
|
||||
UPDATE_ADD = 'ADD'
|
||||
UPDATE_SELECTION = 'SELECTION'
|
||||
UPDATE_STRUCTURE = 'STRUCTURE' # high level update (i.e. not item level but organisation of items)
|
||||
|
||||
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_ALL = (NOTIFY_MESSAGE, NOTIFY_MENTION, NOTIFY_PROGRESS_END, NOTIFY_GENERIC)
|
||||
975
sat_frontends/quick_frontend/quick_app.py
Normal file
975
sat_frontends/quick_frontend/quick_app.py
Normal file
|
|
@ -0,0 +1,975 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
|
||||
from sat.core.i18n import _
|
||||
from sat.core import exceptions
|
||||
from sat.tools import trigger
|
||||
from sat.tools.common import data_format
|
||||
|
||||
from sat_frontends.tools import jid
|
||||
from sat_frontends.quick_frontend import quick_widgets
|
||||
from sat_frontends.quick_frontend import quick_menus
|
||||
from sat_frontends.quick_frontend import quick_blog
|
||||
from sat_frontends.quick_frontend import quick_chat, quick_games
|
||||
from sat_frontends.quick_frontend import quick_contact_list
|
||||
from sat_frontends.quick_frontend.constants import Const as C
|
||||
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
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 = 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
|
||||
bridge = None
|
||||
# cache_keys_to_get = ['avatar']
|
||||
|
||||
def __init__(self, profile):
|
||||
self.profile = profile
|
||||
self.connected = False
|
||||
self.whoami = None
|
||||
self.notifications = {} # key: bare jid or '' for general, value: notif data
|
||||
|
||||
@property
|
||||
def autodisconnect(self):
|
||||
try:
|
||||
autodisconnect = self._autodisconnect
|
||||
except AttributeError:
|
||||
autodisconnect = False
|
||||
return autodisconnect
|
||||
|
||||
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)
|
||||
|
||||
def _plug_profile_jid(self, jid_s):
|
||||
self.whoami = jid.JID(jid_s) # resource might change after the connection
|
||||
self.bridge.isConnected(self.profile, callback=self._plug_profile_isconnected)
|
||||
|
||||
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_))
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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())
|
||||
else:
|
||||
self._plug_profile_afterconnect()
|
||||
|
||||
def _plug_profile_afterconnect(self):
|
||||
# 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)
|
||||
|
||||
def _plug_profile_getFeaturesEb(self, failure):
|
||||
log.error(u"Couldn't get features: {}".format(failure))
|
||||
self._plug_profile_getFeaturesCb({})
|
||||
|
||||
def _plug_profile_getFeaturesCb(self, features):
|
||||
self.host.features = features
|
||||
# FIXME: we don't use cached value at the moment, but keep the code for later use
|
||||
# it was previously used for avatars, but as we don't get full path here, it's better to request later
|
||||
# self.host.bridge.getEntitiesData([], ProfileManager.cache_keys_to_get, profile=self.profile, callback=self._plug_profile_gotCachedValues, errback=self._plug_profile_failedCachedValues)
|
||||
self._plug_profile_gotCachedValues({})
|
||||
|
||||
def _plug_profile_failedCachedValues(self, failure):
|
||||
log.error(u"Couldn't get cached values: {}".format(failure))
|
||||
self._plug_profile_gotCachedValues({})
|
||||
|
||||
def _plug_profile_gotCachedValues(self, cached_values):
|
||||
# add the contact list and its listener
|
||||
contact_list = self.host.contact_lists.addProfile(self.profile)
|
||||
|
||||
for entity_s, data in cached_values.iteritems():
|
||||
for key, value in data.iteritems():
|
||||
self.host.entityDataUpdatedHandler(entity_s, key, value, self.profile)
|
||||
|
||||
if not self.connected:
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
def _plug_profile_gotRoomsJoined(self, rooms_args):
|
||||
#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)
|
||||
|
||||
def _plug_profile_gotPresences(self, presences):
|
||||
def gotEntityData(data, contact):
|
||||
for key in ('avatar', 'nick'):
|
||||
if key in data:
|
||||
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
|
||||
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)))
|
||||
|
||||
# At this point, profile should be fully plugged
|
||||
# and we launch frontend specific method
|
||||
self.host.profilePlugged(self.profile)
|
||||
|
||||
def _getParamError(self, failure):
|
||||
log.error(_("Can't get profile parameter: {msg}").format(msg=failure))
|
||||
|
||||
|
||||
class ProfilesManager(object):
|
||||
"""Class managing collection of profiles"""
|
||||
|
||||
def __init__(self):
|
||||
self._profiles = {}
|
||||
|
||||
def __contains__(self, profile):
|
||||
return profile in self._profiles
|
||||
|
||||
def __iter__(self):
|
||||
return self._profiles.iterkeys()
|
||||
|
||||
def __getitem__(self, profile):
|
||||
return self._profiles[profile]
|
||||
|
||||
def __len__(self):
|
||||
return len(self._profiles)
|
||||
|
||||
def iteritems(self):
|
||||
return self._profiles.iteritems()
|
||||
|
||||
def plug(self, profile):
|
||||
if profile in self._profiles:
|
||||
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))
|
||||
|
||||
# remove the contact list and its listener
|
||||
host = self._profiles[profile].host
|
||||
host.contact_lists[profile].unplug()
|
||||
|
||||
del self._profiles[profile]
|
||||
|
||||
def chooseOneProfile(self):
|
||||
return self._profiles.keys()[0]
|
||||
|
||||
|
||||
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
|
||||
|
||||
def __init__(self, bridge_factory, xmlui, check_options=None, connect_bridge=True):
|
||||
"""Create a frontend application
|
||||
|
||||
@param bridge_factory: method to use to create the Bridge
|
||||
@param xmlui: xmlui module
|
||||
@param check_options: method to call to check options (usually command line arguments)
|
||||
"""
|
||||
self.xmlui = xmlui
|
||||
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.contact_lists = quick_contact_list.QuickContactListHandler(self)
|
||||
self.widgets = quick_widgets.QuickWidgetsManager(self)
|
||||
if check_options is not None:
|
||||
self.options = check_options()
|
||||
else:
|
||||
self.options = None
|
||||
|
||||
# widgets
|
||||
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
|
||||
|
||||
# triggers
|
||||
self.trigger = trigger.TriggerManager() # trigger are used to change the default behaviour
|
||||
|
||||
## bridge ##
|
||||
self.bridge = bridge_factory()
|
||||
ProfileManager.bridge = self.bridge
|
||||
if connect_bridge:
|
||||
self.connectBridge()
|
||||
|
||||
self._notif_id = 0
|
||||
self._notifications = OrderedDict()
|
||||
self.features = None
|
||||
|
||||
def connectBridge(self):
|
||||
self.bridge.bridgeConnect(callback=self._bridgeCb, errback=self._bridgeEb)
|
||||
|
||||
def onBridgeConnected(self):
|
||||
pass
|
||||
|
||||
def _bridgeCb(self):
|
||||
self.registerSignal("connected")
|
||||
self.registerSignal("disconnected")
|
||||
self.registerSignal("actionNew")
|
||||
self.registerSignal("newContact")
|
||||
self.registerSignal("messageNew")
|
||||
self.registerSignal("presenceUpdate")
|
||||
self.registerSignal("subscribe")
|
||||
self.registerSignal("paramUpdate")
|
||||
self.registerSignal("contactDeleted")
|
||||
self.registerSignal("entityDataUpdated")
|
||||
self.registerSignal("progressStarted")
|
||||
self.registerSignal("progressFinished")
|
||||
self.registerSignal("progressError")
|
||||
self.registerSignal("mucRoomJoined", iface="plugin")
|
||||
self.registerSignal("mucRoomLeft", iface="plugin")
|
||||
self.registerSignal("mucRoomUserChangedNick", iface="plugin")
|
||||
self.registerSignal("mucRoomNewSubject", iface="plugin")
|
||||
self.registerSignal("chatStateReceived", iface="plugin")
|
||||
self.registerSignal("messageState", iface="plugin")
|
||||
self.registerSignal("psEvent", iface="plugin")
|
||||
|
||||
# FIXME: do it dynamically
|
||||
quick_games.Tarot.registerSignals(self)
|
||||
quick_games.Quiz.registerSignals(self)
|
||||
quick_games.Radiocol.registerSignals(self)
|
||||
self.onBridgeConnected()
|
||||
|
||||
def _bridgeEb(self, failure):
|
||||
if isinstance(failure, exceptions.BridgeExceptionNoService):
|
||||
print(_(u"Can't connect to SàT backend, are you sure it's launched ?"))
|
||||
sys.exit(1)
|
||||
elif isinstance(failure, exceptions.BridgeInitError):
|
||||
print(_(u"Can't init bridge"))
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(_(u"Error while initialising bridge: {}".format(failure)))
|
||||
|
||||
@property
|
||||
def current_profile(self):
|
||||
"""Profile that a user would expect to use"""
|
||||
try:
|
||||
return self.selected_widget.profile
|
||||
except (TypeError, AttributeError):
|
||||
return self.profiles.chooseOneProfile()
|
||||
|
||||
@property
|
||||
def visible_widgets(self):
|
||||
"""widgets currently visible (must be implemented by frontend)
|
||||
|
||||
@return (iter[QuickWidget]): iterable on visible widgets
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
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
|
||||
@param handler (instancemethod): method to call when the signal arrive, None for calling an automatically named handler (function_name + 'Handler')
|
||||
@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))
|
||||
if handler is None:
|
||||
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')
|
||||
if profile is None:
|
||||
if not args:
|
||||
raise exceptions.ProfileNotSetError
|
||||
profile = args[-1]
|
||||
if profile is not None:
|
||||
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))
|
||||
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):
|
||||
"""Add a listener for an event
|
||||
|
||||
/!\ don't forget to remove listener when not used anymore (e.g. if you delete a widget)
|
||||
@param type_: type of event, can be:
|
||||
- avatar: called when avatar data is updated
|
||||
args: (entity, avatar file, profile)
|
||||
- nick: called when nick data is updated
|
||||
args: (entity, new_nick, profile)
|
||||
- presence: called when a presence is received
|
||||
args: (entity, show, priority, statuses, profile)
|
||||
- notification: called when a new notification is emited
|
||||
args: (entity, notification_data, profile)
|
||||
- notification_clear: called when notifications are cleared
|
||||
args: (entity, type_, profile)
|
||||
- menu: called when a menu item is added or removed
|
||||
args: (type_, path, path_i18n, item) were values are:
|
||||
type_: same as in [sat.core.sat_main.SAT.importMenu]
|
||||
path: same as in [sat.core.sat_main.SAT.importMenu]
|
||||
path_i18n: translated path (or None if the item is removed)
|
||||
item: instance of quick_menus.MenuItemBase or None if the item is removed
|
||||
- gotMenus: called only once when menu are available (no arg)
|
||||
- progressFinished: called when a progressing action has just finished
|
||||
args: (progress_id, metadata, profile)
|
||||
- progressError: called when a progressing action failed
|
||||
args: (progress_id, error_msg, profile):
|
||||
@param callback: method to call on event
|
||||
@param profiles_filter (set[unicode]): if set and not empty, the
|
||||
listener will be callable only by one of the given profiles.
|
||||
"""
|
||||
assert type_ in C.LISTENERS
|
||||
self._listeners.setdefault(type_, OrderedDict())[callback] = profiles_filter
|
||||
|
||||
def removeListener(self, type_, callback):
|
||||
"""Remove a callback from listeners
|
||||
|
||||
@param type_: same as for [addListener]
|
||||
@param callback: callback to remove
|
||||
"""
|
||||
assert type_ in C.LISTENERS
|
||||
self._listeners[type_].pop(callback)
|
||||
|
||||
def callListeners(self, type_, *args, **kwargs):
|
||||
"""Call the methods which listen type_ event. If a profiles filter has
|
||||
been register with a listener and profile argument is not None, the
|
||||
listener will be called only if profile is in the profiles filter list.
|
||||
|
||||
@param type_: same as for [addListener]
|
||||
@param *args: arguments sent to callback
|
||||
@param **kwargs: keywords argument, mainly used to pass "profile" when needed
|
||||
"""
|
||||
assert type_ in C.LISTENERS
|
||||
try:
|
||||
listeners = self._listeners[type_]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
profile = kwargs.get("profile")
|
||||
for listener, profiles_filter in listeners.iteritems():
|
||||
if profile is None or not profiles_filter or profile in profiles_filter:
|
||||
listener(*args, **kwargs)
|
||||
|
||||
def check_profile(self, profile):
|
||||
"""Tell if the profile is currently followed by the application, and ready"""
|
||||
return profile in self.ready_profiles
|
||||
|
||||
def postInit(self, profile_manager):
|
||||
"""Must be called after initialization is done, do all automatic task (auto plug profile)
|
||||
|
||||
@param profile_manager: instance of a subclass of Quick_frontend.QuickProfileManager
|
||||
"""
|
||||
if self.options and self.options.profile:
|
||||
profile_manager.autoconnect([self.options.profile])
|
||||
|
||||
def profilePlugged(self, profile):
|
||||
"""Method called when the profile is fully plugged, to launch frontend specific workflow
|
||||
|
||||
/!\ if you override the method and don't call the parent, be sure to add the profile to ready_profiles !
|
||||
if you don't, all signals will stay in cache
|
||||
|
||||
@param profile(unicode): %(doc_profile)s
|
||||
"""
|
||||
self._plugs_in_progress.remove(profile)
|
||||
self.ready_profiles.add(profile)
|
||||
|
||||
# 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))
|
||||
handler(*args, **kwargs)
|
||||
|
||||
self.callListeners('profilePlugged', profile=profile)
|
||||
if not self._plugs_in_progress:
|
||||
self.contact_lists.lockUpdate(False)
|
||||
|
||||
def connect(self, profile, callback=None, errback=None):
|
||||
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 = ''
|
||||
try:
|
||||
message = failure.message
|
||||
except AttributeError:
|
||||
message = 'error'
|
||||
try:
|
||||
fullname = failure.fullname
|
||||
except AttributeError:
|
||||
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.bridge.connect(profile, callback=callback, errback=errback)
|
||||
|
||||
def plug_profiles(self, profiles):
|
||||
"""Tell application which profiles must be used
|
||||
|
||||
@param profiles: list of valid profile names
|
||||
"""
|
||||
self.contact_lists.lockUpdate()
|
||||
self._plugs_in_progress.update(profiles)
|
||||
self.plugging_profiles()
|
||||
for profile in profiles:
|
||||
self.profiles.plug(profile)
|
||||
|
||||
def plugging_profiles(self):
|
||||
"""Method to subclass to manage frontend specific things to do
|
||||
|
||||
will be called when profiles are choosen and are to be plugged soon
|
||||
"""
|
||||
pass
|
||||
|
||||
def unplug_profile(self, profile):
|
||||
"""Tell the application to not follow anymore the profile"""
|
||||
if not profile in self.profiles:
|
||||
raise ValueError("The profile [{}] is not plugged".format(profile))
|
||||
self.profiles.unplug(profile)
|
||||
|
||||
def clear_profile(self):
|
||||
self.profiles.clear()
|
||||
|
||||
def newWidget(self, widget):
|
||||
raise NotImplementedError
|
||||
|
||||
# bridge signals hanlers
|
||||
|
||||
def connectedHandler(self, profile, jid_s):
|
||||
"""Called when the connection is made.
|
||||
|
||||
@param jid_s (unicode): the JID that we were assigned by the server,
|
||||
as the resource might differ from the JID we asked for.
|
||||
"""
|
||||
log.debug(_("Connected"))
|
||||
self.profiles[profile].whoami = jid.JID(jid_s)
|
||||
self.setPresenceStatus(profile=profile)
|
||||
self.contact_lists[profile].fill()
|
||||
|
||||
def disconnectedHandler(self, profile):
|
||||
"""called when the connection is closed"""
|
||||
log.debug(_("Disconnected"))
|
||||
self.contact_lists[profile].disconnect()
|
||||
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)
|
||||
|
||||
def newContactHandler(self, jid_s, attributes, groups, profile):
|
||||
entity = jid.JID(jid_s)
|
||||
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):
|
||||
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):
|
||||
return
|
||||
|
||||
from_me = from_jid.bare == self.profiles[profile].whoami.bare
|
||||
target = to_jid if from_me else from_jid
|
||||
contact_list = self.contact_lists[profile]
|
||||
# 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)
|
||||
|
||||
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)
|
||||
|
||||
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):
|
||||
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
|
||||
if errback is None:
|
||||
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):
|
||||
return
|
||||
|
||||
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):
|
||||
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})
|
||||
entity = jid.JID(entity_s)
|
||||
|
||||
if entity == self.profiles[profile].whoami:
|
||||
if show == C.PRESENCE_UNAVAILABLE:
|
||||
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)
|
||||
|
||||
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()))
|
||||
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.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})
|
||||
room_jid = jid.JID(room_jid_s)
|
||||
chat_widget = self.widgets.getWidget(quick_chat.QuickChat, room_jid, profile)
|
||||
if chat_widget:
|
||||
self.widgets.deleteWidget(chat_widget)
|
||||
self.contact_lists[profile].removeContact(room_jid)
|
||||
|
||||
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.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})
|
||||
|
||||
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.setSubject(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.
|
||||
|
||||
@param from_jid_s (unicode): JID of a contact or C.ENTITY_ALL
|
||||
@param state (unicode): new state
|
||||
@param profile (unicode): current profile
|
||||
"""
|
||||
from_jid = jid.JID(from_jid_s)
|
||||
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):
|
||||
"""Trigger an event notification
|
||||
|
||||
@param type_(unicode): notifation kind,
|
||||
one of C.NOTIFY_* constant or any custom type specific to frontend
|
||||
@param entity(jid.JID, None): entity involved in the notification
|
||||
if entity is in contact list, a indicator may be added in front of it
|
||||
@param message(unicode, None): message of the notification
|
||||
@param subject(unicode, None): subject of the notification
|
||||
@param callback(callable, None): method to call when notification is selected
|
||||
@param cb_args(list, None): list of args for callback
|
||||
@param widget(object, None): widget where the notification happened
|
||||
"""
|
||||
assert type_ in C.NOTIFY_ALL
|
||||
notif_dict = self.profiles[profile].notifications
|
||||
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,
|
||||
}
|
||||
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)
|
||||
|
||||
def getNotifs(self, entity=None, type_=None, exact_jid=None, profile=C.PROF_KEY_NONE):
|
||||
"""return notifications for given entity
|
||||
|
||||
@param entity(jid.JID, None, C.ENTITY_ALL): jid of the entity to check
|
||||
bare jid to get all notifications, full jid to filter on resource
|
||||
None to get general notifications
|
||||
C.ENTITY_ALL to get all notifications
|
||||
@param type_(unicode, None): notification type to filter
|
||||
None to get all notifications
|
||||
@param exact_jid(bool, None): if True, only return notifications from
|
||||
exact entity jid (i.e. not including other resources)
|
||||
None for automatic selection (True for full jid, False else)
|
||||
False to get resources notifications
|
||||
False doesn't do anything if entity is not a bare jid
|
||||
@return (iter[dict]): notifications
|
||||
"""
|
||||
main_notif_dict = self.profiles[profile].notifications
|
||||
|
||||
if entity is C.ENTITY_ALL:
|
||||
selected_notifs = main_notif_dict.itervalues()
|
||||
exact_jid = False
|
||||
else:
|
||||
if entity is None:
|
||||
key = ''
|
||||
exact_jid = False
|
||||
else:
|
||||
key = entity.bare
|
||||
if exact_jid is None:
|
||||
exact_jid = bool(entity.resource)
|
||||
selected_notifs = (main_notif_dict.setdefault(key, {}),)
|
||||
|
||||
for notifs_from_select in selected_notifs:
|
||||
|
||||
if type_ is None:
|
||||
type_notifs = notifs_from_select.itervalues()
|
||||
else:
|
||||
type_notifs = (notifs_from_select.get(type_, []),)
|
||||
|
||||
for notifs in type_notifs:
|
||||
for notif in notifs:
|
||||
if exact_jid and notif['entity'] != entity:
|
||||
continue
|
||||
yield notif
|
||||
|
||||
def clearNotifs(self, entity, type_=None, profile=C.PROF_KEY_NONE):
|
||||
"""return notifications for given entity
|
||||
|
||||
@param entity(jid.JID, None): bare jid of the entity to check
|
||||
None to clear general notifications (but keep entities ones)
|
||||
@param type_(unicode, None): notification type to filter
|
||||
None to clear all notifications
|
||||
@return (list[dict]): list of notifications
|
||||
"""
|
||||
notif_dict = self.profiles[profile].notifications
|
||||
key = '' if entity is None else entity.bare
|
||||
try:
|
||||
if type_ is None:
|
||||
del notif_dict[key]
|
||||
else:
|
||||
del notif_dict[key][type_]
|
||||
except KeyError:
|
||||
return
|
||||
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.
|
||||
|
||||
@param category(unicode): event category (e.g. "PEP", "MICROBLOG")
|
||||
@param service_s (unicode): pubsub service
|
||||
@param node (unicode): pubsub node
|
||||
@param event_type (unicode): event type (one of C.PUBLISH, C.RETRACT, C.DELETE)
|
||||
@param data (dict): event data
|
||||
"""
|
||||
service_s = jid.JID(service_s)
|
||||
|
||||
if category == C.PS_MICROBLOG and self.MB_HANDLER:
|
||||
if event_type == C.PS_PUBLISH:
|
||||
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)
|
||||
|
||||
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']
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
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)
|
||||
pass
|
||||
else:
|
||||
log.warning("Unmanaged PubSub event type {}".format(event_type))
|
||||
|
||||
def progressStartedHandler(self, pid, metadata, profile):
|
||||
log.info(u"Progress {} started".format(pid))
|
||||
|
||||
def progressFinishedHandler(self, pid, metadata, profile):
|
||||
log.info(u"Progress {} finished".format(pid))
|
||||
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)
|
||||
|
||||
def _subscribe_cb(self, answer, data):
|
||||
entity, profile = data
|
||||
type_ = "subscribed" if answer else "unsubscribed"
|
||||
self.bridge.subscription(type_, unicode(entity.bare), profile_key=profile)
|
||||
|
||||
def subscribeHandler(self, type, raw_jid, profile):
|
||||
"""Called when a subsciption management signal is received"""
|
||||
entity = jid.JID(raw_jid)
|
||||
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(_("The contact %s has accepted your subscription") % entity.bare, _('Subscription confirmation'))
|
||||
elif type == "unsubscribed":
|
||||
# this is a subscription refusal, we just have to inform user
|
||||
self.showDialog(_("The contact %s has refused your subscription") % entity.bare, _('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(_("The contact %s wants to subscribe to your presence.\nDo you accept ?") % 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):
|
||||
raise NotImplementedError
|
||||
|
||||
def showAlert(self, message):
|
||||
pass #FIXME
|
||||
|
||||
def dialogFailure(self, failure):
|
||||
log.warning(u"Failure: {}".format(failure))
|
||||
|
||||
def progressIdHandler(self, progress_id, profile):
|
||||
"""Callback used when an action result in a progress id"""
|
||||
log.info(u"Progress ID received: {}".format(progress_id))
|
||||
|
||||
def isHidden(self):
|
||||
"""Tells if the frontend window is hidden.
|
||||
|
||||
@return bool
|
||||
"""
|
||||
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})
|
||||
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):
|
||||
self.contact_lists[profile].showOfflineContacts(C.bool(value))
|
||||
elif (namespace, name) == ('General', C.SHOW_EMPTY_GROUPS):
|
||||
self.contact_lists[profile].showEmptyGroups(C.bool(value))
|
||||
|
||||
def contactDeletedHandler(self, jid_s, profile):
|
||||
target = jid.JID(jid_s)
|
||||
self.contact_lists[profile].removeContact(target)
|
||||
|
||||
def entityDataUpdatedHandler(self, entity_s, key, value, profile):
|
||||
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)
|
||||
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):
|
||||
"""Handle backend action
|
||||
|
||||
@param action_data(dict): action dict as sent by launchAction or returned by an UI action
|
||||
@param callback(None, callback): if not None, callback to use on XMLUI answer
|
||||
@param ui_show_cb(None, callback): if not None, method to call to show the XMLUI
|
||||
@param user_action(bool): if True, the action is a result of a user interaction
|
||||
else the action come from backend direclty (i.e. actionNew)
|
||||
"""
|
||||
try:
|
||||
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)
|
||||
if ui_show_cb is None:
|
||||
ui.show()
|
||||
else:
|
||||
ui_show_cb(ui)
|
||||
|
||||
try:
|
||||
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_")}
|
||||
|
||||
if action_data:
|
||||
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:
|
||||
self.actionManager(data, profile=profile)
|
||||
else:
|
||||
callback(data=data, cb_id=callback_id, profile=profile)
|
||||
|
||||
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
|
||||
@param data: data needed only for certain actions
|
||||
@param callback(callable, None): will be called with the resut
|
||||
if None, self.actionManager will be called
|
||||
else the callable will be called with the following kw parameters:
|
||||
- data: action_data
|
||||
- cb_id: callback id
|
||||
- profile: %(doc_profile)s
|
||||
@param profile: %(doc_profile)s
|
||||
|
||||
"""
|
||||
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)
|
||||
|
||||
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
|
||||
@param path(iterable[unicode]): path to the menu
|
||||
@param data: data needed only for certain actions
|
||||
@param callback(callable, None): will be called with the resut
|
||||
if None, self.actionManager will be called
|
||||
else the callable will be called with the following kw parameters:
|
||||
- data: action_data
|
||||
- cb_id: (menu_type, path) tuple
|
||||
- profile: %(doc_profile)s
|
||||
@param profile: %(doc_profile)s
|
||||
|
||||
"""
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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):
|
||||
"""return avatar path for an entity
|
||||
|
||||
@param entity(jid.JID): entity to get avatar from
|
||||
@param cache_only(bool): if False avatar will be requested if not in cache
|
||||
with current vCard based implementation, it's better to keep True
|
||||
except if we request avatars for roster items
|
||||
@param hash_only(bool): if True avatar hash is returned, else full path
|
||||
@param ignore_cache(bool): if False, won't check local cache and will request backend in every case
|
||||
@return (unicode, None): avatar full path (None if no avatar found)
|
||||
"""
|
||||
contact_list = self.contact_lists[profile]
|
||||
if ignore_cache:
|
||||
avatar = None
|
||||
else:
|
||||
avatar = contact_list.getCache(entity, "avatar", bare_default=None)
|
||||
if avatar is None:
|
||||
self.bridge.avatarGet(
|
||||
unicode(entity),
|
||||
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))
|
||||
# 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", "")
|
||||
return avatar
|
||||
|
||||
def getDefaultAvatar(self, entity=None):
|
||||
"""return default avatar to use with given entity
|
||||
|
||||
must be implemented by frontend
|
||||
@param entity(jid.JID): entity for which a default avatar is needed
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def disconnect(self, profile):
|
||||
log.info("disconnecting")
|
||||
self.callListeners('disconnect', profile=profile)
|
||||
self.bridge.disconnect(profile)
|
||||
|
||||
def onExit(self):
|
||||
"""Must be called when the frontend is terminating"""
|
||||
to_unplug = []
|
||||
for profile, profile_manager in self.profiles.iteritems():
|
||||
if profile_manager.connected and profile_manager.autodisconnect:
|
||||
#The user wants autodisconnection
|
||||
self.disconnect(profile)
|
||||
to_unplug.append(profile)
|
||||
for profile in to_unplug:
|
||||
self.unplug_profile(profile)
|
||||
471
sat_frontends/quick_frontend/quick_blog.py
Normal file
471
sat_frontends/quick_frontend/quick_blog.py
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2011-2018 Jérôme Poisson <goffi@goffi.org>
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# from sat.core.i18n import _, D_
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
|
||||
|
||||
from sat_frontends.quick_frontend.constants import Const as C
|
||||
from sat_frontends.quick_frontend import quick_widgets
|
||||
from sat_frontends.tools import jid
|
||||
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 = str
|
||||
|
||||
ENTRY_CLS = None
|
||||
COMMENTS_CLS = None
|
||||
|
||||
|
||||
class Item(object):
|
||||
"""Manage all (meta)data of an item"""
|
||||
|
||||
def __init__(self, data):
|
||||
"""
|
||||
@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.title_rich = None
|
||||
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']
|
||||
try:
|
||||
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'])
|
||||
except KeyError:
|
||||
self.author_verified = False
|
||||
|
||||
try:
|
||||
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)
|
||||
except KeyError:
|
||||
self.published = None
|
||||
|
||||
self.comments = data.get('comments')
|
||||
try:
|
||||
self.comments_service = jid.JID(data['comments_service'])
|
||||
except KeyError:
|
||||
self.comments_service = None
|
||||
self.comments_node = data.get('comments_node')
|
||||
|
||||
# def loadComments(self):
|
||||
# """Load all the comments"""
|
||||
# index = str(main_entry.comments_count - main_entry.hidden_count)
|
||||
# rsm = {'max': str(main_entry.hidden_count), 'index': index}
|
||||
# self.host.bridge.call('getMblogComments', self.mblogsInsert, main_entry.comments_service, main_entry.comments_node, rsm)
|
||||
|
||||
|
||||
class EntriesManager(object):
|
||||
"""Class which manages list of (micro)blog entries"""
|
||||
|
||||
def __init__(self, manager):
|
||||
"""
|
||||
@param manager (EntriesManager, None): parent EntriesManager
|
||||
must be None for QuickBlog (and only for QuickBlog)
|
||||
"""
|
||||
self.manager = manager
|
||||
if manager is None:
|
||||
self.blog = self
|
||||
else:
|
||||
self.blog = manager.blog
|
||||
self.entries = []
|
||||
self.edit_entry = None
|
||||
|
||||
@property
|
||||
def level(self):
|
||||
"""indicate how deep is this entry in the tree
|
||||
|
||||
if level == -1, we have a QuickBlog
|
||||
if level == 0, we have a main item
|
||||
else we have a comment
|
||||
"""
|
||||
level = -1
|
||||
manager = self.manager
|
||||
while manager is not None:
|
||||
level += 1
|
||||
manager = manager.manager
|
||||
return level
|
||||
|
||||
def _addMBItems(self, items_tuple, service=None, node=None):
|
||||
"""Add Microblog items to this panel
|
||||
update is NOT called after addition
|
||||
|
||||
@param items_tuple(tuple): (items_data,items_metadata) tuple as returned by mbGet
|
||||
"""
|
||||
items, metadata = items_tuple
|
||||
for item in items:
|
||||
self.addEntry(item, service=service, node=node, with_update=False)
|
||||
|
||||
def _addMBItemsWithComments(self, items_tuple, service=None, node=None):
|
||||
"""Add Microblog items to this panel
|
||||
update is NOT called after addition
|
||||
|
||||
@param items_tuple(tuple): (items_data,items_metadata) tuple as returned by mbGet
|
||||
"""
|
||||
items, metadata = items_tuple
|
||||
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):
|
||||
"""Add a microblog entry
|
||||
|
||||
@param editable (bool): True if the entry can be modified
|
||||
@param item (dict, None): blog item data, or None for an empty entry
|
||||
@param comments (list, None): list of comments data if available
|
||||
@param service (jid.JID, None): service where the entry is coming from
|
||||
@param service (unicode, None): node hosting the entry
|
||||
@param with_update (bool): if True, udpate is called with the new entry
|
||||
@param edit_entry(bool): if True, will be in self.edit_entry instead of
|
||||
self.entries, so it can be managed separately (e.g. first or last
|
||||
entry regardless of sorting)
|
||||
"""
|
||||
new_entry = ENTRY_CLS(self, item, comments, service=service, node=node)
|
||||
new_entry.setEditable(editable)
|
||||
if edit_entry:
|
||||
self.edit_entry = new_entry
|
||||
else:
|
||||
self.entries.append(new_entry)
|
||||
if with_update:
|
||||
self.update()
|
||||
return new_entry
|
||||
|
||||
def update(self, entry=None):
|
||||
"""Update the display with entries
|
||||
|
||||
@param entry (Entry, None): if not None, must be the new entry.
|
||||
If None, all the items will be checked to update the display
|
||||
"""
|
||||
# update is separated from addEntry to allow adding
|
||||
# several entries at once, and updating at the end
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
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):
|
||||
"""
|
||||
@param blog(QuickBlog): the parent QuickBlog
|
||||
@param manager(EntriesManager): the parent EntriesManager
|
||||
@param item_data(dict, None): dict containing the blog item data, or None for an empty entry
|
||||
@param comments_data(list, None): list of comments data
|
||||
"""
|
||||
assert manager is not None
|
||||
EntriesManager.__init__(self, manager)
|
||||
self.service = service
|
||||
self.node = node
|
||||
self.editable = False
|
||||
self.reset(item_data)
|
||||
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)
|
||||
|
||||
def reset(self, item_data):
|
||||
"""Reset the entry with given data
|
||||
|
||||
used during init (it's a set and not a reset then)
|
||||
or later (e.g. message sent, or cancellation of an edition
|
||||
@param idem_data(dict, None): data as in __init__
|
||||
"""
|
||||
if item_data is None:
|
||||
self.new = True
|
||||
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
|
||||
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
|
||||
|
||||
def refresh(self):
|
||||
"""Refresh the display when data have been modified"""
|
||||
pass
|
||||
|
||||
def setEditable(self, editable=True):
|
||||
"""tell if the entry can be edited or not
|
||||
|
||||
@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
|
||||
raise NotImplementedError
|
||||
|
||||
def addComments(self, comments_data):
|
||||
"""Add comments to this entry by calling addEntry repeatidly
|
||||
|
||||
@param comments_data(tuple): data as returned by mbGetFromMany*RTResults
|
||||
"""
|
||||
# TODO: manage seperator between comments of coming from different services/nodes
|
||||
for data in comments_data:
|
||||
service, node, failure, comments, metadata = data
|
||||
for comment in comments:
|
||||
if not failure:
|
||||
self.addEntry(comment, service=jid.JID(service), node=node)
|
||||
else:
|
||||
log.warning("getting comment failed: {}".format(failure))
|
||||
self.update()
|
||||
|
||||
def send(self):
|
||||
"""Send entry according to parent QuickBlog configuration and current level"""
|
||||
|
||||
# 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')
|
||||
|
||||
mb_data = {}
|
||||
for key in keys_to_keep:
|
||||
value = getattr(self.item, key)
|
||||
if value is not None:
|
||||
mb_data[key] = unicode(value)
|
||||
|
||||
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)
|
||||
|
||||
if self.blog.new_message_target not in (C.PUBLIC, C.GROUP):
|
||||
raise NotImplementedError
|
||||
|
||||
if self.level == 0:
|
||||
mb_data["allow_comments"] = C.BOOL_TRUE
|
||||
|
||||
if self.blog.new_message_target == C.GROUP:
|
||||
data_format.iter2dict('group', self.blog.targets, mb_data)
|
||||
|
||||
self.blog.host.bridge.mbSend(
|
||||
unicode(self.service or ''),
|
||||
self.node or '',
|
||||
mb_data,
|
||||
profile=self.blog.profile)
|
||||
|
||||
def delete(self):
|
||||
"""Remove this Entry from parent manager
|
||||
|
||||
This doesn't delete any entry in PubSub, just locally
|
||||
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))
|
||||
for child in self.entries:
|
||||
child.delete()
|
||||
try:
|
||||
self.manager.entries.remove(self)
|
||||
except ValueError:
|
||||
if self != self.manager.edit_entry:
|
||||
log.error(u"Internal Error: entry not found in manager")
|
||||
else:
|
||||
self.manager.edit_entry = None
|
||||
if not self.new:
|
||||
# we must remove references to self
|
||||
# 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)
|
||||
other_entries = self.blog.node2entries[comments_tuple].remove(self)
|
||||
if not other_entries:
|
||||
del self.blog.node2entries[comments_tuple]
|
||||
|
||||
def retract(self):
|
||||
"""Retract this item from microblog node
|
||||
|
||||
if there is a comments node, it will be purged too
|
||||
"""
|
||||
# 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)
|
||||
|
||||
|
||||
class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
|
||||
|
||||
def __init__(self, host, targets, profiles=None):
|
||||
"""Panel used to show microblog
|
||||
|
||||
@param targets (tuple(unicode)): contact groups displayed in this panel.
|
||||
If empty, show all microblogs from all contacts. targets is also used
|
||||
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
|
||||
if not targets:
|
||||
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:
|
||||
assert isinstance(targets[0], basestring)
|
||||
quick_widgets.QuickWidget.__init__(self, host, targets[0], C.PROF_KEY_NONE)
|
||||
for target in targets[1:]:
|
||||
assert isinstance(target, basestring)
|
||||
self.addTarget(target)
|
||||
self._targets_type = C.GROUP
|
||||
|
||||
@property
|
||||
def new_message_target(self):
|
||||
if self._targets_type == C.ALL:
|
||||
return C.PUBLIC
|
||||
elif self._targets_type == C.GROUP:
|
||||
return C.GROUP
|
||||
else:
|
||||
raise ValueError("Unkown targets type")
|
||||
|
||||
def __str__(self):
|
||||
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))
|
||||
for result in results:
|
||||
service, node, failure, items, metadata = result
|
||||
if not failure:
|
||||
self._addMBItemsWithComments((items, metadata), service=jid.JID(service))
|
||||
|
||||
self.update()
|
||||
if remaining:
|
||||
self._getResults(rt_session)
|
||||
|
||||
def _getResultsEb(self, failure):
|
||||
log.warning("microblog getFromMany error: {}".format(failure))
|
||||
|
||||
def _getResults(self, rt_session):
|
||||
"""Manage results from mbGetFromMany RT Session
|
||||
|
||||
@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)
|
||||
|
||||
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)
|
||||
own_pep = self.host.whoami.bare
|
||||
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))
|
||||
|
||||
def isJidAccepted(self, jid_):
|
||||
"""Tell if a jid is actepted and must be shown in this panel
|
||||
|
||||
@param jid_(jid.JID): jid to check
|
||||
@return: True if the jid is accepted
|
||||
"""
|
||||
if self._targets_type == C.ALL:
|
||||
return True
|
||||
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
|
||||
return False
|
||||
|
||||
def addEntryIfAccepted(self, service, node, mb_data, groups, profile):
|
||||
"""add entry to this panel if it's acceptable
|
||||
|
||||
This method check if the entry is new or an update,
|
||||
if it below to a know node, or if it acceptable anyway
|
||||
@param service(jid.JID): jid of the emitting pubsub service
|
||||
@param node(unicode): node identifier
|
||||
@param mb_data: microblog data
|
||||
@param groups(list[unicode], None): groups which can receive this entry
|
||||
None to accept everything
|
||||
@param profile: %(doc_profile)s
|
||||
"""
|
||||
try:
|
||||
entry = self.id2entries[mb_data['id']]
|
||||
except KeyError:
|
||||
# The entry is new
|
||||
try:
|
||||
parent_entries = self.node2entries[(service, node)]
|
||||
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))):
|
||||
self.addEntry(mb_data, service=service, node=node)
|
||||
else:
|
||||
# the entry is a comment in a known node
|
||||
for parent_entry in parent_entries:
|
||||
parent_entry.addEntry(mb_data, service=service, node=node)
|
||||
else:
|
||||
# The entry exist, it's an update
|
||||
entry.reset(mb_data)
|
||||
entry.refresh()
|
||||
|
||||
def deleteEntryIfPresent(self, service, node, item_id, profile):
|
||||
"""Delete and entry if present in this QuickBlog
|
||||
|
||||
@param sender(jid.JID): jid of the entry sender
|
||||
@param mb_data: microblog data
|
||||
@param service(jid.JID): sending service
|
||||
@param node(unicode): hosting node
|
||||
"""
|
||||
try:
|
||||
entry = self.id2entries[item_id]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
entry.delete()
|
||||
|
||||
|
||||
def registerClass(type_, cls):
|
||||
global ENTRY_CLS, COMMENTS_CLS
|
||||
if type_ == "ENTRY":
|
||||
ENTRY_CLS = cls
|
||||
elif type == "COMMENT":
|
||||
COMMENTS_CLS = cls
|
||||
else:
|
||||
raise ValueError("type_ should be ENTRY or COMMENT")
|
||||
if COMMENTS_CLS is None:
|
||||
COMMENTS_CLS = ENTRY_CLS
|
||||
610
sat_frontends/quick_frontend/quick_chat.py
Normal file
610
sat_frontends/quick_frontend/quick_chat.py
Normal file
|
|
@ -0,0 +1,610 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
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')
|
||||
|
||||
|
||||
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 = 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):
|
||||
self.parent = parent
|
||||
self.profile = profile
|
||||
self.uid = uid
|
||||
self.timestamp = timestamp
|
||||
self.from_jid = from_jid
|
||||
self.to_jid = to_jid
|
||||
self.message = msg
|
||||
self.subject = subject
|
||||
self.type = type_
|
||||
self.extra = extra
|
||||
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)
|
||||
# is user mentioned here ?
|
||||
if self.parent.type == C.CHAT_GROUP and not self.own_mess:
|
||||
for m in msg.itervalues():
|
||||
if self.parent.nick.lower() in m.lower():
|
||||
self._mention = True
|
||||
break
|
||||
self.handleMe()
|
||||
self.widgets = set() # widgets linked to this message
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self.parent.host
|
||||
|
||||
@property
|
||||
def info_type(self):
|
||||
return self.extra.get('info_type')
|
||||
|
||||
@property
|
||||
def mention(self):
|
||||
try:
|
||||
return self._mention
|
||||
except AttributeError:
|
||||
return False
|
||||
|
||||
@property
|
||||
def main_message(self):
|
||||
"""currently displayed message"""
|
||||
if self.parent.lang in self.message:
|
||||
self.selected_lang = self.parent.lang
|
||||
return self.message[self.parent.lang]
|
||||
try:
|
||||
self.selected_lang = ''
|
||||
return self.message['']
|
||||
except KeyError:
|
||||
try:
|
||||
lang, mess = self.message.iteritems().next()
|
||||
self.selected_lang = lang
|
||||
return mess
|
||||
except StopIteration:
|
||||
log.error(u"Can't find message for uid {}".format(self.uid))
|
||||
return ''
|
||||
|
||||
@property
|
||||
def main_message_xhtml(self):
|
||||
"""rich message"""
|
||||
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')
|
||||
|
||||
@property
|
||||
def avatar(self):
|
||||
"""avatar full path or None if no avatar is found"""
|
||||
ret = self.host.getAvatar(self.from_jid, profile=self.profile)
|
||||
return ret
|
||||
|
||||
def getNick(self, entity):
|
||||
"""Return nick of an entity when possible"""
|
||||
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']
|
||||
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)):
|
||||
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 entity.node or entity
|
||||
|
||||
@property
|
||||
def status(self):
|
||||
return self._status
|
||||
|
||||
@status.setter
|
||||
def status(self, status):
|
||||
if status != self._status:
|
||||
self._status = status
|
||||
for w in self.widgets:
|
||||
w.update({"status": status})
|
||||
|
||||
def handleMe(self):
|
||||
"""Check if messages starts with "/me " and change them if it is the case
|
||||
|
||||
if several messages (different languages) are presents, they all need to start with "/me "
|
||||
"""
|
||||
# TODO: XHTML-IM /me are not handled
|
||||
me = False
|
||||
# we need to check /me for every message
|
||||
for m in self.message.itervalues():
|
||||
if m.startswith(u"/me "):
|
||||
me = True
|
||||
else:
|
||||
me = False
|
||||
break
|
||||
if me:
|
||||
self.type = C.MESS_TYPE_INFO
|
||||
self.extra['info_type'] = 'me'
|
||||
nick = self.nick
|
||||
for lang, mess in self.message.iteritems():
|
||||
self.message[lang] = u"* " + nick + mess[3:]
|
||||
|
||||
|
||||
class Occupant(object):
|
||||
"""Occupant metadata"""
|
||||
|
||||
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.widgets = set() # widgets linked to this occupant
|
||||
self._state = None
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
"""reconstruct data dict from attributes"""
|
||||
data = {}
|
||||
data['nick'] = self.nick
|
||||
if self._entity is not None:
|
||||
data['entity'] = self._entity
|
||||
data['affiliation'] = self.affiliation
|
||||
data['role'] = self.role
|
||||
return data
|
||||
|
||||
@property
|
||||
def jid(self):
|
||||
"""jid in the room"""
|
||||
return jid.JID(u"{}/{}".format(self.parent.target.bare, self.nick))
|
||||
|
||||
@property
|
||||
def real_jid(self):
|
||||
"""real jid if known else None"""
|
||||
return self._entity
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self.parent.host
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
return self._state
|
||||
|
||||
@state.setter
|
||||
def state(self, new_state):
|
||||
if new_state != self._state:
|
||||
self._state = new_state
|
||||
for w in self.widgets:
|
||||
w.update({"state": new_state})
|
||||
|
||||
def update(self, update_dict=None):
|
||||
for w in self.widgets:
|
||||
w.update(update_dict)
|
||||
|
||||
|
||||
class QuickChat(quick_widgets.QuickWidget):
|
||||
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):
|
||||
"""
|
||||
@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
|
||||
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._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")
|
||||
if nick is None:
|
||||
raise exceptions.InternalError(u"nick must not be None for group chat")
|
||||
|
||||
self.nick = nick
|
||||
self.occupants = {}
|
||||
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")
|
||||
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
|
||||
if self.host.AVATARS_HANDLER:
|
||||
self.host.addListener('avatar', self.onAvatar, profiles)
|
||||
|
||||
def postInit(self):
|
||||
"""Method to be called by frontend after widget is initialised
|
||||
|
||||
handle the display of history and subject
|
||||
"""
|
||||
self.historyPrint(profile=self.profile)
|
||||
if self.subject is not None:
|
||||
self.setSubject(self.subject)
|
||||
|
||||
def onDelete(self):
|
||||
if self.host.AVATARS_HANDLER:
|
||||
self.host.removeListener('avatar', self.onAvatar)
|
||||
|
||||
@property
|
||||
def contact_list(self):
|
||||
return self.host.contact_lists[self.profile]
|
||||
|
||||
## Widget management ##
|
||||
|
||||
def __str__(self):
|
||||
return u"Chat Widget [target: {}, type: {}, profile: {}]".format(self.target, self.type, self.profile)
|
||||
|
||||
@staticmethod
|
||||
def getWidgetHash(target, profiles):
|
||||
profile = list(profiles)[0]
|
||||
return profile + "\n" + unicode(target.bare)
|
||||
|
||||
@staticmethod
|
||||
def getPrivateHash(target, profile):
|
||||
"""Get unique hash for private conversations
|
||||
|
||||
This method should be used with force_hash to get unique widget for private MUC conversations
|
||||
"""
|
||||
return (unicode(profile), target)
|
||||
|
||||
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
|
||||
|
||||
def recreateArgs(self, args, kwargs):
|
||||
"""copy important attribute for a new widget"""
|
||||
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
|
||||
try:
|
||||
kwargs['nick'] = self.nick
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def onPrivateCreated(self, widget):
|
||||
"""Method called when a new widget for private conversation (MUC) is created"""
|
||||
raise NotImplementedError
|
||||
|
||||
def getOrCreatePrivateWidget(self, entity):
|
||||
"""Create a widget for private conversation, or get it if it already exists
|
||||
|
||||
@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
|
||||
|
||||
@property
|
||||
def target(self):
|
||||
if self.type == C.CHAT_GROUP:
|
||||
return self.current_target.bare
|
||||
return self.current_target
|
||||
|
||||
## occupants ##
|
||||
|
||||
def setOccupants(self, occupants):
|
||||
"""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
|
||||
)
|
||||
|
||||
def addUser(self, occupant_data):
|
||||
"""Add user if it is not in the group list"""
|
||||
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']
|
||||
try:
|
||||
occupant = self.occupants.pop(nick)
|
||||
except KeyError:
|
||||
log.warning(u"Trying to remove an unknown occupant: {}".format(nick))
|
||||
else:
|
||||
return occupant
|
||||
|
||||
def setUserNick(self, nick):
|
||||
"""Set the nick of the user, usefull for e.g. change the color of the user"""
|
||||
self.nick = nick
|
||||
|
||||
def changeUserNick(self, old_nick, new_nick):
|
||||
"""Change nick of a user in group list"""
|
||||
self.printInfo("%s is now known as %s" % (old_nick, new_nick))
|
||||
|
||||
## Messages ##
|
||||
|
||||
def manageMessage(self, entity, mess_type):
|
||||
"""Tell if this chat widget manage an entity and message type couple
|
||||
|
||||
@param entity (jid.JID): (full) jid of the sending entity
|
||||
@param mess_type (str): message type as given by messageNew
|
||||
@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:
|
||||
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@'):
|
||||
"""Called when history need to be recreated
|
||||
|
||||
Remove all message from history then call historyPrint
|
||||
Must probably be overriden by frontend to clear widget
|
||||
@param size (int): number of messages
|
||||
@param filters (str): patterns to filter the history results
|
||||
@param profile (str): %(doc_profile)s
|
||||
"""
|
||||
self._locked = True
|
||||
self._cache = OrderedDict()
|
||||
self.messages.clear()
|
||||
self.historyPrint(size, filters, profile)
|
||||
|
||||
def _onHistoryPrinted(self):
|
||||
"""Method called when history is printed (or failed)
|
||||
|
||||
unlock the widget, and can be used to refresh or scroll down
|
||||
the focus after the history is printed
|
||||
"""
|
||||
self._locked = False
|
||||
for data in self._cache.itervalues():
|
||||
self.messageNew(*data)
|
||||
del self._cache
|
||||
|
||||
def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile='@NONE@'):
|
||||
"""Print the current history
|
||||
|
||||
@param size (int): number of messages
|
||||
@param search (str): pattern to filter the history results
|
||||
@param profile (str): %(doc_profile)s
|
||||
"""
|
||||
if filters is None:
|
||||
filters = {}
|
||||
if size == 0:
|
||||
log.debug(u"Empty history requested, skipping")
|
||||
self._onHistoryPrinted()
|
||||
return
|
||||
log_msg = _(u"now we print the history")
|
||||
if size != C.HISTORY_LIMIT_DEFAULT:
|
||||
log_msg += _(u" ({} messages)".format(size))
|
||||
log.debug(log_msg)
|
||||
|
||||
if self.type == C.CHAT_ONE2ONE:
|
||||
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
|
||||
else:
|
||||
target = self.target.bare
|
||||
else:
|
||||
# groupchat
|
||||
target = self.target.bare
|
||||
# FIXME: info not handled correctly
|
||||
filters['types'] = C.MESS_TYPE_GROUPCHAT
|
||||
|
||||
def _historyGetCb(history):
|
||||
# day_format = "%A, %d %b %Y" # to display the day change
|
||||
# previous_day = datetime.now().strftime(day_format)
|
||||
# message_day = datetime.fromtimestamp(timestamp).strftime(self.day_format)
|
||||
# if previous_day != message_day:
|
||||
# self.printDayChange(message_day)
|
||||
# previous_day = message_day
|
||||
for data in history:
|
||||
uid, timestamp, from_jid, to_jid, message, subject, type_, extra = data
|
||||
# cached messages may already be in history
|
||||
# so we check it to avoid duplicates, they'll be added later
|
||||
if uid in self._cache:
|
||||
continue
|
||||
from_jid = jid.JID(from_jid)
|
||||
to_jid = jid.JID(to_jid)
|
||||
# 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
|
||||
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)
|
||||
|
||||
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)
|
||||
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)
|
||||
return
|
||||
if type_ == C.MESS_TYPE_INFO:
|
||||
try:
|
||||
info_type = extra['info_type']
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
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)
|
||||
self.messages[uid] = message
|
||||
|
||||
if 'received_timestamp' in extra:
|
||||
log.warning(u"Delayed message received after history, this should not happen")
|
||||
self.createMessage(message)
|
||||
|
||||
def createMessage(self, message, append=False):
|
||||
"""Must be implemented by frontend to create and show a new message widget
|
||||
|
||||
This is only called on messageNew, not on history.
|
||||
You need to override historyPrint to handle the later
|
||||
@param message(Message): message data
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def printDayChange(self, day):
|
||||
"""Display the day on a new line.
|
||||
|
||||
@param day(unicode): day to display (or not if this method is not overwritten)
|
||||
"""
|
||||
# FIXME: not called anymore after refactoring
|
||||
pass
|
||||
|
||||
## Room ##
|
||||
|
||||
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")
|
||||
self.subject = subject
|
||||
|
||||
def changeSubject(self, new_subject):
|
||||
"""Change the subject of the room
|
||||
|
||||
This change the subject on the room itself (i.e. via XMPP),
|
||||
while setSubject change the subject of this widget
|
||||
"""
|
||||
self.host.bridge.mucSubject(unicode(self.target), new_subject, self.profile)
|
||||
|
||||
def addGamePanel(self, widget):
|
||||
"""Insert a game panel to this Chat dialog.
|
||||
|
||||
@param widget (Widget): the game panel
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def removeGamePanel(self, widget):
|
||||
"""Remove the game panel from this Chat dialog.
|
||||
|
||||
@param widget (Widget): the game panel
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def update(self, entity=None):
|
||||
"""Update one or all entities.
|
||||
|
||||
@param entity (jid.JID): entity to update
|
||||
"""
|
||||
# FIXME: to remove ?
|
||||
raise NotImplementedError
|
||||
|
||||
## events ##
|
||||
|
||||
def onChatState(self, from_jid, state, profile):
|
||||
"""A chat state has been received"""
|
||||
if self.type == C.CHAT_GROUP:
|
||||
nick = from_jid.resource
|
||||
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))
|
||||
|
||||
def onMessageState(self, uid, status, profile):
|
||||
try:
|
||||
mess_data = self.messages[uid]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
mess_data.status = status
|
||||
|
||||
def onAvatar(self, entity, filename, profile):
|
||||
if self.type == C.CHAT_GROUP:
|
||||
if entity.bare == self.target:
|
||||
try:
|
||||
self.occupants[entity.resource].update({'avatar': filename})
|
||||
except KeyError:
|
||||
# can happen for a message in history where the
|
||||
# entity is not here anymore
|
||||
pass
|
||||
|
||||
for m in self.messages.values():
|
||||
if m.nick == entity.resource:
|
||||
for w in m.widgets:
|
||||
w.update({'avatar': filename})
|
||||
else:
|
||||
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})
|
||||
|
||||
|
||||
quick_widgets.register(QuickChat)
|
||||
954
sat_frontends/quick_frontend/quick_contact_list.py
Normal file
954
sat_frontends/quick_frontend/quick_contact_list.py
Normal file
|
|
@ -0,0 +1,954 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
"""Contact List handling multi profiles at once, should replace quick_contact_list module in the future"""
|
||||
|
||||
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
|
||||
from sat_frontends.quick_frontend.constants import Const as C
|
||||
from sat_frontends.tools import jid
|
||||
from collections import OrderedDict
|
||||
|
||||
|
||||
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
|
||||
# XXX: pyjamas' max doesn't support key argument, so we implement it ourself
|
||||
pyjamas_max = max
|
||||
|
||||
def max(iterable, key):
|
||||
iter_cpy = list(iterable)
|
||||
iter_cpy.sort(key=key)
|
||||
return pyjamas_max(iter_cpy)
|
||||
|
||||
# next doesn't exist in pyjamas
|
||||
def next(iterable, *args):
|
||||
try:
|
||||
return iterable.next()
|
||||
except StopIteration as e:
|
||||
if args:
|
||||
return args[0]
|
||||
raise e
|
||||
|
||||
|
||||
handler = None
|
||||
|
||||
|
||||
class ProfileContactList(object):
|
||||
"""Contact list data for a single profile"""
|
||||
|
||||
def __init__(self, profile):
|
||||
self.host = handler.host
|
||||
self.profile = profile
|
||||
# contain all jids in roster or not,
|
||||
# bare jids as keys, resources are used in data
|
||||
# XXX: we don't mutualise cache, as values may differ
|
||||
# for different profiles (e.g. directed presence)
|
||||
self._cache = {}
|
||||
|
||||
# special entities (groupchat, gateways, etc)
|
||||
# may be bare or full jid
|
||||
self._specials = set()
|
||||
|
||||
# group data contain jids in groups and misc frontend data
|
||||
# None key is used for jids with not group
|
||||
self._groups = {} # groups to group data map
|
||||
|
||||
# contacts in roster (bare jids)
|
||||
self._roster = set()
|
||||
|
||||
# selected entities, full jid
|
||||
self._selected = set()
|
||||
|
||||
# we keep our own jid
|
||||
self.whoami = self.host.profiles[profile].whoami
|
||||
|
||||
# options
|
||||
self.show_disconnected = False
|
||||
self.show_empty_groups = True
|
||||
self.show_resources = False
|
||||
self.show_status = False
|
||||
|
||||
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)
|
||||
|
||||
# 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.nickListener = self.onNickUpdate
|
||||
self.host.addListener('nick', self.nickListener, [self.profile])
|
||||
self.notifListener = self.onNotification
|
||||
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])
|
||||
|
||||
def _showEmptyGroups(self, show_str):
|
||||
# Called only by __init__
|
||||
# self.update is not wanted here, as it is done by
|
||||
# handler when all profiles are ready
|
||||
self.showEmptyGroups(C.bool(show_str))
|
||||
|
||||
def _showOfflineContacts(self, show_str):
|
||||
# same comments as for _showEmptyGroups
|
||||
self.showOfflineContacts(C.bool(show_str))
|
||||
|
||||
def __contains__(self, entity):
|
||||
"""Check if entity is in contact list
|
||||
|
||||
An entity can be in contact list even if not in roster
|
||||
@param entity (jid.JID): jid of the entity (resource is not ignored, use bare jid if needed)
|
||||
"""
|
||||
if entity.resource:
|
||||
try:
|
||||
return entity.resource in self.getCache(entity.bare, C.CONTACT_RESOURCES)
|
||||
except KeyError:
|
||||
return False
|
||||
return entity in self._cache
|
||||
|
||||
@property
|
||||
def roster(self):
|
||||
"""Return all the bare JIDs of the roster entities.
|
||||
|
||||
@return (set[jid.JID])
|
||||
"""
|
||||
return self._roster
|
||||
|
||||
@property
|
||||
def roster_connected(self):
|
||||
"""Return all the bare JIDs of the roster entities that are connected.
|
||||
|
||||
@return (set[jid.JID])
|
||||
"""
|
||||
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):
|
||||
"""Return a dictionary binding the roster groups to their entities bare JIDs.
|
||||
|
||||
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}
|
||||
|
||||
@property
|
||||
def roster_groups_by_entities(self):
|
||||
"""Return a dictionary binding the entities bare JIDs to their roster groups
|
||||
|
||||
@return (dict[jid.JID, set(unicode)])
|
||||
"""
|
||||
result = {}
|
||||
for group, data in self._groups.iteritems():
|
||||
for entity in data['jids']:
|
||||
result.setdefault(entity, set()).add(group)
|
||||
return result
|
||||
|
||||
@property
|
||||
def selected(self):
|
||||
"""Return contacts currently selected
|
||||
|
||||
@return (set): set of selected entities
|
||||
"""
|
||||
return self._selected
|
||||
|
||||
@property
|
||||
def all_iter(self):
|
||||
"""return all know entities in cache as an iterator of tuples
|
||||
|
||||
entities are not sorted
|
||||
"""
|
||||
return self._cache.iteritems()
|
||||
|
||||
|
||||
@property
|
||||
def items(self):
|
||||
"""Return item representation for all visible entities in cache
|
||||
|
||||
entities are not sorted
|
||||
key: bare jid, value: data
|
||||
"""
|
||||
return {jid_:cache for jid_, cache in self._cache.iteritems() if self.entityToShow(jid_)}
|
||||
|
||||
|
||||
def getItem(self, entity):
|
||||
"""Return item representation of requested entity
|
||||
|
||||
@param entity(jid.JID): bare jid of entity
|
||||
@raise (KeyError): entity is unknown
|
||||
"""
|
||||
return self._cache[entity]
|
||||
|
||||
def _gotContacts(self, contacts):
|
||||
"""Called during filling, add contacts and notice parent that contacts are filled"""
|
||||
for contact in contacts:
|
||||
self.host.newContactHandler(*contact, profile=self.profile)
|
||||
handler._contactsFilled(self.profile)
|
||||
|
||||
def _fill(self):
|
||||
"""Get all contacts from backend
|
||||
|
||||
Contacts will be cleared before refilling them
|
||||
"""
|
||||
self.clearContacts(keep_cache=True)
|
||||
self.host.bridge.getContacts(self.profile, callback=self._gotContacts)
|
||||
|
||||
def fill(self):
|
||||
handler.fill(self.profile)
|
||||
|
||||
def getCache(self, entity, name=None, bare_default=True):
|
||||
"""Return a cache value for a contact
|
||||
|
||||
@param entity(jid.JID): entity of the contact from who we want data (resource is used if given)
|
||||
if a resource specific information is requested:
|
||||
- if no resource is given (bare jid), the main resource is used, according to priority
|
||||
- if resource is given, it is used
|
||||
@param name(unicode): name the data to get, or None to get everything
|
||||
@param bare_default(bool, None): if True and entity is a full jid, the value of bare jid
|
||||
will be returned if not value is found for the requested resource.
|
||||
If False, None is returned if no value is found for the requested resource.
|
||||
If None, bare_default will be set to False if entity is in a room, True else
|
||||
@return: full cache if no name is given, or value of "name", or None
|
||||
"""
|
||||
# FIXME: resource handling need to be reworked
|
||||
# FIXME: bare_default work for requesting full jid to get bare jid, but not the other way
|
||||
# e.g.: if we have set an avatar for user@server.tld/resource and we request user@server.tld
|
||||
# we won't get the avatar set in the resource
|
||||
try:
|
||||
cache = self._cache[entity.bare]
|
||||
except KeyError:
|
||||
self.setContact(entity)
|
||||
cache = self._cache[entity.bare]
|
||||
|
||||
if name is None:
|
||||
return cache
|
||||
|
||||
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]
|
||||
if main_resource is None:
|
||||
# we ignore presence info if we don't have any resource in cache
|
||||
# FIXME: to be checked
|
||||
return
|
||||
cache = cache[C.CONTACT_RESOURCES].setdefault(main_resource, {})
|
||||
else:
|
||||
cache = cache[C.CONTACT_RESOURCES].setdefault(entity.resource, {})
|
||||
|
||||
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, '')
|
||||
|
||||
elif entity.resource:
|
||||
try:
|
||||
return cache[C.CONTACT_RESOURCES][entity.resource][name]
|
||||
except KeyError:
|
||||
if bare_default is None:
|
||||
bare_default = not self.isRoom(entity.bare)
|
||||
if not bare_default:
|
||||
return None
|
||||
|
||||
try:
|
||||
return cache[name]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
def setCache(self, entity, name, value):
|
||||
"""Set or update value for one data in cache
|
||||
|
||||
@param entity(JID): entity to update
|
||||
@param name(unicode): value to set or update
|
||||
"""
|
||||
self.setContact(entity, attributes={name: value})
|
||||
|
||||
def getFullJid(self, entity):
|
||||
"""Get full jid from a bare jid
|
||||
|
||||
@param entity(jid.JID): must be a bare jid
|
||||
@return (jid.JID): bare jid + main resource
|
||||
@raise ValueError: the entity is not bare
|
||||
"""
|
||||
if entity.resource:
|
||||
raise ValueError(u"getFullJid must be used with a bare jid")
|
||||
main_resource = self.getCache(entity, C.CONTACT_MAIN_RESOURCE)
|
||||
return jid.JID(u"{}/{}".format(entity, main_resource))
|
||||
|
||||
def setGroupData(self, group, name, value):
|
||||
"""Register a data for a group
|
||||
|
||||
@param group: a valid (existing) group name
|
||||
@param name: name of the data (can't be "jids")
|
||||
@param value: value to set
|
||||
"""
|
||||
assert name is not 'jids'
|
||||
self._groups[group][name] = value
|
||||
|
||||
def getGroupData(self, group, name=None):
|
||||
"""Return value associated to group data
|
||||
|
||||
@param group: a valid (existing) group name
|
||||
@param name: name of the data or None to get the whole dict
|
||||
@return: registered value
|
||||
"""
|
||||
if name is None:
|
||||
return self._groups[group]
|
||||
return self._groups[group][name]
|
||||
|
||||
def isRoom(self, entity):
|
||||
"""Helper method to know if entity is a MUC room
|
||||
|
||||
@param entity(jid.JID): jid of the entity
|
||||
hint: use bare jid here, as room can't be full jid with MUC
|
||||
@return (bool): True if entity is a room
|
||||
"""
|
||||
assert entity.resource is None # FIXME: this may change when MIX will be handled
|
||||
return self.isSpecial(entity, C.CONTACT_SPECIAL_GROUP)
|
||||
|
||||
def isSpecial(self, entity, special_type):
|
||||
"""Tell if an entity is of a specialy _type
|
||||
|
||||
@param entity(jid.JID): jid of the special entity
|
||||
if the jid is full, will be added to special extras
|
||||
@param special_type: one of special type (e.g. C.CONTACT_SPECIAL_GROUP)
|
||||
@return (bool): True if entity is from this special type
|
||||
"""
|
||||
return self.getCache(entity, C.CONTACT_SPECIAL) == special_type
|
||||
|
||||
def setSpecial(self, entity, special_type):
|
||||
"""Set special flag on an entity
|
||||
|
||||
@param entity(jid.JID): jid of the special entity
|
||||
if the jid is full, will be added to special extras
|
||||
@param special_type: one of special type (e.g. C.CONTACT_SPECIAL_GROUP) or None to remove special flag
|
||||
"""
|
||||
assert special_type in C.CONTACT_SPECIAL_ALLOWED + (None,)
|
||||
self.setCache(entity, C.CONTACT_SPECIAL, special_type)
|
||||
|
||||
def getSpecials(self, special_type=None, bare=False):
|
||||
"""Return all the bare JIDs of the special roster entities of with given type.
|
||||
|
||||
@param special_type(unicode, None): if not None, filter by special type (e.g. C.CONTACT_SPECIAL_GROUP)
|
||||
@param bare(bool): return only bare jids if True
|
||||
@return (iter[jid.JID]): found special entities
|
||||
"""
|
||||
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:
|
||||
continue
|
||||
yield entity
|
||||
|
||||
def disconnect(self):
|
||||
# for now we just clear contacts on disconnect
|
||||
self.clearContacts()
|
||||
|
||||
def clearContacts(self, keep_cache=False):
|
||||
"""Clear all the contact list
|
||||
|
||||
@param keep_cache: if True, don't reset the cache
|
||||
"""
|
||||
self.select(None)
|
||||
if not keep_cache:
|
||||
self._cache.clear()
|
||||
self._groups.clear()
|
||||
self._specials.clear()
|
||||
self._roster.clear()
|
||||
self.update()
|
||||
|
||||
def setContact(self, entity, groups=None, attributes=None, in_roster=False):
|
||||
"""Add a contact to the list if doesn't exist, else update it.
|
||||
|
||||
This method can be called with groups=None for the purpose of updating
|
||||
the contact's attributes (e.g. nickname). In that case, the groups
|
||||
attribute must not be set to the default group but ignored. If not,
|
||||
you may move your contact from its actual group(s) to the default one.
|
||||
|
||||
None value for 'groups' has a different meaning than [None] which is for the default group.
|
||||
|
||||
@param entity (jid.JID): entity to add or replace
|
||||
if entity is a full jid, attributes will be cached in for the full jid only
|
||||
@param groups (list): list of groups or None to ignore the groups membership.
|
||||
@param attributes (dict): attibutes of the added jid or to update
|
||||
if attribute value is None, it will be removed
|
||||
@param in_roster (bool): True if contact is from roster
|
||||
"""
|
||||
if attributes is None:
|
||||
attributes = {}
|
||||
|
||||
entity_bare = entity.bare
|
||||
update_type = C.UPDATE_MODIFY if entity_bare in self._cache else C.UPDATE_ADD
|
||||
|
||||
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()})
|
||||
|
||||
assert not C.CONTACT_DATA_FORBIDDEN.intersection(attributes) # we don't want forbidden data in attributes
|
||||
|
||||
# we set groups and fill self._groups accordingly
|
||||
if groups is not None:
|
||||
if not groups:
|
||||
groups = [None] # [None] is the default group
|
||||
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)
|
||||
cache[C.CONTACT_GROUPS] = groups
|
||||
for group in groups:
|
||||
self._groups.setdefault(group, {}).setdefault('jids', set()).add(entity_bare)
|
||||
|
||||
# special entities management
|
||||
if C.CONTACT_SPECIAL in attributes:
|
||||
if attributes[C.CONTACT_SPECIAL] is None:
|
||||
del attributes[C.CONTACT_SPECIAL]
|
||||
self._specials.remove(entity)
|
||||
else:
|
||||
self._specials.add(entity)
|
||||
cache[C.CONTACT_MAIN_RESOURCE] = None
|
||||
|
||||
# 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
|
||||
for attribute, value in attributes.iteritems():
|
||||
if value is None:
|
||||
# XXX: pyjamas hack: we need to use pop instead of del
|
||||
try:
|
||||
cache_attr[attribute].pop(value)
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
cache_attr[attribute] = value
|
||||
|
||||
# we can update the display
|
||||
self.update([entity], update_type, self.profile)
|
||||
|
||||
def entityToShow(self, entity, check_resource=False):
|
||||
"""Tell if the contact should be showed or hidden.
|
||||
|
||||
@param entity (jid.JID): jid of the contact
|
||||
@param check_resource (bool): True if resource must be significant
|
||||
@return (bool): True if that contact should be showed in the list
|
||||
"""
|
||||
show = self.getCache(entity, C.PRESENCE_SHOW)
|
||||
|
||||
if check_resource:
|
||||
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 next(self.host.getNotifs(entity.bare, profile=self.profile), None)
|
||||
)
|
||||
|
||||
def anyEntityToShow(self, entities, check_resources=False):
|
||||
"""Tell if in a list of entities, at least one should be shown
|
||||
|
||||
@param entities (list[jid.JID]): list of jids
|
||||
@param check_resources (bool): True if resources must be significant
|
||||
@return (bool): True if a least one entity need to be shown
|
||||
"""
|
||||
# FIXME: looks inefficient, really needed?
|
||||
for entity in entities:
|
||||
if self.entityToShow(entity, check_resources):
|
||||
return True
|
||||
return False
|
||||
|
||||
def isEntityInGroup(self, entity, group):
|
||||
"""Tell if an entity is in a roster group
|
||||
|
||||
@param entity(jid.JID): jid of the entity
|
||||
@param group(unicode): group to check
|
||||
@return (bool): True if the entity is in the group
|
||||
"""
|
||||
return entity in self.getGroupData(group, "jids")
|
||||
|
||||
def removeContact(self, entity):
|
||||
"""remove a contact from the list
|
||||
|
||||
@param entity(jid.JID): jid of the entity to remove (bare jid is used)
|
||||
"""
|
||||
entity_bare = entity.bare
|
||||
try:
|
||||
groups = self._cache[entity_bare].get(C.CONTACT_GROUPS, set())
|
||||
except KeyError:
|
||||
log.error(_(u"Trying to delete an unknow entity [{}]").format(entity))
|
||||
try:
|
||||
self._roster.remove(entity_bare)
|
||||
except KeyError:
|
||||
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.pop(group) # FIXME: we use pop because of pyjamas: http://wiki.goffi.org/wiki/Issues_with_Pyjamas/en
|
||||
for iterable in (self._selected, self._specials):
|
||||
to_remove = set()
|
||||
for set_entity in iterable:
|
||||
if set_entity.bare == entity.bare:
|
||||
to_remove.add(set_entity)
|
||||
iterable.difference_update(to_remove)
|
||||
self.update([entity], C.UPDATE_DELETE, self.profile)
|
||||
|
||||
def onPresenceUpdate(self, entity, show, priority, statuses, profile):
|
||||
"""Update entity's presence status
|
||||
|
||||
@param entity(jid.JID): entity updated
|
||||
@param show: availability
|
||||
@parap priority: resource's priority
|
||||
@param statuses: dict of statuses
|
||||
@param profile: %(doc_profile)s
|
||||
"""
|
||||
cache = self.getCache(entity)
|
||||
if show == C.PRESENCE_UNAVAILABLE:
|
||||
if not entity.resource:
|
||||
cache[C.CONTACT_RESOURCES].clear()
|
||||
cache[C.CONTACT_MAIN_RESOURCE] = None
|
||||
else:
|
||||
try:
|
||||
del cache[C.CONTACT_RESOURCES][entity.resource]
|
||||
except KeyError:
|
||||
log.error(u"Presence unavailable received 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 without resource: {}".format(entity)))
|
||||
resources_data = cache[C.CONTACT_RESOURCES]
|
||||
resource_data = resources_data.setdefault(entity.resource, {})
|
||||
resource_data[C.PRESENCE_SHOW] = show
|
||||
resource_data[C.PRESENCE_PRIORITY] = int(priority)
|
||||
resource_data[C.PRESENCE_STATUSES] = statuses
|
||||
|
||||
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))
|
||||
cache[C.CONTACT_MAIN_RESOURCE] = priority_resource
|
||||
self.update([entity], C.UPDATE_MODIFY, self.profile)
|
||||
|
||||
def onNickUpdate(self, entity, new_nick, profile):
|
||||
"""Update entity's nick
|
||||
|
||||
@param entity(jid.JID): entity updated
|
||||
@param new_nick(unicode): new nick of the entity
|
||||
@param profile: %(doc_profile)s
|
||||
"""
|
||||
assert profile == self.profile
|
||||
self.setCache(entity, 'nick', new_nick)
|
||||
self.update([entity], C.UPDATE_MODIFY, profile)
|
||||
|
||||
def onNotification(self, entity, notif, profile):
|
||||
"""Update entity with notification
|
||||
|
||||
@param entity(jid.JID): entity updated
|
||||
@param notif(dict): notification data
|
||||
@param profile: %(doc_profile)s
|
||||
"""
|
||||
assert profile == self.profile
|
||||
if entity is not None:
|
||||
self.update([entity], C.UPDATE_MODIFY, profile)
|
||||
|
||||
def unselect(self, entity):
|
||||
"""Unselect an entity
|
||||
|
||||
@param entity(jid.JID): entity to unselect
|
||||
"""
|
||||
try:
|
||||
cache = self._cache[entity.bare]
|
||||
except:
|
||||
log.error(u"Try to unselect an entity not in cache")
|
||||
else:
|
||||
try:
|
||||
cache[C.CONTACT_SELECTED].remove(entity.resource)
|
||||
except KeyError:
|
||||
log.error(u"Try to unselect a not selected entity")
|
||||
else:
|
||||
self._selected.remove(entity)
|
||||
self.update([entity], C.UPDATE_SELECTION)
|
||||
|
||||
def select(self, entity):
|
||||
"""Select an entity
|
||||
|
||||
@param entity(jid.JID, None): entity to select (resource is significant)
|
||||
None to unselect all entities
|
||||
"""
|
||||
if entity is None:
|
||||
self._selected.clear()
|
||||
for cache in self._cache.itervalues():
|
||||
cache[C.CONTACT_SELECTED].clear()
|
||||
self.update(type_=C.UPDATE_SELECTION, profile=self.profile)
|
||||
else:
|
||||
log.debug(u"select %s" % entity)
|
||||
try:
|
||||
cache = self._cache[entity.bare]
|
||||
except:
|
||||
log.error(u"Try to select an entity not in cache")
|
||||
else:
|
||||
cache[C.CONTACT_SELECTED].add(entity.resource)
|
||||
self._selected.add(entity)
|
||||
self.update([entity], C.UPDATE_SELECTION, profile=self.profile)
|
||||
|
||||
def showOfflineContacts(self, show):
|
||||
"""Tell if offline contacts should shown
|
||||
|
||||
@param show(bool): True if offline contacts should be shown
|
||||
"""
|
||||
assert isinstance(show, bool)
|
||||
if self.show_disconnected == show:
|
||||
return
|
||||
self.show_disconnected = show
|
||||
self.update(type_=C.UPDATE_STRUCTURE, profile=self.profile)
|
||||
|
||||
def showEmptyGroups(self, show):
|
||||
assert isinstance(show, bool)
|
||||
if self.show_empty_groups == show:
|
||||
return
|
||||
self.show_empty_groups = show
|
||||
self.update(type_=C.UPDATE_STRUCTURE, profile=self.profile)
|
||||
|
||||
def showResources(self, show):
|
||||
assert isinstance(show, bool)
|
||||
if self.show_resources == show:
|
||||
return
|
||||
self.show_resources = show
|
||||
self.update(profile=self.profile)
|
||||
|
||||
def plug(self):
|
||||
handler.addProfile(self.profile)
|
||||
|
||||
def unplug(self):
|
||||
handler.removeProfile(self.profile)
|
||||
|
||||
def update(self, entities=None, type_=None, profile=None):
|
||||
handler.update(entities, type_, profile)
|
||||
|
||||
|
||||
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 instanciated only once")
|
||||
handler = self
|
||||
self._clist = {} # key: profile, value: ProfileContactList
|
||||
self._widgets = set()
|
||||
self._update_locked = False # se to True to ignore updates
|
||||
|
||||
def __getitem__(self, profile):
|
||||
"""Return ProfileContactList instance for the requested profile"""
|
||||
return self._clist[profile]
|
||||
|
||||
def __contains__(self, entity):
|
||||
"""Check if entity is in contact list
|
||||
|
||||
@param entity (jid.JID): jid of the entity (resource is not ignored, use bare jid if needed)
|
||||
"""
|
||||
for contact_list in self._clist.itervalues():
|
||||
if entity in contact_list:
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def roster(self):
|
||||
"""Return all the bare JIDs of the roster entities.
|
||||
|
||||
@return (set[jid.JID])
|
||||
"""
|
||||
entities = set()
|
||||
for contact_list in self._clist.itervalues():
|
||||
entities.update(contact_list.roster)
|
||||
return entities
|
||||
|
||||
@property
|
||||
def roster_connected(self):
|
||||
"""Return all the bare JIDs of the roster entities that are connected.
|
||||
|
||||
@return (set[jid.JID])
|
||||
"""
|
||||
entities = set()
|
||||
for contact_list in self._clist.itervalues():
|
||||
entities.update(contact_list.roster_connected)
|
||||
return entities
|
||||
|
||||
@property
|
||||
def roster_entities_by_group(self):
|
||||
"""Return a dictionary binding the roster groups to their entities bare
|
||||
JIDs. This also includes the empty group (None key).
|
||||
|
||||
@return (dict[unicode,set(jid.JID)])
|
||||
"""
|
||||
groups = {}
|
||||
for contact_list in self._clist.itervalues():
|
||||
groups.update(contact_list.roster_entities_by_group)
|
||||
return groups
|
||||
|
||||
@property
|
||||
def roster_groups_by_entities(self):
|
||||
"""Return a dictionary binding the entities bare JIDs to their roster
|
||||
groups.
|
||||
|
||||
@return (dict[jid.JID, set(unicode)])
|
||||
"""
|
||||
entities = {}
|
||||
for contact_list in self._clist.itervalues():
|
||||
entities.update(contact_list.roster_groups_by_entities)
|
||||
return entities
|
||||
|
||||
@property
|
||||
def selected(self):
|
||||
"""Return contacts currently selected
|
||||
|
||||
@return (set): set of selected entities
|
||||
"""
|
||||
entities = set()
|
||||
for contact_list in self._clist.itervalues():
|
||||
entities.update(contact_list.selected)
|
||||
return entities
|
||||
|
||||
@property
|
||||
def all_iter(self):
|
||||
"""Return item representation for all entities in cache
|
||||
|
||||
items are unordered
|
||||
"""
|
||||
for profile, contact_list in self._clist.iteritems():
|
||||
for bare_jid, cache in contact_list.all_iter:
|
||||
data = cache.copy()
|
||||
data[C.CONTACT_PROFILE] = profile
|
||||
yield bare_jid, data
|
||||
|
||||
@property
|
||||
def items(self):
|
||||
"""Return item representation for visible entities in cache
|
||||
|
||||
items are unordered
|
||||
key: bare jid, value: data
|
||||
"""
|
||||
items = {}
|
||||
for profile, contact_list in self._clist.iteritems():
|
||||
for bare_jid, cache in contact_list.items.iteritems():
|
||||
data = cache.copy()
|
||||
items[bare_jid] = data
|
||||
data[C.CONTACT_PROFILE] = profile
|
||||
return items
|
||||
|
||||
@property
|
||||
def items_sorted(self):
|
||||
"""Return item representation for visible entities in cache
|
||||
|
||||
items are ordered using self.items_sort
|
||||
key: bare jid, value: data
|
||||
"""
|
||||
return self.items_sort(self.items)
|
||||
|
||||
def items_sort(self, 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
|
||||
|
||||
def register(self, widget):
|
||||
"""Register a QuickContactList widget
|
||||
|
||||
This method should only be used in QuickContactList
|
||||
"""
|
||||
self._widgets.add(widget)
|
||||
|
||||
def unregister(self, widget):
|
||||
"""Unregister a QuickContactList widget
|
||||
|
||||
This method should only be used in QuickContactList
|
||||
"""
|
||||
self._widgets.remove(widget)
|
||||
|
||||
def addProfiles(self, profiles):
|
||||
"""Add a contact list for plugged profiles
|
||||
|
||||
@param profile(iterable[unicode]): plugged profiles
|
||||
"""
|
||||
for profile in profiles:
|
||||
if profile not in self._clist:
|
||||
self._clist[profile] = ProfileContactList(profile)
|
||||
return [self._clist[profile] for profile in profiles]
|
||||
|
||||
def addProfile(self, profile):
|
||||
return self.addProfiles([profile])[0]
|
||||
|
||||
def removeProfiles(self, profiles):
|
||||
"""Remove given unplugged profiles from contact list
|
||||
|
||||
@param profile(iterable[unicode]): unplugged profiles
|
||||
"""
|
||||
for profile in profiles:
|
||||
del self._clist[profile]
|
||||
|
||||
def removeProfile(self, profile):
|
||||
self.removeProfiles([profile])
|
||||
|
||||
def getSpecialExtras(self, special_type=None):
|
||||
"""Return special extras with given type
|
||||
|
||||
If special_type is None, return all special extras.
|
||||
|
||||
@param special_type(unicode, None): one of special type (e.g. C.CONTACT_SPECIAL_GROUP)
|
||||
None to return all special extras.
|
||||
@return (set[jid.JID])
|
||||
"""
|
||||
entities = set()
|
||||
for contact_list in self._clist.itervalues():
|
||||
entities.update(contact_list.getSpecialExtras(special_type))
|
||||
return entities
|
||||
|
||||
def _contactsFilled(self, profile):
|
||||
self._to_fill.remove(profile)
|
||||
if not self._to_fill:
|
||||
del self._to_fill
|
||||
self.update()
|
||||
|
||||
def fill(self, profile=None):
|
||||
"""Get all contacts from backend, and fill the widget
|
||||
|
||||
Contacts will be cleared before refilling them
|
||||
@param profile(unicode, None): profile to fill
|
||||
None to fill all profiles
|
||||
"""
|
||||
try:
|
||||
to_fill = self._to_fill
|
||||
except AttributeError:
|
||||
to_fill = self._to_fill = set()
|
||||
|
||||
# if check if profiles have already been filled
|
||||
# to void filling them several times
|
||||
filled = to_fill.copy()
|
||||
|
||||
if profile is not None:
|
||||
assert profile in self._clist
|
||||
to_fill.add(profile)
|
||||
else:
|
||||
to_fill.update(self._clist.items())
|
||||
|
||||
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))))
|
||||
for profile in remaining:
|
||||
self._clist[profile]._fill()
|
||||
|
||||
def clearContacts(self, keep_cache=False):
|
||||
"""Clear all the contact list
|
||||
|
||||
@param keep_cache: if True, don't reset the cache
|
||||
"""
|
||||
for contact_list in self._clist.itervalues():
|
||||
contact_list.clearContacts(keep_cache)
|
||||
self.update()
|
||||
|
||||
def select(self, entity):
|
||||
for contact_list in self._clist.itervalues():
|
||||
contact_list.select(entity)
|
||||
|
||||
def unselect(self, entity):
|
||||
for contact_list in self._clist.itervalues():
|
||||
contact_list.select(entity)
|
||||
|
||||
def lockUpdate(self, locked=True, do_update=True):
|
||||
"""Forbid contact list updates
|
||||
|
||||
Used mainly while profiles are plugged, as many updates can occurs, causing
|
||||
an impact on performances
|
||||
@param locked(bool): updates are forbidden if True
|
||||
@param do_update(bool): if True, a full update is done after unlocking
|
||||
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"))
|
||||
self._update_locked = locked
|
||||
if not locked and do_update:
|
||||
self.update()
|
||||
|
||||
def update(self, entities=None, type_=None, profile=None):
|
||||
if not self._update_locked:
|
||||
for widget in self._widgets:
|
||||
widget.update(entities, type_, profile)
|
||||
|
||||
|
||||
class QuickContactList(QuickWidget):
|
||||
"""This class manage the visual representation of contacts"""
|
||||
SINGLE=False
|
||||
PROFILES_MULTIPLE=True
|
||||
PROFILES_ALLOW_NONE=True # Can be linked to no profile (e.g. at the early forntend start)
|
||||
|
||||
def __init__(self, host, profiles):
|
||||
super(QuickContactList, self).__init__(host, None, profiles)
|
||||
|
||||
# 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
|
||||
|
||||
def postInit(self):
|
||||
"""Method to be called by frontend after widget is initialised"""
|
||||
handler.register(self)
|
||||
|
||||
@property
|
||||
def all_iter(self):
|
||||
return handler.all_iter
|
||||
|
||||
@property
|
||||
def items(self):
|
||||
return handler.items
|
||||
|
||||
@property
|
||||
def items_sorted(self):
|
||||
return handler.items
|
||||
|
||||
def update(self, entities=None, type_=None, profile=None):
|
||||
"""Update the display when something changed
|
||||
|
||||
@param entities(iterable[jid.JID], None): updated entities,
|
||||
None to update the whole contact list
|
||||
@param type_(unicode, None): update type, may be:
|
||||
- C.UPDATE_DELETE: entity deleted
|
||||
- C.UPDATE_MODIFY: entity updated
|
||||
- C.UPDATE_ADD: entity added
|
||||
- C.UPDATE_SELECTION: selection modified
|
||||
or None for undefined update
|
||||
@param profile(unicode, None): profile concerned with the update
|
||||
None if unknown
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def onDelete(self):
|
||||
QuickWidget.onDelete(self)
|
||||
handler.unregister(self)
|
||||
103
sat_frontends/quick_frontend/quick_contact_management.py
Normal file
103
sat_frontends/quick_frontend/quick_contact_management.py
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from sat.core.i18n import _
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
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):
|
||||
self.__contactlist = {}
|
||||
|
||||
def __contains__(self, entity):
|
||||
return entity.bare in self.__contactlist
|
||||
|
||||
def clear(self):
|
||||
"""Clear all the contact list"""
|
||||
self.__contactlist.clear()
|
||||
|
||||
def add(self, entity):
|
||||
"""Add contact to the list, update resources"""
|
||||
if not self.__contactlist.has_key(entity.bare):
|
||||
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)
|
||||
|
||||
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']:
|
||||
result.append(JID(contact))
|
||||
return result
|
||||
|
||||
def getAttr(self, entity, name):
|
||||
"""Return a specific attribute of contact, or all attributes
|
||||
@param entity: jid of the contact
|
||||
@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 self.__contactlist[entity.bare].has_key(name):
|
||||
return self.__contactlist[entity.bare][name]
|
||||
else:
|
||||
log.debug(_('Trying to get attribute for an unknown contact'))
|
||||
return None
|
||||
|
||||
def isConnected(self, entity):
|
||||
"""Tell if the contact is online"""
|
||||
return self.__contactlist.has_key(entity.bare)
|
||||
|
||||
def remove(self, entity):
|
||||
"""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
|
||||
del self.__contactlist[entity.bare]
|
||||
except KeyError:
|
||||
log.error(_('INTERNAL ERROR: Key log.error'))
|
||||
raise
|
||||
|
||||
def update(self, entity, key, value):
|
||||
"""Update attribute of contact
|
||||
@param entity: jid of the contact
|
||||
@param key: name of the attribute
|
||||
@param value: value of the attribute
|
||||
"""
|
||||
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)
|
||||
|
||||
def get_full(self, entity):
|
||||
return entity.bare+'/'+self.__contactlist[entity.bare]['resources'][-1]
|
||||
|
||||
158
sat_frontends/quick_frontend/quick_game_tarot.py
Normal file
158
sat_frontends/quick_frontend/quick_game_tarot.py
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
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.parent = parent
|
||||
self.referee = referee
|
||||
self.players = players
|
||||
self.played = {}
|
||||
for player in players:
|
||||
self.played[player] = None
|
||||
self.player_nick = parent.nick
|
||||
self.bottom_nick = unicode(self.player_nick)
|
||||
idx = self.players.index(self.player_nick)
|
||||
idx = (idx + 1) % len(self.players)
|
||||
self.right_nick = unicode(self.players[idx])
|
||||
idx = (idx + 1) % len(self.players)
|
||||
self.top_nick = unicode(self.players[idx])
|
||||
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.hand = []
|
||||
self.to_show = []
|
||||
self.state = None
|
||||
|
||||
def resetRound(self):
|
||||
"""Reset the game's variables to be reatty to start the next round"""
|
||||
del self.selected[:]
|
||||
del self.hand[:]
|
||||
del self.to_show[:]
|
||||
self.state = None
|
||||
for pl in self.played:
|
||||
self.played[pl] = None
|
||||
|
||||
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:
|
||||
return location
|
||||
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
|
||||
|
||||
def tarotGameNewHandler(self, hand):
|
||||
"""Start a new game, with given hand"""
|
||||
assert (len(self.hand) == 0)
|
||||
for suit, value in hand:
|
||||
self.hand.append(self.cards[suit, value])
|
||||
self.hand.sort()
|
||||
self.state = "init"
|
||||
|
||||
def tarotGameChooseContratHandler(self, xml_data):
|
||||
"""Called when the player as to select his contrat
|
||||
@param xml_data: SàT xml representation of the form"""
|
||||
raise NotImplementedError
|
||||
|
||||
def tarotGameShowCardsHandler(self, game_stage, cards, data):
|
||||
"""Display cards in the middle of the game (to show for e.g. chien ou poignée)"""
|
||||
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:
|
||||
self.state = "wait_for_ecart"
|
||||
else:
|
||||
self.state = "chien"
|
||||
|
||||
def tarotGameYourTurnHandler(self):
|
||||
"""Called when we have to play :)"""
|
||||
if self.state == "chien":
|
||||
self.to_show = []
|
||||
self.state = "play"
|
||||
self.__fakePlay()
|
||||
|
||||
def __fakePlay(self):
|
||||
"""Convenience method for stupid autoplay
|
||||
/!\ don't forgot to comment any interactive dialog for invalid card"""
|
||||
if self._autoplay == None:
|
||||
return
|
||||
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)
|
||||
del self.hand[self._autoplay]
|
||||
self.state = "wait"
|
||||
self._autoplay+=1
|
||||
|
||||
def tarotGameScoreHandler(self, xml_data, winners, loosers):
|
||||
"""Called at the end of a game
|
||||
@param xml_data: SàT xml representation of the scores
|
||||
@param winners: list of winners' nicks
|
||||
@param loosers: list of loosers' nicks"""
|
||||
raise NotImplementedError
|
||||
|
||||
def tarotGameCardsPlayedHandler(self, player, cards):
|
||||
"""A card has been played by player"""
|
||||
if self.to_show:
|
||||
self.to_show = []
|
||||
pl_cards = []
|
||||
if self.played[player] != None: #FIXME
|
||||
for pl in self.played:
|
||||
self.played[pl] = None
|
||||
for suit, value in cards:
|
||||
pl_cards.append(self.cards[suit, value])
|
||||
self.played[player] = pl_cards[0]
|
||||
|
||||
def tarotGameInvalidCardsHandler(self, phase, played_cards, invalid_cards):
|
||||
"""Invalid cards have been played
|
||||
@param phase: phase of the game
|
||||
@param played_cards: all the cards played
|
||||
@param invalid_cards: cards which are invalid"""
|
||||
|
||||
if phase == "play":
|
||||
self.state = "play"
|
||||
elif phase == "ecart":
|
||||
self.state = "ecart"
|
||||
else:
|
||||
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()
|
||||
|
||||
117
sat_frontends/quick_frontend/quick_games.py
Normal file
117
sat_frontends/quick_frontend/quick_games.py
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
|
||||
from sat.core.i18n import _
|
||||
|
||||
from sat_frontends.tools import jid
|
||||
from sat_frontends.tools import games
|
||||
from sat_frontends.quick_frontend.constants import Const as C
|
||||
|
||||
import quick_chat
|
||||
|
||||
|
||||
class RoomGame(object):
|
||||
_game_name = None
|
||||
_signal_prefix = None
|
||||
_signal_suffixes = None
|
||||
|
||||
@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")
|
||||
|
||||
@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)
|
||||
|
||||
# update symbols
|
||||
if cls._game_name not in chat_widget.visible_states:
|
||||
chat_widget.visible_states.append(cls._game_name)
|
||||
symbols = games.SYMBOLS[cls._game_name]
|
||||
index = 0
|
||||
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)
|
||||
chat_widget.update(occupant_jid)
|
||||
|
||||
if suffix == "Players" or chat_widget.nick not in players:
|
||||
return # waiting for other players to join, or not playing
|
||||
if cls._game_name in chat_widget.games:
|
||||
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))
|
||||
return
|
||||
panel = real_class(chat_widget, referee, players, *args)
|
||||
chat_widget.games[cls._game_name] = panel
|
||||
chat_widget.addGamePanel(panel)
|
||||
|
||||
@classmethod
|
||||
def genericHandler(cls, host, signal, *args):
|
||||
room_jid, args, profile = jid.JID(args[0]), args[1:-1], args[-1]
|
||||
chat_widget = host.widgets.getWidget(quick_chat.QuickChat, room_jid, profile)
|
||||
if chat_widget:
|
||||
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)
|
||||
return
|
||||
else:
|
||||
getattr(game_panel, "%sHandler" % signal)(*args)
|
||||
|
||||
|
||||
class Tarot(RoomGame):
|
||||
_game_name = "Tarot"
|
||||
_signal_prefix = "tarotGame"
|
||||
_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",
|
||||
)
|
||||
|
||||
|
||||
class Radiocol(RoomGame):
|
||||
_game_name = "Radiocol"
|
||||
_signal_prefix = "radiocol"
|
||||
_signal_suffixes = ("Started", "Players", "SongRejected", "Preload",
|
||||
"Play", "NoUpload", "UploadOk")
|
||||
68
sat_frontends/quick_frontend/quick_list_manager.py
Normal file
68
sat_frontends/quick_frontend/quick_list_manager.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Libervia: a Salut à Toi frontend
|
||||
# Copyright (C) 2013-2016 Adrien Cossa <souliane@mailoo.org>
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
class QuickTagList(object):
|
||||
"""This class manages a sorted list of tagged items, and a complementary sorted list of suggested but non tagged items."""
|
||||
|
||||
def __init__(self, items=None):
|
||||
"""
|
||||
|
||||
@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.untagged.sort()
|
||||
|
||||
@property
|
||||
def items(self):
|
||||
"""Return a sorted list of all items, tagged or untagged.
|
||||
|
||||
@return list
|
||||
"""
|
||||
res = list(set(self.tagged).union(self.untagged))
|
||||
res.sort()
|
||||
return res
|
||||
|
||||
def tag(self, items):
|
||||
"""Tag some items.
|
||||
|
||||
@param items (list): items to be tagged
|
||||
"""
|
||||
for item in items:
|
||||
if item not in self.tagged:
|
||||
self.tagged.append(item)
|
||||
if item in self.untagged:
|
||||
self.untagged.remove(item)
|
||||
self.tagged.sort()
|
||||
self.untagged.sort()
|
||||
|
||||
def untag(self, items):
|
||||
"""Untag some items.
|
||||
|
||||
@param items (list): items to be untagged
|
||||
"""
|
||||
for item in items:
|
||||
if item not in self.untagged and item in self.original:
|
||||
self.untagged.append(item)
|
||||
if item in self.tagged:
|
||||
self.tagged.remove(item)
|
||||
self.tagged.sort()
|
||||
self.untagged.sort()
|
||||
448
sat_frontends/quick_frontend/quick_menus.py
Normal file
448
sat_frontends/quick_frontend/quick_menus.py
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
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 = 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
|
||||
|
||||
|
||||
## items ##
|
||||
|
||||
class MenuBase(object):
|
||||
ACTIVE=True
|
||||
|
||||
def __init__(self, name, extra=None):
|
||||
"""
|
||||
@param name(unicode): canonical name of the item
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus]
|
||||
"""
|
||||
self._name = name
|
||||
self.setExtra(extra)
|
||||
|
||||
@property
|
||||
def canonical(self):
|
||||
"""Return the canonical name of the container, used to identify it"""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the container, can be translated"""
|
||||
return self._name
|
||||
|
||||
def setExtra(self, extra):
|
||||
if extra is None:
|
||||
extra = {}
|
||||
self.icon = extra.get("icon")
|
||||
|
||||
|
||||
class MenuItem(MenuBase):
|
||||
"""A callable item in the menu"""
|
||||
CALLABLE=False
|
||||
|
||||
def __init__(self, name, name_i18n, extra=None, type_=None):
|
||||
"""
|
||||
@param name(unicode): canonical name of the item
|
||||
@param name_i18n(unicode): translated name of the item
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus]
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
"""
|
||||
MenuBase.__init__(self, name, extra)
|
||||
self._name_i18n = name_i18n if name_i18n else name
|
||||
self.type = type_
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name_i18n
|
||||
|
||||
def collectData(self, caller):
|
||||
"""Get data according to data_collector
|
||||
|
||||
@param caller: Menu caller
|
||||
"""
|
||||
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:
|
||||
return {}
|
||||
|
||||
elif callable(data_collector):
|
||||
return data_collector(caller, self.name)
|
||||
|
||||
else:
|
||||
if caller is None:
|
||||
log.error(u"Caller can't be None with a dictionary as data_collector")
|
||||
return {}
|
||||
data = {}
|
||||
for data_key, caller_attr in data_collector.iteritems():
|
||||
data[data_key] = unicode(getattr(caller, caller_attr))
|
||||
return data
|
||||
|
||||
|
||||
def call(self, caller, profile=C.PROF_KEY_NONE):
|
||||
"""Execute the menu item
|
||||
|
||||
@param caller: instance linked to the menu
|
||||
@param profile: %(doc_profile)s
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class MenuItemDistant(MenuItem):
|
||||
"""A MenuItem with a distant callback"""
|
||||
CALLABLE=True
|
||||
|
||||
def __init__(self, host, type_, name, name_i18n, id_, extra=None):
|
||||
"""
|
||||
@param host: %(doc_host)s
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param name(unicode): canonical name of the item
|
||||
@param name_i18n(unicode): translated name of the item
|
||||
@param id_(unicode): id of the distant callback
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus]
|
||||
"""
|
||||
MenuItem.__init__(self, name, name_i18n, extra, type_)
|
||||
self.host = host
|
||||
self.id = id_
|
||||
|
||||
def call(self, caller, profile=C.PROF_KEY_NONE):
|
||||
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
|
||||
|
||||
def __init__(self, type_, name, name_i18n, callback, extra=None):
|
||||
"""
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param name(unicode): canonical name of the item
|
||||
@param name_i18n(unicode): translated name of the item
|
||||
@param callback(callable): local callback.
|
||||
Will be called with no argument if data_collector is None
|
||||
and with caller, profile, and requested data otherwise
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus]
|
||||
"""
|
||||
MenuItem.__init__(self, name, name_i18n, extra, type_)
|
||||
self.callback = callback
|
||||
|
||||
def call(self, caller, profile=C.PROF_KEY_NONE):
|
||||
data_collector = QuickMenusManager.getDataCollector(self.type)
|
||||
if data_collector is None:
|
||||
# FIXME: would not it be better if caller and profile where used as arguments?
|
||||
self.callback()
|
||||
else:
|
||||
self.callback(caller, self.collectData(caller), profile)
|
||||
|
||||
|
||||
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
|
||||
|
||||
def __init__(self, name):
|
||||
MenuItem.__init__(self, name, name)
|
||||
|
||||
|
||||
class MenuSeparator(MenuItem):
|
||||
"""A separation between items/categories"""
|
||||
SEP_IDX=0
|
||||
|
||||
def __init__(self):
|
||||
MenuSeparator.SEP_IDX +=1
|
||||
name = u"___separator_{}".format(MenuSeparator.SEP_IDX)
|
||||
MenuItem.__init__(self, name, name)
|
||||
|
||||
|
||||
## containers ##
|
||||
|
||||
|
||||
class MenuContainer(MenuBase):
|
||||
|
||||
def __init__(self, name, extra=None):
|
||||
MenuBase.__init__(self, name, extra)
|
||||
self._items = OrderedDict()
|
||||
|
||||
def __len__(self):
|
||||
return len(self._items)
|
||||
|
||||
def __contains__(self, item):
|
||||
return item.canonical in self._items
|
||||
|
||||
def __iter__(self):
|
||||
return self._items.itervalues()
|
||||
|
||||
def __getitem__(self, item):
|
||||
try:
|
||||
return self._items[item.canonical]
|
||||
except KeyError:
|
||||
raise KeyError(item)
|
||||
|
||||
def getOrCreate(self, item):
|
||||
log.debug(u"MenuContainer getOrCreate: item=%s name=%s\nlist=%s" % (item, item.canonical, self._items.keys()))
|
||||
try:
|
||||
return self[item]
|
||||
except KeyError:
|
||||
self.append(item)
|
||||
return item
|
||||
|
||||
def getActiveMenus(self):
|
||||
"""Return an iterator on active children"""
|
||||
for child in self._items.itervalues():
|
||||
if child.ACTIVE:
|
||||
yield child
|
||||
|
||||
def append(self, item):
|
||||
"""add an item at the end of current ones
|
||||
|
||||
@param item: instance of MenuBase (must be unique in container)
|
||||
"""
|
||||
assert isinstance(item, MenuItem) or isinstance(item, MenuContainer)
|
||||
assert item.canonical not in self._items
|
||||
self._items[item.canonical] = item
|
||||
|
||||
def replace(self, item):
|
||||
"""add an item at the end of current ones or replace an existing one"""
|
||||
self._items[item.canonical] = item
|
||||
|
||||
|
||||
class MenuCategory(MenuContainer):
|
||||
"""A category which can hold other menus or categories"""
|
||||
|
||||
def __init__(self, name, name_i18n=None, extra=None):
|
||||
"""
|
||||
@param name(unicode): canonical name
|
||||
@param name_i18n(unicode, None): translated name
|
||||
@param icon(unicode, None): same as in MenuBase.__init__
|
||||
"""
|
||||
log.debug("creating menuCategory %s with extra %s" % (name, extra))
|
||||
MenuContainer.__init__(self, name, extra)
|
||||
self._name_i18n = name_i18n or name
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name_i18n
|
||||
|
||||
|
||||
class MenuType(MenuContainer):
|
||||
"""A type which can hold other menus or categories"""
|
||||
pass
|
||||
|
||||
|
||||
## manager ##
|
||||
|
||||
|
||||
class QuickMenusManager(object):
|
||||
"""Manage all the menus"""
|
||||
_data_collectors={C.MENU_GLOBAL: None} # No data is associated with C.MENU_GLOBAL items
|
||||
|
||||
def __init__(self, host, menus=None, language=None):
|
||||
"""
|
||||
@param host: %(doc_host)s
|
||||
@param menus(iterable): menus as in [addMenus]
|
||||
@param language: same as in [i18n.languageSwitch]
|
||||
"""
|
||||
self.host = host
|
||||
MenuBase.host = host
|
||||
self.language = language
|
||||
self.menus = {}
|
||||
if menus is not None:
|
||||
self.addMenus(menus)
|
||||
|
||||
def _getPathI18n(self, path):
|
||||
"""Return translated version of path"""
|
||||
languageSwitch(self.language)
|
||||
path_i18n = [_(elt) for elt in path]
|
||||
languageSwitch()
|
||||
return path_i18n
|
||||
|
||||
def _createCategories(self, type_, path, path_i18n=None, top_extra=None):
|
||||
"""Create catogories of the path
|
||||
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path_i18n(list[unicode], None): translated menu path (same lenght as path) or None to get deferred translation of path
|
||||
@param top_extra: extra data to use on the first element of path only. If the first element already exists and is reused, top_extra will be ignored (you'll have to manually change it if you really want to).
|
||||
@return (MenuContainer): last category created, or MenuType if path is empty
|
||||
"""
|
||||
if path_i18n is None:
|
||||
path_i18n = self._getPathI18n(path)
|
||||
assert len(path) == len(path_i18n)
|
||||
menu_container = self.menus.setdefault(type_, MenuType(type_))
|
||||
|
||||
for idx, category in enumerate(path):
|
||||
menu_category = MenuCategory(category, path_i18n[idx], extra=top_extra)
|
||||
menu_container = menu_container.getOrCreate(menu_category)
|
||||
top_extra = None
|
||||
|
||||
return menu_container
|
||||
|
||||
@staticmethod
|
||||
def addDataCollector(type_, data_collector):
|
||||
"""Associate a data collector to a menu type
|
||||
|
||||
A data collector is a method or a map which allow to collect context data to construct the dictionnary which will be sent to the bridge method managing the menu item.
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param data_collector(dict[unicode,unicode], callable, None): can be:
|
||||
- a dict which map data name to local name.
|
||||
The attribute named after the dict values will be getted from caller, and put in data.
|
||||
e.g.: if data_collector={'room_jid':'target'}, then the "room_jid" data will be the value of the "target" attribute of the caller.
|
||||
- a callable which must return the data dictionnary. callable will have caller and item name as argument
|
||||
- None: an empty dict will be used
|
||||
"""
|
||||
QuickMenusManager._data_collectors[type_] = data_collector
|
||||
|
||||
@staticmethod
|
||||
def getDataCollector(type_):
|
||||
"""Get data_collector associated to type_
|
||||
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@return (callable, dict, None): data_collector
|
||||
"""
|
||||
try:
|
||||
return QuickMenusManager._data_collectors[type_]
|
||||
except KeyError:
|
||||
log.error(u"No data collector registered for {}".format(type_))
|
||||
return None
|
||||
|
||||
def addMenuItem(self, type_, path, item, path_i18n=None, top_extra=None):
|
||||
"""Add a MenuItemBase instance
|
||||
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu], stop at the last parent category
|
||||
@param item(MenuItem): a instancied item
|
||||
@param path_i18n(list[unicode],None): translated menu path (same lenght as path) or None to use deferred translation of path
|
||||
@param top_extra: same as in [_createCategories]
|
||||
"""
|
||||
if path_i18n is None:
|
||||
path_i18n = self._getPathI18n(path)
|
||||
assert path and len(path) == len(path_i18n)
|
||||
|
||||
menu_container = self._createCategories(type_, path, path_i18n, top_extra)
|
||||
|
||||
if item in menu_container:
|
||||
if isinstance(item, MenuHook):
|
||||
menu_container.replace(item)
|
||||
else:
|
||||
container_item = menu_container[item]
|
||||
if isinstance(container_item, MenuPlaceHolder):
|
||||
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))
|
||||
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)
|
||||
|
||||
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]
|
||||
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path_i18n(list[unicode], None): translated menu path (same lenght as path), or None to get deferred translation
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus]
|
||||
@param top_extra: same as in [_createCategories]
|
||||
@param id_(unicode): callback id (mutually exclusive with callback)
|
||||
@param callback(callable): local callback (mutually exclusive with id_)
|
||||
"""
|
||||
if path_i18n is None:
|
||||
path_i18n = self._getPathI18n(path)
|
||||
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)
|
||||
else:
|
||||
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):
|
||||
"""Add several menus at once
|
||||
|
||||
@param menus(iterable): iterable with:
|
||||
id_(unicode,callable): id of distant callback or local callback
|
||||
type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
path(iterable[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
path_i18n(iterable[unicode]): translated menu path (same lenght as path)
|
||||
extra(dict[unicode,unicode]): dictionary of extra data (used on the leaf menu), can be:
|
||||
- "icon": icon name
|
||||
@param top_extra: same as in [_createCategories]
|
||||
"""
|
||||
# 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)
|
||||
else:
|
||||
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):
|
||||
"""Helper method to add a menu hook
|
||||
|
||||
Menu hooks are local menus which override menu given by backend
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path_i18n(list[unicode], None): translated menu path (same lenght as path), or None to get deferred translation
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus]
|
||||
@param top_extra: same as in [_createCategories]
|
||||
@param callback(callable): local callback (mutually exclusive with id_)
|
||||
"""
|
||||
if path_i18n is None:
|
||||
path_i18n = self._getPathI18n(path)
|
||||
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_))
|
||||
|
||||
def addCategory(self, type_, path, path_i18n=None, extra=None, top_extra=None):
|
||||
"""Create a category with all parents, and set extra on the last one
|
||||
|
||||
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
|
||||
@param path_i18n(list[unicode], None): translated menu path (same lenght as path), or None to get deferred translation of path
|
||||
@param extra(dict[unicode, unicode], None): same as in [addMenus] (added on the leaf category only)
|
||||
@param top_extra: same as in [_createCategories]
|
||||
@return (MenuCategory): last category add
|
||||
"""
|
||||
if path_i18n is None:
|
||||
path_i18n = self._getPathI18n(path)
|
||||
last_container = self._createCategories(type_, path, path_i18n, top_extra=top_extra)
|
||||
last_container.setExtra(extra)
|
||||
return last_container
|
||||
|
||||
def getMainContainer(self, type_):
|
||||
"""Get a main MenuType container
|
||||
|
||||
@param type_: a C.MENU_* constant
|
||||
@return(MenuContainer): the main container
|
||||
"""
|
||||
menu_container = self.menus.setdefault(type_, MenuType(type_))
|
||||
return menu_container
|
||||
259
sat_frontends/quick_frontend/quick_profile_manager.py
Normal file
259
sat_frontends/quick_frontend/quick_profile_manager.py
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
|
||||
|
||||
class ProfileRecord(object):
|
||||
"""Class which manage data for one profile"""
|
||||
|
||||
def __init__(self, profile=None, login=None, password=None):
|
||||
self._profile = profile
|
||||
self._login = login
|
||||
self._password = password
|
||||
|
||||
@property
|
||||
def profile(self):
|
||||
return self._profile
|
||||
|
||||
@profile.setter
|
||||
def profile(self, value):
|
||||
self._profile = value
|
||||
# if we change the profile,
|
||||
# we must have no login/password until backend give them
|
||||
self._login = self._password = None
|
||||
|
||||
@property
|
||||
def login(self):
|
||||
return self._login
|
||||
|
||||
@login.setter
|
||||
def login(self, value):
|
||||
self._login = value
|
||||
|
||||
@property
|
||||
def password(self):
|
||||
return self._password
|
||||
|
||||
@password.setter
|
||||
def password(self, value):
|
||||
self._password = value
|
||||
|
||||
|
||||
class QuickProfileManager(object):
|
||||
"""Class with manage profiles creation/deletion/connection"""
|
||||
|
||||
def __init__(self, host, autoconnect=None):
|
||||
"""Create the manager
|
||||
|
||||
@param host: %(doc_host)s
|
||||
@param autoconnect(iterable): list of profiles to connect automatically
|
||||
"""
|
||||
self.host = host
|
||||
self._autoconnect = bool(autoconnect)
|
||||
self.current = ProfileRecord()
|
||||
|
||||
def go(self, autoconnect):
|
||||
if self._autoconnect:
|
||||
self.autoconnect(autoconnect)
|
||||
|
||||
def autoconnect(self, profile_keys):
|
||||
"""Automatically connect profiles
|
||||
|
||||
@param profile_keys(iterable): list of profile keys to connect
|
||||
"""
|
||||
if not profile_keys:
|
||||
log.warning("No profile given to autoconnect")
|
||||
return
|
||||
self._autoconnect = True
|
||||
self._autoconnect_profiles=[]
|
||||
self._do_autoconnect(profile_keys)
|
||||
|
||||
|
||||
def _do_autoconnect(self, profile_keys):
|
||||
"""Connect automatically given profiles
|
||||
|
||||
@param profile_kes(iterable): profiles to connect
|
||||
"""
|
||||
assert self._autoconnect
|
||||
|
||||
def authenticate_cb(data, cb_id, profile):
|
||||
|
||||
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.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
|
||||
msg = _("Trying to plug an unknown profile key ({})".format(profile_key))
|
||||
log.warning(msg)
|
||||
self.host.showDialog(_("Profile plugging in error"), msg, 'error')
|
||||
else:
|
||||
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)
|
||||
|
||||
|
||||
def getParamError(self, dummy):
|
||||
self.host.showDialog(_(u"Error"), _("Can't get profile parameter"), 'error')
|
||||
|
||||
## Helping methods ##
|
||||
|
||||
def _getErrorMessage(self, reason):
|
||||
"""Return an error message corresponding to profile creation error
|
||||
|
||||
@param reason (str): reason as returned by profileCreate
|
||||
@return (unicode): human readable error message
|
||||
"""
|
||||
if reason == "ConflictError":
|
||||
message = _("A profile with this name already exists")
|
||||
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 '@')
|
||||
else:
|
||||
message = _("Can't create profile ({})").format(reason)
|
||||
return message
|
||||
|
||||
def _deleteProfile(self):
|
||||
"""Delete the currently selected profile"""
|
||||
if self.current.profile:
|
||||
self.host.bridge.asyncDeleteProfile(self.current.profile, callback=self.refillProfiles)
|
||||
self.resetFields()
|
||||
|
||||
## workflow methods (events occuring during the profiles selection) ##
|
||||
|
||||
# These methods must be called by the frontend at some point
|
||||
|
||||
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')
|
||||
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')
|
||||
else:
|
||||
# All profiles in the list are already validated, so we can plug them directly
|
||||
self.host.plug_profiles(profiles)
|
||||
|
||||
def getConnectionParams(self, profile):
|
||||
"""Get login and password and display them
|
||||
|
||||
@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)
|
||||
|
||||
def updateConnectionParams(self):
|
||||
"""Check if connection parameters have changed, and update them if so"""
|
||||
if self.current.profile:
|
||||
login = self.getJID()
|
||||
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)
|
||||
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))
|
||||
|
||||
## graphic updates (should probably be overriden in frontends) ##
|
||||
|
||||
def resetFields(self):
|
||||
"""Set profile to None, and reset fields"""
|
||||
self.current.profile=None
|
||||
self.setJID("")
|
||||
self.setPassword("")
|
||||
|
||||
def refillProfiles(self):
|
||||
"""Rebuild the list of profiles"""
|
||||
profiles = self.host.bridge.profilesListGet()
|
||||
profiles.sort()
|
||||
self.setProfiles(profiles)
|
||||
|
||||
## Method which must be implemented by frontends ##
|
||||
|
||||
# get/set data
|
||||
|
||||
def getProfiles(self):
|
||||
"""Return list of selected profiles
|
||||
|
||||
Must be implemented by frontends
|
||||
@return (list): list of profiles
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def setProfiles(self, profiles):
|
||||
"""Update the list of profiles"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def getJID(self):
|
||||
"""Get current jid
|
||||
|
||||
Must be implemented by frontends
|
||||
@return (unicode): current jabber id
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def getPassword(self):
|
||||
"""Get current password
|
||||
|
||||
Must be implemented by frontends
|
||||
@return (unicode): current password
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def setJID(self, jid_):
|
||||
"""Set current jid
|
||||
|
||||
Must be implemented by frontends
|
||||
@param jid_(unicode): jabber id to set
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def setPassword(self, password):
|
||||
"""Set current password
|
||||
|
||||
Must be implemented by frontends
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# dialogs
|
||||
|
||||
# Note: a method which check profiles change must be implemented too
|
||||
51
sat_frontends/quick_frontend/quick_utils.py
Normal file
51
sat_frontends/quick_frontend/quick_utils.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Primitivus: a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
if not exists(path):
|
||||
return path
|
||||
root, ext = splitext(path)
|
||||
while True:
|
||||
new_path = "%s_%d%s" % (root, idx, ext)
|
||||
if not exists(new_path):
|
||||
return new_path
|
||||
idx+=1
|
||||
|
||||
def check_options():
|
||||
"""Check command line options"""
|
||||
usage = _("""
|
||||
%prog [options]
|
||||
|
||||
%prog --help for options list
|
||||
""")
|
||||
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')
|
||||
return options
|
||||
|
||||
363
sat_frontends/quick_frontend/quick_widgets.py
Normal file
363
sat_frontends/quick_frontend/quick_widgets.py
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
#!/usr/bin/env python2
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# helper class for making a SAT frontend
|
||||
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
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_'
|
||||
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 = str
|
||||
|
||||
|
||||
def register(base_cls, child_cls=None):
|
||||
"""Register a child class to use by default when a base class is needed
|
||||
|
||||
@param base_cls: "Quick..." base class (like QuickChat or QuickContact), must inherit from QuickWidget
|
||||
@param child_cls: inherited class to use when Quick... class is requested, must inherit from base_cls.
|
||||
Can be None if it's the base_cls itself which register
|
||||
"""
|
||||
# FIXME: we use base_cls.__name__ instead of base_cls directly because pyjamas because
|
||||
# in the second case
|
||||
classes_map[base_cls.__name__] = child_cls
|
||||
|
||||
|
||||
class WidgetAlreadyExistsError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class QuickWidgetsManager(object):
|
||||
"""This class is used to manage all the widgets of a frontend
|
||||
A widget can be a window, a graphical thing, or someting else depending of the frontend"""
|
||||
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
self._widgets = {}
|
||||
|
||||
def __iter__(self):
|
||||
"""Iterate throught all widgets"""
|
||||
for widget_map in self._widgets.itervalues():
|
||||
for widget in widget_map.itervalues():
|
||||
yield widget
|
||||
|
||||
def getRealClass(self, class_):
|
||||
"""Return class registered for given class_
|
||||
|
||||
@param class_: subclass of QuickWidget
|
||||
@return: class actually used to create widget
|
||||
"""
|
||||
try:
|
||||
# FIXME: we use base_cls.__name__ instead of base_cls directly because pyjamas bugs
|
||||
# in the second case
|
||||
cls = classes_map[class_.__name__]
|
||||
except KeyError:
|
||||
cls = class_
|
||||
if cls is None:
|
||||
raise exceptions.InternalError("There is not class registered for {}".format(class_))
|
||||
return cls
|
||||
|
||||
def getRootHash(self, hash_):
|
||||
"""Return root hash (i.e. hash without new instance suffix for recreated widgets
|
||||
|
||||
@param hash_(immutable): hash of a widget
|
||||
@return (unicode): root hash (transtyped to unicode)
|
||||
"""
|
||||
return unicode(hash_).split(NEW_INSTANCE_SUFF)[0]
|
||||
|
||||
def getWidgets(self, class_, target=None, profiles=None):
|
||||
"""Get all subclassed widgets instances
|
||||
|
||||
@param class_: subclass of QuickWidget, same parameter as used in [getOrCreateWidget]
|
||||
@param target: if not None, construct a hash with this target and filter corresponding widgets
|
||||
recreated widgets (with new instance suffix) are handled
|
||||
@param profiles(iterable, None): if not None, filter on instances linked to these profiles
|
||||
@return: iterator on widgets
|
||||
"""
|
||||
class_ = self.getRealClass(class_)
|
||||
try:
|
||||
widgets_map = self._widgets[class_.__name__]
|
||||
except KeyError:
|
||||
return
|
||||
else:
|
||||
if target is not None:
|
||||
filter_hash = unicode(class_.getWidgetHash(target, profiles))
|
||||
else:
|
||||
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:
|
||||
continue
|
||||
yield w
|
||||
|
||||
def getWidget(self, class_, target=None, profiles=None):
|
||||
"""Get a widget without creating it if it doesn't exist.
|
||||
|
||||
@param class_(class): class of the widget to create
|
||||
@param target: target depending of the widget, usually a JID instance
|
||||
@param profiles (unicode, iterable[unicode], None): profile(s) to use (may or may not be
|
||||
used, depending of the widget class)
|
||||
@return: a class_ instance or None if the widget doesn't exist
|
||||
"""
|
||||
assert (target is not None) or (profiles is not None)
|
||||
if profiles is not None and isinstance(profiles, unicode):
|
||||
profiles = [profiles]
|
||||
class_ = self.getRealClass(class_)
|
||||
hash_ = class_.getWidgetHash(target, profiles)
|
||||
try:
|
||||
return self._widgets[class_.__name__][hash_]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
def getOrCreateWidget(self, class_, target, *args, **kwargs):
|
||||
"""Get an existing widget or create a new one when necessary
|
||||
|
||||
If the widget is new, self.host.newWidget will be called with it.
|
||||
@param class_(class): class of the widget to create
|
||||
@param target: target depending of the widget, usually a JID instance
|
||||
@param args(list): optional args to create a new instance of class_
|
||||
@param kwargs(dict): optional kwargs to create a new instance of class_
|
||||
if 'profile' key is present, it will be popped and put in 'profiles'
|
||||
if there is neither 'profile' nor 'profiles', None will be used for 'profiles'
|
||||
if 'on_new_widget' is present it can have the following values:
|
||||
C.WIDGET_NEW [default]: self.host.newWidget will be called on widget creation
|
||||
[callable]: this method will be called instead of self.host.newWidget
|
||||
None: do nothing
|
||||
if 'on_existing_widget' is present it can have the following values:
|
||||
C.WIDGET_KEEP [default]: return the existing widget
|
||||
C.WIDGET_RAISE: raise WidgetAlreadyExistsError
|
||||
C.WIDGET_RECREATE: create a new widget *WITH A NEW HASH*
|
||||
if the existing widget has a "recreateArgs" method, it will be called with args list and kwargs dict
|
||||
so the values can be completed to create correctly the new instance
|
||||
[callable]: this method will be called with existing widget as argument
|
||||
if 'force_hash' is present, the hash given in value will be used instead of the one returned by class_.getWidgetHash
|
||||
other keys will be used to instanciate class_ if the case happen (e.g. if type_ is present and class_ is a QuickChat subclass,
|
||||
it will be used to create a new QuickChat instance).
|
||||
@return: a class_ instance, either new or already existing
|
||||
"""
|
||||
cls = self.getRealClass(class_)
|
||||
|
||||
## arguments management ##
|
||||
_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")
|
||||
try:
|
||||
_kwargs['profiles'] = [_kwargs.pop('profile')]
|
||||
except KeyError:
|
||||
if not 'profiles' in _kwargs:
|
||||
_kwargs['profiles'] = None
|
||||
|
||||
#on_new_widget tell what to do for the new widget creation
|
||||
try:
|
||||
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
|
||||
try:
|
||||
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')
|
||||
except KeyError:
|
||||
hash_ = cls.getWidgetHash(target, _kwargs['profiles'])
|
||||
|
||||
## widget creation or retrieval ##
|
||||
|
||||
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
|
||||
else:
|
||||
try:
|
||||
widget = widgets_map[hash_]
|
||||
widget.addTarget(target)
|
||||
except KeyError:
|
||||
widget = None
|
||||
|
||||
if widget is None:
|
||||
# we need to create a new widget
|
||||
log.debug(u"Creating new widget for target {} {}".format(target, cls))
|
||||
widget = cls(*_args, **_kwargs)
|
||||
widgets_map[hash_] = widget
|
||||
|
||||
if on_new_widget == C.WIDGET_NEW:
|
||||
self.host.newWidget(widget)
|
||||
elif callable(on_new_widget):
|
||||
on_new_widget(widget)
|
||||
else:
|
||||
assert on_new_widget is None
|
||||
else:
|
||||
# the widget already exists
|
||||
if on_existing_widget == C.WIDGET_KEEP:
|
||||
pass
|
||||
elif on_existing_widget == C.WIDGET_RAISE:
|
||||
raise WidgetAlreadyExistsError(hash_)
|
||||
elif on_existing_widget == C.WIDGET_RECREATE:
|
||||
# we use getOrCreateWidget to recreate the new widget
|
||||
# /!\ we use args and kwargs and not _args and _kwargs because we need the original args
|
||||
# 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
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
raise ValueError("force_hash option can't be used with on_existing_widget=RECREATE")
|
||||
|
||||
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
|
||||
try:
|
||||
recreateArgs = widget.recreateArgs
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
recreateArgs(args, new_kwargs)
|
||||
hash_idx = 1
|
||||
while True:
|
||||
new_kwargs['force_hash'] = "{}{}{}".format(hash_, NEW_INSTANCE_SUFF, hash_idx)
|
||||
try:
|
||||
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']))
|
||||
break
|
||||
elif callable(on_existing_widget):
|
||||
on_existing_widget(widget)
|
||||
else:
|
||||
raise exceptions.InternalError("Unexpected on_existing_widget value ({})".format(on_existing_widget))
|
||||
|
||||
return widget
|
||||
|
||||
def deleteWidget(self, widget_to_delete, *args, **kwargs):
|
||||
"""Delete a widget
|
||||
|
||||
this method must be called by frontends when a widget is deleted
|
||||
widget's onDelete method will be called before deletion
|
||||
@param widget_to_delete(QuickWidget): widget which need to deleted
|
||||
@param *args: extra arguments to pass to onDelete
|
||||
@param *kwargs: extra keywords arguments to pass to onDelete
|
||||
the extra arguments are not use by QuickFrontend, it's is up to
|
||||
the frontend to use them or not
|
||||
"""
|
||||
if widget_to_delete.onDelete(*args, **kwargs) == False:
|
||||
return
|
||||
|
||||
if self.host.selected_widget == widget_to_delete:
|
||||
self.host.selected_widget = None
|
||||
|
||||
for widget_map in self._widgets.itervalues():
|
||||
to_delete = set()
|
||||
for hash_, widget in widget_map.iteritems():
|
||||
if widget_to_delete is widget:
|
||||
to_delete.add(hash_)
|
||||
for hash_ in to_delete:
|
||||
del widget_map[hash_]
|
||||
|
||||
|
||||
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
|
||||
|
||||
def __init__(self, host, target, profiles=None):
|
||||
"""
|
||||
@param host: %(doc_host)s
|
||||
@param target: target specific for this widget class
|
||||
@param profiles: can be either:
|
||||
- (unicode): used when widget class manage a unique profile
|
||||
- (iterable): some widget class can manage several profiles, several at once can be specified here
|
||||
- None: no profile is managed by this widget class (rare)
|
||||
@raise: ValueError when (iterable) or None is given to profiles for a widget class which manage one unique profile.
|
||||
"""
|
||||
self.host = host
|
||||
self.targets = set()
|
||||
self.addTarget(target)
|
||||
self.profiles = set()
|
||||
if isinstance(profiles, basestring):
|
||||
self.addProfile(profiles)
|
||||
elif profiles is None:
|
||||
if not self.PROFILES_ALLOW_NONE:
|
||||
raise ValueError("profiles can't have a value of None")
|
||||
else:
|
||||
for profile in profiles:
|
||||
self.addProfile(profile)
|
||||
if not self.profiles:
|
||||
raise ValueError("no profile found, use None for no profile classes")
|
||||
|
||||
@property
|
||||
def profile(self):
|
||||
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):
|
||||
"""Add a target if it doesn't already exists
|
||||
|
||||
@param target: target to add
|
||||
"""
|
||||
self.targets.add(target)
|
||||
|
||||
def addProfile(self, profile):
|
||||
"""Add a profile is if doesn't already exists
|
||||
|
||||
@param profile: profile to add
|
||||
"""
|
||||
if self.profiles and not self.PROFILES_MULTIPLE:
|
||||
raise ValueError("multiple profiles are not allowed")
|
||||
self.profiles.add(profile)
|
||||
|
||||
@staticmethod
|
||||
def getWidgetHash(target, profiles):
|
||||
"""Return the hash associated with this target for this widget class
|
||||
|
||||
some widget classes can manage several target on the same instance
|
||||
(e.g.: a chat widget with multiple resources on the same bare jid),
|
||||
this method allow to return a hash associated to one or several targets
|
||||
to retrieve the good instance. For example, a widget managing JID targets,
|
||||
and all resource of the same bare jid would return the bare jid as hash.
|
||||
|
||||
@param target: target to check
|
||||
@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
|
||||
|
||||
def onDelete(self, *args, **kwargs):
|
||||
"""Called when a widget is being deleted
|
||||
|
||||
@return (boot, None): False to cancel deletion
|
||||
all other value continue deletion
|
||||
"""
|
||||
log.debug(u"widget {} deleted".format(self))
|
||||
return True
|
||||
|
||||
Loading…
Reference in a new issue