Remove trailing whitespaces.
This commit is contained in:
parent
310e2cc347
commit
27b3592e16
42 changed files with 899 additions and 899 deletions
|
|
@ -94,7 +94,7 @@ class DbusObject(dbus.service.Object):
|
|||
raise DeferredNotAsync
|
||||
return result
|
||||
|
||||
### signals ###
|
||||
### signals ###
|
||||
|
||||
@dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX,
|
||||
signature='')
|
||||
|
|
@ -175,8 +175,8 @@ class DbusObject(dbus.service.Object):
|
|||
pass
|
||||
|
||||
|
||||
### methods ###
|
||||
|
||||
### methods ###
|
||||
|
||||
@dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX,
|
||||
in_signature='ss', out_signature='',
|
||||
async_callbacks=None)
|
||||
|
|
@ -411,11 +411,11 @@ class DbusObject(dbus.service.Object):
|
|||
def updateContact(self, entity_jid, name, groups, profile_key="@DEFAULT@"):
|
||||
return self._callback("updateContact", unicode(entity_jid), unicode(name), groups, unicode(profile_key))
|
||||
|
||||
|
||||
|
||||
def __attributes(self, in_sign):
|
||||
"""Return arguments to user given a in_sign
|
||||
@param in_sign: in_sign in the short form (using s,a,i,b etc)
|
||||
@return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
@return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
i=0
|
||||
idx=0
|
||||
attr=[]
|
||||
|
|
@ -454,19 +454,19 @@ class DbusObject(dbus.service.Object):
|
|||
|
||||
_arguments = inspect_args.args
|
||||
_defaults = list(inspect_args.defaults or [])
|
||||
|
||||
|
||||
if inspect.ismethod(method):
|
||||
#if we have a method, we don't want the first argument (usually 'self')
|
||||
del(_arguments[0])
|
||||
|
||||
#first arguments are for the _callback method
|
||||
arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments))
|
||||
|
||||
|
||||
if async:
|
||||
_arguments.extend(['callback','errback'])
|
||||
_defaults.extend([None, None])
|
||||
|
||||
|
||||
|
||||
|
||||
#now we create a second list with default values
|
||||
for i in range(1, len(_defaults)+1):
|
||||
_arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i]))
|
||||
|
|
@ -484,7 +484,7 @@ class DbusObject(dbus.service.Object):
|
|||
function = getattr(self, name)
|
||||
func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
|
||||
func_table[function.__name__] = function #Needed for introspection
|
||||
|
||||
|
||||
def addSignal(self, name, int_suffix, signature, doc={}):
|
||||
"""Dynamically add a signal to Dbus Bridge"""
|
||||
attributes = ', '.join(self.__attributes(signature))
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ class Bridge(object):
|
|||
info ("Bridge initialization")
|
||||
|
||||
##signals
|
||||
def newContact(self, contact):
|
||||
def newContact(self, contact):
|
||||
raise NotImplementedError
|
||||
|
||||
def newMessage(self, from_jid, msg, type='chat'):
|
||||
|
|
@ -45,7 +45,7 @@ class Bridge(object):
|
|||
|
||||
def getContacts(self):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def getPresenceStatus(self):
|
||||
raise NotImplementedError
|
||||
|
||||
|
|
@ -57,12 +57,12 @@ class Bridge(object):
|
|||
|
||||
def setParam(self, name, value, namespace):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def getParam(self, name, namespace):
|
||||
raise NotImplementedError
|
||||
|
||||
def getParams(self, namespace):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def getHistory(self, from_jid, to_jid, size):
|
||||
raise NotImplementedError
|
||||
|
|
|
|||
|
|
@ -53,11 +53,11 @@ from xml.dom import minidom
|
|||
|
||||
|
||||
class ParseError(Exception):
|
||||
#Used when the signature parsing is going wrong (invalid signature ?)
|
||||
#Used when the signature parsing is going wrong (invalid signature ?)
|
||||
pass
|
||||
|
||||
class Constructor:
|
||||
|
||||
|
||||
def __init__(self, bridge_template, options):
|
||||
self.bridge_template = bridge_template
|
||||
self.options = options
|
||||
|
|
@ -74,14 +74,14 @@ class Constructor:
|
|||
value = None
|
||||
function[option] = value
|
||||
return function
|
||||
|
||||
|
||||
def getDefault(self, name):
|
||||
"""Return default values of a function in a dict
|
||||
@param name: Name of the function to get
|
||||
@return: dict, each key is the integer param number (no key if no default value)"""
|
||||
default_dict={}
|
||||
def_re = re.compile(r"param_(\d+)_default")
|
||||
|
||||
|
||||
for option in self.bridge_template.options(name):
|
||||
match = def_re.match(option)
|
||||
if match:
|
||||
|
|
@ -90,7 +90,7 @@ class Constructor:
|
|||
except ValueError:
|
||||
raise ParseError("Invalid value [%s] for parameter number" % match.group(1))
|
||||
default_dict[idx] = self.bridge_template.get(name, option)
|
||||
|
||||
|
||||
return default_dict
|
||||
|
||||
def getFlags(self, name):
|
||||
|
|
@ -102,7 +102,7 @@ class Constructor:
|
|||
if option in FLAGS:
|
||||
flags.append(option)
|
||||
return flags
|
||||
|
||||
|
||||
def getArgumentsDoc(self, name):
|
||||
"""Return documentation of arguments
|
||||
@param name: Name of the function to get
|
||||
|
|
@ -175,10 +175,10 @@ class Constructor:
|
|||
@param name: dictionary of arguments name like given by getArguments
|
||||
@param default: dictionary of default values, like given by getDefault
|
||||
@param unicode_protect: activate unicode protection on strings (return strings as unicode(str))
|
||||
@return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
@return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
idx=0
|
||||
attr_string=[]
|
||||
|
||||
|
||||
for arg in self.argumentsParser(signature):
|
||||
attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and arg=='s') else "%(name)s%(default)s") % {
|
||||
'name':name[idx][0] if (name and name.has_key(idx)) else "arg_%i" % idx,
|
||||
|
|
@ -186,7 +186,7 @@ class Constructor:
|
|||
}) #give arg_1, arg2, etc or name1, name2=default, etc. \
|
||||
#give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string
|
||||
idx+=1
|
||||
|
||||
|
||||
return ", ".join(attr_string)
|
||||
|
||||
def generateCoreSide(self):
|
||||
|
|
@ -209,7 +209,7 @@ class Constructor:
|
|||
os.mkdir(DEST_DIR)
|
||||
full_path=os.path.join(DEST_DIR,filename)
|
||||
if os.path.exists(full_path) and not self.options.force:
|
||||
print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path)
|
||||
print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path)
|
||||
try:
|
||||
with open(full_path,'w') as dest_file:
|
||||
dest_file.write('\n'.join(file_buf))
|
||||
|
|
@ -223,8 +223,8 @@ class MediawikiConstructor(Constructor):
|
|||
|
||||
def __init__(self, bridge_template, options):
|
||||
Constructor.__init__(self, bridge_template, options)
|
||||
self.core_template="mediawiki_template.tpl"
|
||||
self.core_dest="mediawiki.wiki"
|
||||
self.core_template="mediawiki_template.tpl"
|
||||
self.core_dest="mediawiki.wiki"
|
||||
|
||||
def _addTextDecorations(self, text):
|
||||
"""Add text decorations like coloration or shortcuts"""
|
||||
|
|
@ -259,7 +259,7 @@ class MediawikiConstructor(Constructor):
|
|||
if arg_default.has_key(i):
|
||||
wiki.append(":''DEFAULT: %s''" % arg_default[i])
|
||||
return "\n".join(wiki)
|
||||
|
||||
|
||||
def _wikiReturn(self, name):
|
||||
"""Format return doc with the wiki syntax
|
||||
@param name: name of the function
|
||||
|
|
@ -317,7 +317,7 @@ class MediawikiConstructor(Constructor):
|
|||
%(async)s
|
||||
{| class="wikitable" style="text-align:left; width:80%%;"
|
||||
! scope=row | category
|
||||
| %(category)s
|
||||
| %(category)s
|
||||
|-
|
||||
%(signature)s
|
||||
! scope=row | parameters
|
||||
|
|
@ -325,7 +325,7 @@ class MediawikiConstructor(Constructor):
|
|||
%(parameters)s%(return)s
|
||||
|}
|
||||
""" % completion)
|
||||
|
||||
|
||||
#at this point, signals_part, and methods_part should be filled,
|
||||
#we just have to place them in the right part of the template
|
||||
core_bridge = []
|
||||
|
|
@ -342,7 +342,7 @@ class MediawikiConstructor(Constructor):
|
|||
core_bridge.append(line.replace('\n',''))
|
||||
except IOError:
|
||||
print ("Can't open template file [%s]" % self.core_template)
|
||||
sys.exit(1)
|
||||
sys.exit(1)
|
||||
|
||||
#now we write to final file
|
||||
self.finalWrite(self.core_dest, core_bridge)
|
||||
|
|
@ -351,9 +351,9 @@ class DbusConstructor(Constructor):
|
|||
|
||||
def __init__(self, bridge_template, options):
|
||||
Constructor.__init__(self, bridge_template, options)
|
||||
self.core_template="dbus_core_template.py"
|
||||
self.frontend_template="dbus_frontend_template.py"
|
||||
self.frontend_dest = self.core_dest="DBus.py"
|
||||
self.core_template="dbus_core_template.py"
|
||||
self.frontend_template="dbus_frontend_template.py"
|
||||
self.frontend_dest = self.core_dest="DBus.py"
|
||||
|
||||
def generateCoreSide(self):
|
||||
signals_part = []
|
||||
|
|
@ -371,7 +371,7 @@ class DbusConstructor(Constructor):
|
|||
'sig_in':function['sig_in'] or '',
|
||||
'sig_out':function['sig_out'] or '',
|
||||
'category':'PLUGIN' if function['category'] == 'plugin' else 'CORE',
|
||||
'name':section,
|
||||
'name':section,
|
||||
'args':self.getArguments(function['sig_in'], name=arg_doc, default=default )
|
||||
}
|
||||
|
||||
|
|
@ -427,7 +427,7 @@ class DbusConstructor(Constructor):
|
|||
core_bridge.append(line.replace('\n',''))
|
||||
except IOError:
|
||||
print ("Can't open template file [%s]" % self.core_template)
|
||||
sys.exit(1)
|
||||
sys.exit(1)
|
||||
|
||||
#now we write to final file
|
||||
self.finalWrite(self.core_dest, core_bridge)
|
||||
|
|
@ -446,7 +446,7 @@ class DbusConstructor(Constructor):
|
|||
'sig_in':function['sig_in'] or '',
|
||||
'sig_out':function['sig_out'] or '',
|
||||
'category':'plugin' if function['category'] == 'plugin' else 'core',
|
||||
'name':section,
|
||||
'name':section,
|
||||
'args':self.getArguments(function['sig_in'], name=arg_doc, default=default)
|
||||
}
|
||||
|
||||
|
|
@ -483,7 +483,7 @@ class DbusConstructor(Constructor):
|
|||
frontend_bridge.append(line.replace('\n',''))
|
||||
except IOError:
|
||||
print ("Can't open template file [%s]" % self.frontend_template)
|
||||
sys.exit(1)
|
||||
sys.exit(1)
|
||||
|
||||
#now we write to final file
|
||||
self.finalWrite(self.frontend_dest, frontend_bridge)
|
||||
|
|
@ -493,8 +493,8 @@ class DbusXmlConstructor(Constructor):
|
|||
|
||||
def __init__(self, bridge_template, options):
|
||||
Constructor.__init__(self, bridge_template, options)
|
||||
|
||||
self.template="dbus_xml_template.xml"
|
||||
|
||||
self.template="dbus_xml_template.xml"
|
||||
self.core_dest="org.goffi.sat.xml"
|
||||
self.default_annotation = { 'a{ss}': 'StringDict',
|
||||
'a(sa{ss}as)': 'QList<Contact>',
|
||||
|
|
@ -540,7 +540,7 @@ class DbusXmlConstructor(Constructor):
|
|||
annot_elt.setAttribute('value', self.default_annotation[arg])
|
||||
new_elt.appendChild(annot_elt)
|
||||
idx+=1
|
||||
|
||||
|
||||
if function['sig_out']:
|
||||
arg_elt = doc.createElement('arg')
|
||||
arg_elt.setAttribute('type', function['sig_out'])
|
||||
|
|
@ -575,7 +575,7 @@ class ConstructorFactory:
|
|||
class BridgeConstructor:
|
||||
def __init__(self):
|
||||
self.options = None
|
||||
|
||||
|
||||
def check_options(self):
|
||||
"""Check command line options"""
|
||||
_usage="""
|
||||
|
|
@ -597,7 +597,7 @@ class BridgeConstructor:
|
|||
help=("Add debug information printing"))
|
||||
parser.add_option("--no_unicode", action="store_false", dest="unicode", default=True,
|
||||
help=("Remove unicode type protection from string results"))
|
||||
parser.add_option("--flags", action="store", type="string",
|
||||
parser.add_option("--flags", action="store", type="string",
|
||||
help=("Constructors' specific flags, comma separated"))
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ doc=New contact received in roster
|
|||
doc_param_0=contact_jid: JID from who the message is comming
|
||||
doc_param_1=attributes: Dictionary of attributes where keys are:
|
||||
- name: name of the contact
|
||||
- to: "True" if the contact give its presence information to us
|
||||
- to: "True" if the contact give its presence information to us
|
||||
- from: "True" if contact is registred to our presence information
|
||||
- ask: "True" is subscription is pending
|
||||
doc_param_2=groups: Roster's groups where the contact is
|
||||
|
|
@ -135,7 +135,7 @@ category=core
|
|||
sig_in=ssa{sa{ss}}s
|
||||
doc=Requested result of an action (Extended)
|
||||
doc_param_0=answer_type: Same as for [actionResult] but with the following additional one:
|
||||
- DICT_DICT: As RESULT, but returned as a dictionary of dictionary
|
||||
- DICT_DICT: As RESULT, but returned as a dictionary of dictionary
|
||||
doc_param_1=id: Id of the action
|
||||
doc_param_2=data: answer_type specific data
|
||||
doc_param_3=%(doc_profile)s
|
||||
|
|
@ -319,7 +319,7 @@ param_0_default="@DEFAULT@"
|
|||
doc=Return presence informations of all contacts
|
||||
doc_param_0=%(doc_profile_key)s
|
||||
doc_return=Dict of presence with bare JID of contact as key, and value as follow:
|
||||
A dict where key is the resource and the value is a tuple with (show, priority, statuses) as for [presenceUpdate]
|
||||
A dict where key is the resource and the value is a tuple with (show, priority, statuses) as for [presenceUpdate]
|
||||
|
||||
[getWaitingSub]
|
||||
type=method
|
||||
|
|
@ -552,7 +552,7 @@ doc_param_0=id: id of the progression status
|
|||
doc_param_1=%(doc_profile)s
|
||||
doc_return=dict with progress information:
|
||||
- position: current position
|
||||
- size: end position
|
||||
- size: end position
|
||||
|
||||
[getMenus]
|
||||
type=method
|
||||
|
|
@ -564,7 +564,7 @@ doc_return=list of tuple with the following value:
|
|||
- category: Category of the menu
|
||||
- name: Name of the menu
|
||||
- menu_type: Type which can be:
|
||||
* NORMAL: Classical application menu
|
||||
* NORMAL: Classical application menu
|
||||
|
||||
[getMenuHelp]
|
||||
type=method
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ class DbusObject(dbus.service.Object):
|
|||
raise DeferredNotAsync
|
||||
return result
|
||||
|
||||
### signals ###
|
||||
### signals ###
|
||||
|
||||
@dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX,
|
||||
signature='')
|
||||
|
|
@ -106,14 +106,14 @@ class DbusObject(dbus.service.Object):
|
|||
|
||||
##SIGNALS_PART##
|
||||
|
||||
### methods ###
|
||||
|
||||
### methods ###
|
||||
|
||||
##METHODS_PART##
|
||||
|
||||
|
||||
def __attributes(self, in_sign):
|
||||
"""Return arguments to user given a in_sign
|
||||
@param in_sign: in_sign in the short form (using s,a,i,b etc)
|
||||
@return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
@return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")"""
|
||||
i=0
|
||||
idx=0
|
||||
attr=[]
|
||||
|
|
@ -152,19 +152,19 @@ class DbusObject(dbus.service.Object):
|
|||
|
||||
_arguments = inspect_args.args
|
||||
_defaults = list(inspect_args.defaults or [])
|
||||
|
||||
|
||||
if inspect.ismethod(method):
|
||||
#if we have a method, we don't want the first argument (usually 'self')
|
||||
del(_arguments[0])
|
||||
|
||||
#first arguments are for the _callback method
|
||||
arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments))
|
||||
|
||||
|
||||
if async:
|
||||
_arguments.extend(['callback','errback'])
|
||||
_defaults.extend([None, None])
|
||||
|
||||
|
||||
|
||||
|
||||
#now we create a second list with default values
|
||||
for i in range(1, len(_defaults)+1):
|
||||
_arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i]))
|
||||
|
|
@ -182,7 +182,7 @@ class DbusObject(dbus.service.Object):
|
|||
function = getattr(self, name)
|
||||
func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface]
|
||||
func_table[function.__name__] = function #Needed for introspection
|
||||
|
||||
|
||||
def addSignal(self, name, int_suffix, signature, doc={}):
|
||||
"""Dynamically add a signal to Dbus Bridge"""
|
||||
attributes = ', '.join(self.__attributes(signature))
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ class DBusBridgeFrontend(BridgeFrontend):
|
|||
# - or if the last two arguments are callable
|
||||
|
||||
async = False
|
||||
|
||||
|
||||
if kwargs:
|
||||
if 'callback' in kwargs and 'errback' in kwargs:
|
||||
async = True
|
||||
|
|
@ -84,26 +84,26 @@ class DBusBridgeFrontend(BridgeFrontend):
|
|||
args = list(args)
|
||||
_errback = args.pop()
|
||||
_callback = args.pop()
|
||||
|
||||
|
||||
method = getattr(self.db_plugin_iface, name)
|
||||
|
||||
|
||||
if async:
|
||||
kwargs['reply_handler'] = _callback
|
||||
kwargs['error_handler'] = lambda err:_errback(err._dbus_error_name[len(const_ERROR_PREFIX)+1:])
|
||||
|
||||
return method(*args, **kwargs)
|
||||
|
||||
|
||||
return getPluginMethod
|
||||
|
||||
##METHODS_PART##
|
||||
|
||||
#methods from plugins
|
||||
|
||||
|
||||
def joinMUC(self, room_jid, nick, options, profile_key):
|
||||
if options == None:
|
||||
options = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature
|
||||
return self.db_plugin_iface.joinMUC(room_jid, nick, options, profile_key)
|
||||
|
||||
|
||||
def gatewayRegister(self, action, target, data, profile_key):
|
||||
if data == None:
|
||||
data = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ def sat_next_id():
|
|||
return "sat_id_"+str(sat_id)
|
||||
|
||||
class SAT(service.Service):
|
||||
|
||||
|
||||
def get_next_id(self):
|
||||
return sat_next_id()
|
||||
|
||||
|
|
@ -87,26 +87,26 @@ class SAT(service.Service):
|
|||
"""Save a constant"""
|
||||
if CONST.has_key(name):
|
||||
error(_('Trying to redefine a constant'))
|
||||
raise Exception
|
||||
raise Exception
|
||||
CONST[name] = value
|
||||
|
||||
|
||||
def __init__(self):
|
||||
#TODO: standardize callback system
|
||||
|
||||
self.__general_cb_map = {} #callback called for general reasons (key = name)
|
||||
|
||||
self.__general_cb_map = {} #callback called for general reasons (key = name)
|
||||
self.__private_data = {} #used for internal callbacks (key = id)
|
||||
self.profiles = {}
|
||||
self.plugins = {}
|
||||
self.menus = {} #used to know which new menus are wanted by plugins
|
||||
|
||||
|
||||
self.memory=Memory(self)
|
||||
|
||||
|
||||
local_dir = self.memory.getConfig('', 'local_dir')
|
||||
if not os.path.exists(local_dir):
|
||||
os.makedirs(local_dir)
|
||||
|
||||
self.trigger = TriggerManager() #trigger are used to change SàT behaviour
|
||||
|
||||
self.trigger = TriggerManager() #trigger are used to change SàT behaviour
|
||||
|
||||
self.bridge=DBusBridge()
|
||||
self.bridge.register("getVersion", lambda: self.get_const('client_version'))
|
||||
self.bridge.register("getProfileName", self.memory.getProfileName)
|
||||
|
|
@ -147,8 +147,8 @@ class SAT(service.Service):
|
|||
self.bridge.register("getMenus", self.getMenus)
|
||||
self.bridge.register("getMenuHelp", self.getMenuHelp)
|
||||
self.bridge.register("callMenu", self.callMenu)
|
||||
|
||||
self.memory.initialized.addCallback(self._postMemoryInit)
|
||||
|
||||
self.memory.initialized.addCallback(self._postMemoryInit)
|
||||
|
||||
def _postMemoryInit(self, ignore):
|
||||
"""Method called after memory initialization is done"""
|
||||
|
|
@ -159,7 +159,7 @@ class SAT(service.Service):
|
|||
def _import_plugins(self):
|
||||
"""Import all plugins found in plugins directory"""
|
||||
import sat.plugins
|
||||
plugins_path = os.path.dirname(sat.plugins.__file__)
|
||||
plugins_path = os.path.dirname(sat.plugins.__file__)
|
||||
plug_lst = [os.path.splitext(plugin)[0] for plugin in map(os.path.basename,glob(os.path.join(plugins_path,"plugin*.py")))]
|
||||
__plugins_to_import = {} #plugins we still have to import
|
||||
for plug in plug_lst:
|
||||
|
|
@ -198,11 +198,11 @@ class SAT(service.Service):
|
|||
self.plugins[import_name].is_handler = False
|
||||
#TODO: test xmppclient presence and register handler parent
|
||||
|
||||
|
||||
|
||||
def connect(self, profile_key = '@DEFAULT@'):
|
||||
"""Connect to jabber server"""
|
||||
self.asyncConnect(profile_key)
|
||||
|
||||
|
||||
def asyncConnect(self, profile_key = '@DEFAULT@'):
|
||||
"""Connect to jabber server with asynchronous reply
|
||||
@param profile_key: %(doc_profile)s
|
||||
|
|
@ -212,7 +212,7 @@ class SAT(service.Service):
|
|||
if not profile:
|
||||
error (_('Trying to connect a non-exsitant profile'))
|
||||
raise ProfileUnknownError(profile_key)
|
||||
|
||||
|
||||
if (self.isConnected(profile)):
|
||||
info(_("already connected !"))
|
||||
return defer.succeed("None")
|
||||
|
|
@ -227,12 +227,12 @@ class SAT(service.Service):
|
|||
current = self.profiles[profile] = xmpp.SatXMPPClient(self, profile,
|
||||
jid.JID(self.memory.getParamA("JabberID", "Connection", profile_key = profile), profile),
|
||||
self.memory.getParamA("Password", "Connection", profile_key = profile),
|
||||
self.memory.getParamA("Server", "Connection", profile_key = profile),
|
||||
self.memory.getParamA("Server", "Connection", profile_key = profile),
|
||||
port)
|
||||
|
||||
current.messageProt = xmpp.SatMessageProtocol(self)
|
||||
current.messageProt.setHandlerParent(current)
|
||||
|
||||
|
||||
current.roster = xmpp.SatRosterProtocol(self)
|
||||
current.roster.setHandlerParent(current)
|
||||
|
||||
|
|
@ -247,7 +247,7 @@ class SAT(service.Service):
|
|||
current.versionHandler.setHandlerParent(current)
|
||||
|
||||
debug (_("setting plugins parents"))
|
||||
|
||||
|
||||
for plugin in self.plugins.iteritems():
|
||||
if plugin[1].is_handler:
|
||||
plugin[1].getHandler(profile).setHandlerParent(current)
|
||||
|
|
@ -307,7 +307,7 @@ class SAT(service.Service):
|
|||
info("Salut à toi ô mon frère !")
|
||||
#TODO: manage autoconnect
|
||||
#self.connect()
|
||||
|
||||
|
||||
def stopService(self):
|
||||
self.memory.save()
|
||||
info("Salut aussi à Rantanplan")
|
||||
|
|
@ -315,13 +315,13 @@ class SAT(service.Service):
|
|||
def run(self):
|
||||
debug(_("running app"))
|
||||
reactor.run()
|
||||
|
||||
|
||||
def stop(self):
|
||||
debug(_("stopping app"))
|
||||
reactor.stop()
|
||||
|
||||
|
||||
## Misc methods ##
|
||||
|
||||
|
||||
def getJidNStream(self, profile_key):
|
||||
"""Convenient method to get jid and stream from profile key
|
||||
@return: tuple (jid, xmlstream) from profile, can be None"""
|
||||
|
|
@ -347,8 +347,8 @@ class SAT(service.Service):
|
|||
serverRegistrer = xmlstream.XmlStreamFactory(xmpp.RegisteringAuthenticator(self, server, login, password, email, next_id, profile))
|
||||
connector = reactor.connectTCP(server, port, serverRegistrer)
|
||||
serverRegistrer.clientConnectionLost = lambda conn, reason: connector.disconnect()
|
||||
|
||||
return next_id
|
||||
|
||||
return next_id
|
||||
|
||||
def registerNewAccountCB(self, id, data, profile):
|
||||
user = jid.parse(self.memory.getParamA("JabberID", "Connection", profile_key=profile))[0]
|
||||
|
|
@ -363,7 +363,7 @@ class SAT(service.Service):
|
|||
|
||||
confirm_id = sat_next_id()
|
||||
self.__private_data[confirm_id]=(id,profile)
|
||||
|
||||
|
||||
self.askConfirmation(confirm_id, "YES/NO",
|
||||
{"message":_("Are you sure to register new account [%(user)s] to server %(server)s ?") % {'user':user, 'server':server, 'profile':profile}},
|
||||
self.regisConfirmCB, profile)
|
||||
|
|
@ -393,7 +393,7 @@ class SAT(service.Service):
|
|||
profile = self.memory.getProfileName(profile_key)
|
||||
assert(profile)
|
||||
to_jid = jid.JID(target)
|
||||
|
||||
|
||||
iq = compat.IQ(self.profiles[profile].xmlstream, 'set')
|
||||
iq["to"] = target
|
||||
iq["from"] = self.profiles[profile].jid.full()
|
||||
|
|
@ -456,7 +456,7 @@ class SAT(service.Service):
|
|||
|
||||
|
||||
## jabber methods ##
|
||||
|
||||
|
||||
def getWaitingConf(self, profile_key=None):
|
||||
assert(profile_key)
|
||||
client = self.getClient(profile_key)
|
||||
|
|
@ -467,22 +467,22 @@ class SAT(service.Service):
|
|||
conf_type, data = client._waiting_conf[conf_id][:2]
|
||||
ret.append((conf_id, conf_type, data))
|
||||
return ret
|
||||
|
||||
|
||||
def sendMessage(self, to, msg, subject=None, mess_type='auto', profile_key='@DEFAULT@'):
|
||||
#FIXME: check validity of recipient
|
||||
profile = self.memory.getProfileName(profile_key)
|
||||
assert(profile)
|
||||
client = self.profiles[profile]
|
||||
current_jid = client.jid
|
||||
mess_data = { #we put data in a dict, so trigger methods can change them
|
||||
mess_data = { #we put data in a dict, so trigger methods can change them
|
||||
"to": jid.JID(to),
|
||||
"message": msg,
|
||||
"subject": subject,
|
||||
"type": mess_type
|
||||
}
|
||||
|
||||
|
||||
if mess_data["type"] == "auto":
|
||||
# we try to guess the type
|
||||
# we try to guess the type
|
||||
if mess_data["subject"]:
|
||||
mess_data["type"] = 'normal'
|
||||
elif not mess_data["to"].resource: #if to JID has a resource, the type is not 'groupchat'
|
||||
|
|
@ -492,7 +492,7 @@ class SAT(service.Service):
|
|||
#FIXME: should entity_type manage ressources ?
|
||||
except (UnknownEntityError, KeyError):
|
||||
entity_type = "contact"
|
||||
|
||||
|
||||
if entity_type == "chatroom":
|
||||
mess_data["type"] = 'groupchat'
|
||||
else:
|
||||
|
|
@ -500,10 +500,10 @@ class SAT(service.Service):
|
|||
else:
|
||||
mess_data["type"] == 'chat'
|
||||
mess_data["type"] == "chat" if mess_data["subject"] else "normal"
|
||||
|
||||
|
||||
if not self.trigger.point("sendMessage", mess_data, profile):
|
||||
return
|
||||
|
||||
|
||||
debug(_("Sending jabber message of type [%(type)s] to %(to)s...") % {"type": mess_data["type"], "to": to})
|
||||
message = domish.Element((None,'message'))
|
||||
message["to"] = mess_data["to"].full()
|
||||
|
|
@ -531,8 +531,8 @@ class SAT(service.Service):
|
|||
del statuses['']
|
||||
self.bridge.presenceUpdate(self.profiles[profile].jid.full(), show,
|
||||
int(priority), statuses, profile)
|
||||
|
||||
|
||||
|
||||
|
||||
def subscription(self, subs_type, raw_jid, profile_key):
|
||||
"""Called to manage subscription
|
||||
@param subs_type: subsciption type (cf RFC 3921)
|
||||
|
|
@ -592,31 +592,31 @@ class SAT(service.Service):
|
|||
def serverDiscoItems(self, disco_result, disco_client, profile, initialized):
|
||||
"""xep-0030 Discovery Protocol.
|
||||
@param disco_result: result of the disco item querry
|
||||
@param disco_client: SatDiscoProtocol instance
|
||||
@param profile: profile of the user
|
||||
@param disco_client: SatDiscoProtocol instance
|
||||
@param profile: profile of the user
|
||||
@param initialized: deferred which must be chained when everything is done"""
|
||||
|
||||
|
||||
def _check_entity_cb(result, entity, profile):
|
||||
for category, type in result.identities:
|
||||
debug (_('Identity added: (%(category)s,%(type)s) ==> %(entity)s [%(profile)s]') % {
|
||||
'category':category, 'type':type, 'entity':entity, 'profile':profile})
|
||||
self.memory.addServerIdentity(category, type, entity, profile)
|
||||
self.memory.addServerIdentity(category, type, entity, profile)
|
||||
|
||||
def _errback(result, entity, profile):
|
||||
warning(_("Can't get information on identity [%(entity)s] for profile [%(profile)s]") % {'entity':entity, 'profile': profile})
|
||||
|
||||
|
||||
defer_list = []
|
||||
for item in disco_result._items:
|
||||
if item.entity.full().count('.') == 1: #XXX: workaround for a bug on jabberfr, tmp
|
||||
warning(_('Using jabberfr workaround, be sure your domain has at least two levels (e.g. "example.tld", not "example" alone)'))
|
||||
continue
|
||||
args = [item.entity, profile]
|
||||
args = [item.entity, profile]
|
||||
defer_list.append(disco_client.requestInfo(item.entity).addCallbacks(_check_entity_cb, _errback, args, None, args))
|
||||
defer.DeferredList(defer_list).chainDeferred(initialized)
|
||||
|
||||
|
||||
## Generic HMI ##
|
||||
|
||||
|
||||
## Generic HMI ##
|
||||
|
||||
def actionResult(self, action_id, action_type, data, profile):
|
||||
"""Send the result of an action
|
||||
@param action_id: same action_id used with action
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ from calendar import timegm
|
|||
|
||||
|
||||
class SatXMPPClient(client.XMPPClient):
|
||||
|
||||
|
||||
def __init__(self, host_app, profile, user_jid, password, host=None, port=5222):
|
||||
client.XMPPClient.__init__(self, user_jid, password, host, port)
|
||||
self.factory.clientConnectionLost = self.connectionLost
|
||||
|
|
@ -39,7 +39,7 @@ class SatXMPPClient(client.XMPPClient):
|
|||
self.conn_deferred = defer.Deferred()
|
||||
self._waiting_conf = {} #callback called when a confirmation is received
|
||||
self._progress_cb_map = {} #callback called when a progress is requested (key = progress id)
|
||||
|
||||
|
||||
|
||||
def getConnectionDeferred(self):
|
||||
"""Return a deferred which fire when the client is connected"""
|
||||
|
|
@ -53,28 +53,28 @@ class SatXMPPClient(client.XMPPClient):
|
|||
info (_("********** [%s] CONNECTED **********") % self.profile)
|
||||
self.streamInitialized()
|
||||
self.host_app.bridge.connected(self.profile) #we send the signal to the clients
|
||||
|
||||
|
||||
|
||||
def streamInitialized(self):
|
||||
"""Called after _authd"""
|
||||
debug (_("XML stream is initialized"))
|
||||
self.keep_alife = task.LoopingCall(self.xmlstream.send, " ") #Needed to avoid disconnection (specially with openfire)
|
||||
self.keep_alife.start(180)
|
||||
|
||||
|
||||
self.disco = SatDiscoProtocol(self)
|
||||
self.disco.setHandlerParent(self)
|
||||
self.discoHandler = disco.DiscoHandler()
|
||||
self.discoHandler.setHandlerParent(self)
|
||||
|
||||
|
||||
if not self.host_app.trigger.point("Disco Handled", self.profile):
|
||||
return
|
||||
|
||||
self.roster.requestRoster()
|
||||
|
||||
|
||||
self.presence.available()
|
||||
|
||||
|
||||
self.disco.requestInfo(jid.JID(self.jid.host)).addCallback(self.host_app.serverDisco, self.profile) #FIXME: use these informations
|
||||
|
||||
|
||||
self.disco.requestItems(jid.JID(self.jid.host)).addCallback(self.host_app.serverDiscoItems, self.disco, self.profile, self.client_initialized)
|
||||
self.conn_deferred.callback(None)
|
||||
|
||||
|
|
@ -90,7 +90,7 @@ class SatXMPPClient(client.XMPPClient):
|
|||
|
||||
def isConnected(self):
|
||||
return self.__connected
|
||||
|
||||
|
||||
def connectionLost(self, connector, unused_reason):
|
||||
self.__connected=False
|
||||
info (_("********** [%s] DISCONNECTED **********") % self.profile)
|
||||
|
|
@ -103,7 +103,7 @@ class SatXMPPClient(client.XMPPClient):
|
|||
|
||||
|
||||
class SatMessageProtocol(xmppim.MessageProtocol):
|
||||
|
||||
|
||||
def __init__(self, host):
|
||||
xmppim.MessageProtocol.__init__(self)
|
||||
self.host = host
|
||||
|
|
@ -128,7 +128,7 @@ class SatMessageProtocol(xmppim.MessageProtocol):
|
|||
self.host.memory.addToHistory(jid.JID(message["from"]), jid.JID(message["to"]), mess_body, mess_type, profile=self.parent.profile)
|
||||
self.host.bridge.newMessage(message["from"], mess_body, mess_type, message['to'], extra, profile=self.parent.profile)
|
||||
break
|
||||
|
||||
|
||||
class SatRosterProtocol(xmppim.RosterClientProtocol):
|
||||
|
||||
def __init__(self, host):
|
||||
|
|
@ -138,7 +138,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
#XXX: the two following dicts keep a local copy of the roster
|
||||
self._groups = {} #map from groups to bare jids: key=group value=set of bare jids
|
||||
self._jids = {} #map from bare jids to RosterItem: key=jid value=RosterItem
|
||||
|
||||
|
||||
def rosterCb(self, roster):
|
||||
for raw_jid, item in roster.iteritems():
|
||||
self.onRosterSet(item)
|
||||
|
|
@ -153,7 +153,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
"""Remove a contact from roster list"""
|
||||
xmppim.RosterClientProtocol.removeItem(self, to)
|
||||
#TODO: check IQ result
|
||||
|
||||
|
||||
#XXX: disabled (cf http://wokkel.ik.nu/ticket/56))
|
||||
#def addItem(self, to):
|
||||
#"""Add a contact to roster list"""
|
||||
|
|
@ -187,7 +187,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
if item.name:
|
||||
item_attr['name'] = item.name
|
||||
return item_attr
|
||||
|
||||
|
||||
def onRosterSet(self, item):
|
||||
"""Called when a new/update roster item is received"""
|
||||
#TODO: send a signal to frontends
|
||||
|
|
@ -199,13 +199,13 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
return
|
||||
info (_("new contact in roster list: %s"), item.jid.full())
|
||||
#self.host.memory.addContact(item.jid, item_attr, item.groups, self.parent.profile)
|
||||
|
||||
|
||||
bare_jid = item.jid.userhost()
|
||||
self._jids[bare_jid] = item
|
||||
for group in item.groups:
|
||||
self._groups.setdefault(group,set()).add(bare_jid)
|
||||
self.host.bridge.newContact(item.jid.full(), self.getAttributes(item), item.groups, self.parent.profile)
|
||||
|
||||
|
||||
def onRosterRemove(self, entity):
|
||||
"""Called when a roster removal event is received"""
|
||||
print _("removing %s from roster list") % entity.full()
|
||||
|
|
@ -226,7 +226,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
except KeyError:
|
||||
log.warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" %
|
||||
{"group": group, "jid": bare_jid})
|
||||
|
||||
|
||||
#then we send the bridge signal
|
||||
self.host.bridge.contactDeleted(entity.userhost(), self.parent.profile)
|
||||
|
||||
|
|
@ -247,7 +247,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
def isJidInRoster(self, entity_jid):
|
||||
"""Return True if jid is in roster"""
|
||||
return entity_jid.userhost() in self._jids
|
||||
|
||||
|
||||
def getItems(self):
|
||||
"""Return all items of the roster"""
|
||||
return self._jids.values()
|
||||
|
|
@ -257,20 +257,20 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
|
|||
return self._groups[group]
|
||||
except KeyError:
|
||||
return exceptions.UnknownGroupError
|
||||
|
||||
|
||||
|
||||
class SatPresenceProtocol(xmppim.PresenceClientProtocol):
|
||||
|
||||
def __init__(self, host):
|
||||
xmppim.PresenceClientProtocol.__init__(self)
|
||||
self.host = host
|
||||
|
||||
|
||||
def availableReceived(self, entity, show=None, statuses=None, priority=0):
|
||||
debug (_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity':entity, 'show':show, 'statuses':statuses, 'priority':priority})
|
||||
|
||||
|
||||
if not statuses:
|
||||
statuses = {}
|
||||
|
||||
|
||||
if statuses.has_key(None): #we only want string keys
|
||||
statuses["default"] = statuses[None]
|
||||
del statuses[None]
|
||||
|
|
@ -281,13 +281,13 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
|
|||
#now it's time to notify frontends
|
||||
self.host.bridge.presenceUpdate(entity.full(), show or "",
|
||||
int(priority), statuses, self.parent.profile)
|
||||
|
||||
|
||||
def unavailableReceived(self, entity, statuses=None):
|
||||
debug (_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity':entity, 'statuses':statuses})
|
||||
|
||||
|
||||
if not statuses:
|
||||
statuses = {}
|
||||
|
||||
|
||||
if statuses.has_key(None): #we only want string keys
|
||||
statuses["default"] = statuses[None]
|
||||
del statuses[None]
|
||||
|
|
@ -295,13 +295,13 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
|
|||
|
||||
#now it's time to notify frontends
|
||||
self.host.bridge.presenceUpdate(entity.full(), "unavailable", 0, statuses, self.parent.profile)
|
||||
|
||||
|
||||
|
||||
|
||||
def available(self, entity=None, show=None, statuses=None, priority=0):
|
||||
if not statuses:
|
||||
statuses = {}
|
||||
# default for us is None for wokkel
|
||||
# so we must temporarily switch to wokkel's convention...
|
||||
# so we must temporarily switch to wokkel's convention...
|
||||
if 'default' in statuses:
|
||||
statuses[None] = statuses['default']
|
||||
|
||||
|
|
@ -380,10 +380,10 @@ class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
|
|||
self.answer_id = answer_id
|
||||
self.profile = profile
|
||||
print _("Registration asked for"),user_login, user_pass, jabber_host
|
||||
|
||||
|
||||
def connectionMade(self):
|
||||
print "connectionMade"
|
||||
|
||||
|
||||
self.xmlstream.namespace = "jabber:client"
|
||||
self.xmlstream.sendHeader()
|
||||
|
||||
|
|
@ -405,7 +405,7 @@ class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
|
|||
answer_data={"message":_("Registration successfull")}
|
||||
self.host.bridge.actionResult(answer_type, self.answer_id, answer_data, self.profile)
|
||||
self.xmlstream.sendFooter()
|
||||
|
||||
|
||||
def registrationFailure(self, failure):
|
||||
info (_("Registration failure: %s") % str(failure.value))
|
||||
answer_type = "ERROR"
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ SAVEFILE_DATABASE="/sat.db"
|
|||
class Params():
|
||||
"""This class manage parameters with xml"""
|
||||
### TODO: add desciption in params
|
||||
|
||||
|
||||
#TODO: move Watched in a plugin
|
||||
default_xml = u"""
|
||||
<params>
|
||||
|
|
@ -84,7 +84,7 @@ class Params():
|
|||
source_set = set(source_map.keys())
|
||||
dest_set = set(dest_map.keys())
|
||||
to_add = source_set.difference(dest_set)
|
||||
|
||||
|
||||
for node_key in to_add:
|
||||
dest_node.appendChild(source_map[node_key].cloneNode(True))
|
||||
|
||||
|
|
@ -97,12 +97,12 @@ class Params():
|
|||
self.dom = minidom.parse(xml_file)
|
||||
default_dom = minidom.parseString(Params.default_xml.encode('utf-8'))
|
||||
self._mergeParams(default_dom.documentElement, self.dom.documentElement)
|
||||
|
||||
|
||||
def loadGenParams(self):
|
||||
"""Load general parameters data from storage
|
||||
@return: deferred triggered once params are loaded"""
|
||||
return self.storage.loadGenParams(self.params_gen)
|
||||
|
||||
|
||||
def loadIndParams(self, profile, cache=None):
|
||||
"""Load individual parameters
|
||||
set self.params cache or a temporary cache
|
||||
|
|
@ -112,7 +112,7 @@ class Params():
|
|||
if cache == None:
|
||||
self.params[profile] = {}
|
||||
return self.storage.loadIndParams(self.params[profile] if cache==None else cache, profile)
|
||||
|
||||
|
||||
def purgeProfile(self, profile):
|
||||
"""Remove cache data of a profile
|
||||
@param profile: %(doc_profile)s"""
|
||||
|
|
@ -279,7 +279,7 @@ class Params():
|
|||
@param category: category of the parameter
|
||||
@param attr: name of the attribute (default: "value")
|
||||
@param profile: owner of the param (@ALL@ for everyone)
|
||||
|
||||
|
||||
@return: attribute"""
|
||||
#FIXME: looks really dirty and buggy, need to be reviewed/refactored
|
||||
node = self.__getParamNode(name, category)
|
||||
|
|
@ -290,19 +290,19 @@ class Params():
|
|||
if node[0] == 'general':
|
||||
value = self.__getParam(None, category, name, 'general')
|
||||
return self.__getAttr(node[1], attr, value)
|
||||
|
||||
|
||||
assert(node[0] == 'individual')
|
||||
|
||||
profile = self.getProfileName(profile_key)
|
||||
if not profile:
|
||||
error(_('Requesting a param for an non-existant profile'))
|
||||
raise exceptions.ProfileUnknownError
|
||||
|
||||
|
||||
if profile not in self.params:
|
||||
error(_('Requesting synchronous param for not connected profile'))
|
||||
raise exceptions.NotConnectedProfileError(profile)
|
||||
|
||||
if attr == "value":
|
||||
if attr == "value":
|
||||
value = self.__getParam(profile, category, name)
|
||||
return self.__getAttr(node[1], attr, value)
|
||||
|
||||
|
|
@ -325,15 +325,15 @@ class Params():
|
|||
if node[0] == 'general':
|
||||
value = self.__getParam(None, category, name, 'general')
|
||||
return defer.succeed(self.__getAttr(node[1], attr, value))
|
||||
|
||||
|
||||
assert(node[0] == 'individual')
|
||||
|
||||
profile = self.getProfileName(profile_key)
|
||||
if not profile:
|
||||
error(_('Requesting a param for a non-existant profile'))
|
||||
return defer.fail()
|
||||
|
||||
if attr != "value":
|
||||
|
||||
if attr != "value":
|
||||
return defer.succeed(node[1].getAttribute(attr))
|
||||
try:
|
||||
value = self.__getParam(profile, category, name)
|
||||
|
|
@ -396,7 +396,7 @@ class Params():
|
|||
|
||||
for param_node in params:
|
||||
name = param_node.getAttribute('name')
|
||||
|
||||
|
||||
if name not in dest_params:
|
||||
dest_params[name] = param_node.cloneNode(True)
|
||||
dest_cat.appendChild(dest_params[name])
|
||||
|
|
@ -407,8 +407,8 @@ class Params():
|
|||
if new_node:
|
||||
prof_xml.documentElement.appendChild(dest_cat)
|
||||
return prof_xml
|
||||
|
||||
|
||||
|
||||
|
||||
if self.params.has_key(profile):
|
||||
d = defer.succeed(None)
|
||||
profile_cache = self.params[profile]
|
||||
|
|
@ -435,13 +435,13 @@ class Params():
|
|||
if not profile:
|
||||
error(_("Asking params for inexistant profile"))
|
||||
return ""
|
||||
|
||||
|
||||
def returnXML(prof_xml):
|
||||
return_xml = prof_xml.toxml()
|
||||
prof_xml.unlink()
|
||||
return return_xml
|
||||
|
||||
return self.__constructProfileXml(profile).addCallback(returnXML)
|
||||
return self.__constructProfileXml(profile).addCallback(returnXML)
|
||||
|
||||
def getParamsForCategory(self, category, profile_key):
|
||||
"""Return node's xml for selected category"""
|
||||
|
|
@ -460,7 +460,7 @@ class Params():
|
|||
|
||||
prof_xml.unlink()
|
||||
return "<category />"
|
||||
|
||||
|
||||
d = self.__constructProfileXml(profile)
|
||||
return d.addCallback(returnCategoryXml)
|
||||
|
||||
|
|
@ -475,7 +475,7 @@ class Params():
|
|||
@return: a tuple with the node type and the the node, or None if not found"""
|
||||
|
||||
for type_node in self.dom.documentElement.childNodes:
|
||||
if ( ((_type == "@ALL@" or _type == "@GENERAL@") and type_node.nodeName == 'general')
|
||||
if ( ((_type == "@ALL@" or _type == "@GENERAL@") and type_node.nodeName == 'general')
|
||||
or ( (_type == "@ALL@" or _type == "@INDIVIDUAL@") and type_node.nodeName == 'individual') ):
|
||||
for node in type_node.getElementsByTagName('category'):
|
||||
if node.getAttribute("name") == category:
|
||||
|
|
@ -484,7 +484,7 @@ class Params():
|
|||
if param.getAttribute("name") == name:
|
||||
return (type_node.nodeName, param)
|
||||
return None
|
||||
|
||||
|
||||
def getParamsCategories(self):
|
||||
"""return the categories availables"""
|
||||
categories=[]
|
||||
|
|
@ -507,7 +507,7 @@ class Params():
|
|||
if not node:
|
||||
error(_('Requesting an unknown parameter (%(category)s/%(name)s)') % {'category':category, 'name':name})
|
||||
return
|
||||
|
||||
|
||||
if node[0] == 'general':
|
||||
self.params_gen[(category, name)] = value
|
||||
self.storage.setGenParam(category, name, value)
|
||||
|
|
@ -515,10 +515,10 @@ class Params():
|
|||
if self.host.isConnected(profile):
|
||||
self.host.bridge.paramUpdate(name, value, category, profile)
|
||||
return
|
||||
|
||||
|
||||
assert (node[0] == 'individual')
|
||||
assert (profile_key != "@NONE@")
|
||||
|
||||
|
||||
_type = node[1].getAttribute("type")
|
||||
if _type=="button":
|
||||
print "clique",node.toxml()
|
||||
|
|
@ -533,7 +533,7 @@ class Memory:
|
|||
|
||||
def __init__(self, host):
|
||||
info (_("Memory manager init"))
|
||||
self.initialized = defer.Deferred()
|
||||
self.initialized = defer.Deferred()
|
||||
self.host = host
|
||||
self.entitiesCache={} #XXX: keep presence/last resource/other data in cache
|
||||
# /!\ an entity is not necessarily in roster
|
||||
|
|
@ -611,7 +611,7 @@ class Memory:
|
|||
@param profile: %(doc_profile)s"""
|
||||
info(_("[%s] Profile session started" % profile))
|
||||
self.entitiesCache[profile] = {}
|
||||
|
||||
|
||||
def purgeProfileSession(self, profile):
|
||||
"""Delete cache of data of profile
|
||||
@param profile: %(doc_profile)s"""
|
||||
|
|
@ -628,7 +628,7 @@ class Memory:
|
|||
#TODO: need to encrypt files (at least passwords !) and set permissions
|
||||
param_file_xml = os.path.expanduser(self.getConfig('','local_dir')+
|
||||
self.host.get_const('savefile_param_xml'))
|
||||
|
||||
|
||||
self.params.save_xml(param_file_xml)
|
||||
debug(_("params saved"))
|
||||
|
||||
|
|
@ -647,13 +647,13 @@ class Memory:
|
|||
@param name: Profile name
|
||||
"""
|
||||
return self.params.createProfile(name)
|
||||
|
||||
|
||||
def asyncCreateProfile(self, name):
|
||||
"""Create a new profile
|
||||
@param name: Profile name
|
||||
"""
|
||||
return self.params.asyncCreateProfile(name)
|
||||
|
||||
|
||||
def deleteProfile(self, name):
|
||||
"""Delete an existing profile
|
||||
@param name: Name of the profile"""
|
||||
|
|
@ -674,7 +674,7 @@ class Memory:
|
|||
if not self.server_features.has_key(profile):
|
||||
self.server_features[profile] = []
|
||||
self.server_features[profile].append(feature)
|
||||
|
||||
|
||||
def addServerIdentity(self, category, _type, entity, profile):
|
||||
"""Add an identity discovered from server
|
||||
@param feature: string of the feature
|
||||
|
|
@ -727,7 +727,7 @@ class Memory:
|
|||
return self.entitiesCache[profile][entity]["last_resource"]
|
||||
except KeyError:
|
||||
return ""
|
||||
|
||||
|
||||
def getPresenceStatus(self, profile_key):
|
||||
profile = self.getProfileName(profile_key)
|
||||
if not profile:
|
||||
|
|
@ -782,7 +782,7 @@ class Memory:
|
|||
if there is no value of a given key, resulting dict will
|
||||
have nothing with that key nether
|
||||
@raise: exceptions.UnknownEntityError if entity is not in cache
|
||||
exceptions.ProfileNotInCacheError if profile is not in cache
|
||||
exceptions.ProfileNotInCacheError if profile is not in cache
|
||||
"""
|
||||
profile = self.getProfileName(profile_key)
|
||||
if not profile:
|
||||
|
|
@ -819,14 +819,14 @@ class Memory:
|
|||
if not self.subscriptions.has_key(profile):
|
||||
self.subscriptions[profile] = {}
|
||||
self.subscriptions[profile][entity_jid] = _type
|
||||
|
||||
|
||||
def delWaitingSub(self, entity_jid, profile_key):
|
||||
"""Called when a subcription request is finished"""
|
||||
profile = self.getProfileName(profile_key)
|
||||
assert(profile)
|
||||
if self.subscriptions.has_key(profile) and self.subscriptions[profile].has_key(entity_jid):
|
||||
del self.subscriptions[profile][entity_jid]
|
||||
|
||||
|
||||
def getWaitingSub(self, profile_key):
|
||||
"""Called to get a list of currently waiting subscription requests"""
|
||||
profile = self.getProfileName(profile_key)
|
||||
|
|
@ -835,38 +835,38 @@ class Memory:
|
|||
return {}
|
||||
if not self.subscriptions.has_key(profile):
|
||||
return {}
|
||||
|
||||
|
||||
return self.subscriptions[profile]
|
||||
|
||||
def getStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
|
||||
return self.params.getStringParamA(name, category, attr, profile_key)
|
||||
|
||||
|
||||
def getParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
|
||||
return self.params.getParamA(name, category, attr, profile_key)
|
||||
|
||||
|
||||
def asyncGetParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
|
||||
return self.params.asyncGetParamA(name, category, attr, profile_key)
|
||||
|
||||
|
||||
def asyncGetStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'):
|
||||
return self.params.asyncGetStringParamA(name, category, attr, profile_key)
|
||||
|
||||
|
||||
def getParamsUI(self, profile_key):
|
||||
return self.params.getParamsUI(profile_key)
|
||||
|
||||
|
||||
def getParams(self, profile_key):
|
||||
return self.params.getParams(profile_key)
|
||||
|
||||
return self.params.getParams(profile_key)
|
||||
|
||||
def getParamsForCategory(self, category, profile_key):
|
||||
return self.params.getParamsForCategory(category, profile_key)
|
||||
|
||||
return self.params.getParamsForCategory(category, profile_key)
|
||||
|
||||
def getParamsCategories(self):
|
||||
return self.params.getParamsCategories()
|
||||
|
||||
|
||||
def setParam(self, name, value, category, profile_key):
|
||||
return self.params.setParam(name, value, category, profile_key)
|
||||
|
||||
def importParams(self, xml):
|
||||
return self.params.importParams(xml)
|
||||
|
||||
|
||||
def setDefault(self, name, category, callback, errback=None):
|
||||
return self.params.setDefault(name, category, callback, errback)
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ class PersistentDict:
|
|||
|
||||
def __cmp__(self, other):
|
||||
return self._cache.__cmp__(other)
|
||||
|
||||
|
||||
def __hash__(self):
|
||||
return self._cache.__hash__()
|
||||
|
||||
|
|
@ -117,7 +117,7 @@ class PersistentDict:
|
|||
|
||||
class PersistentBinaryDict(PersistentDict):
|
||||
"""Persistent dict where value can be any python data (instead of string only)"""
|
||||
|
||||
|
||||
def load(self):
|
||||
"""load persistent data from storage
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ class SqliteStorage():
|
|||
def fillProfileCache(ignore):
|
||||
d = self.dbpool.runQuery("SELECT name,id FROM profiles").addCallback(self._profilesCache)
|
||||
d.chainDeferred(self.initialized)
|
||||
|
||||
|
||||
defer.DeferredList(init_defers).addCallback(fillProfileCache)
|
||||
|
||||
#Profiles
|
||||
|
|
@ -77,8 +77,8 @@ class SqliteStorage():
|
|||
@param profiles_result: result of the sql profiles query"""
|
||||
for profile in profiles_result:
|
||||
name, id = profile
|
||||
self.profiles[name] = id
|
||||
|
||||
self.profiles[name] = id
|
||||
|
||||
def getProfilesList(self):
|
||||
""""Return list of all registered profiles"""
|
||||
return self.profiles.keys()
|
||||
|
|
@ -87,23 +87,23 @@ class SqliteStorage():
|
|||
"""return True if profile_name exists
|
||||
@param profile_name: name of the profile to check"""
|
||||
return self.profiles.has_key(profile_name)
|
||||
|
||||
|
||||
def createProfile(self, name):
|
||||
"""Create a new profile
|
||||
@param name: name of the profile
|
||||
@return: deferred triggered once profile is actually created"""
|
||||
def getProfileId(ignore):
|
||||
return self.dbpool.runQuery("SELECT (id) FROM profiles WHERE name = ?", (name,))
|
||||
|
||||
|
||||
def profile_created(profile_id):
|
||||
_id = profile_id[0][0]
|
||||
self.profiles[name] = _id #we synchronise the cache
|
||||
|
||||
|
||||
d = self.dbpool.runQuery("INSERT INTO profiles(name) VALUES (?)", (name,))
|
||||
d.addCallback(getProfileId)
|
||||
d.addCallback(profile_created)
|
||||
return d
|
||||
|
||||
|
||||
def deleteProfile(self, name):
|
||||
"""Delete profile
|
||||
@param name: name of the profile
|
||||
|
|
@ -126,7 +126,7 @@ class SqliteStorage():
|
|||
for param in result:
|
||||
category,name,value = param
|
||||
params_gen[(category, name)] = value
|
||||
debug(_("loading general parameters from database"))
|
||||
debug(_("loading general parameters from database"))
|
||||
return self.dbpool.runQuery("SELECT category,name,value FROM param_gen").addCallback(fillParams)
|
||||
|
||||
def loadIndParams(self, params_ind, profile):
|
||||
|
|
@ -138,7 +138,7 @@ class SqliteStorage():
|
|||
for param in result:
|
||||
category,name,value = param
|
||||
params_ind[(category, name)] = value
|
||||
debug(_("loading individual parameters from database"))
|
||||
debug(_("loading individual parameters from database"))
|
||||
d = self.dbpool.runQuery("SELECT category,name,value FROM param_ind WHERE profile_id=?", (self.profiles[profile],))
|
||||
d.addCallback(fillParams)
|
||||
return d
|
||||
|
|
@ -218,7 +218,7 @@ class SqliteStorage():
|
|||
values.append(_jid.resource)
|
||||
return '(%s=? AND %s_res=?)' % (_type, _type)
|
||||
return '%s=?' % (_type,)
|
||||
|
||||
|
||||
if between:
|
||||
query_parts.append("(%s OR %s) AND (%s or %s)" % (test_jid('source', from_jid),
|
||||
test_jid('source', to_jid),
|
||||
|
|
@ -233,7 +233,7 @@ class SqliteStorage():
|
|||
if limit:
|
||||
query_parts.append("LIMIT ?")
|
||||
values.append(limit)
|
||||
|
||||
|
||||
d = self.dbpool.runQuery(" ".join(query_parts), values)
|
||||
return d.addCallback(sqliteToDict)
|
||||
|
||||
|
|
@ -247,7 +247,7 @@ class SqliteStorage():
|
|||
for private in result:
|
||||
key,value = private
|
||||
private_gen[key] = value
|
||||
debug(_("loading general private values [namespace: %s] from database") % (namespace,))
|
||||
debug(_("loading general private values [namespace: %s] from database") % (namespace,))
|
||||
d = self.dbpool.runQuery("SELECT key,value FROM private_gen WHERE namespace=?", (namespace,)).addCallback(fillPrivates)
|
||||
return d.addErrback(lambda x: debug(_("No data present in database for namespace %s") % namespace))
|
||||
|
||||
|
|
@ -273,7 +273,7 @@ class SqliteStorage():
|
|||
@param value: value to set
|
||||
@return: deferred"""
|
||||
d = self.dbpool.runQuery("REPLACE INTO private_gen(namespace,key,value) VALUES (?,?,?)", (namespace,key,value))
|
||||
d.addErrback(lambda ignore: error(_("Can't set general private value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
d.addErrback(lambda ignore: error(_("Can't set general private value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
{"namespace":namespace, "key":key})))
|
||||
return d
|
||||
|
||||
|
|
@ -295,7 +295,7 @@ class SqliteStorage():
|
|||
@param key: key of the private value
|
||||
@return: deferred"""
|
||||
d = self.dbpool.runQuery("DELETE FROM private_gen WHERE namespace=? AND key=?", (namespace,key))
|
||||
d.addErrback(lambda ignore: error(_("Can't delete general private value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
d.addErrback(lambda ignore: error(_("Can't delete general private value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
{"namespace":namespace, "key":key})))
|
||||
return d
|
||||
|
||||
|
|
@ -320,7 +320,7 @@ class SqliteStorage():
|
|||
for private in result:
|
||||
key,value = private
|
||||
private_gen[key] = pickle.loads(str(value))
|
||||
debug(_("loading general private binary values [namespace: %s] from database") % (namespace,))
|
||||
debug(_("loading general private binary values [namespace: %s] from database") % (namespace,))
|
||||
d = self.dbpool.runQuery("SELECT key,value FROM private_gen_bin WHERE namespace=?", (namespace,)).addCallback(fillPrivates)
|
||||
return d.addErrback(lambda x: debug(_("No binary data present in database for namespace %s") % namespace))
|
||||
|
||||
|
|
@ -346,7 +346,7 @@ class SqliteStorage():
|
|||
@param value: value to set
|
||||
@return: deferred"""
|
||||
d = self.dbpool.runQuery("REPLACE INTO private_gen_bin(namespace,key,value) VALUES (?,?,?)", (namespace,key,pickle.dumps(value,0)))
|
||||
d.addErrback(lambda ignore: error(_("Can't set general private binary value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
d.addErrback(lambda ignore: error(_("Can't set general private binary value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
{"namespace":namespace, "key":key})))
|
||||
return d
|
||||
|
||||
|
|
@ -368,7 +368,7 @@ class SqliteStorage():
|
|||
@param key: key of the private value
|
||||
@return: deferred"""
|
||||
d = self.dbpool.runQuery("DELETE FROM private_gen_bin WHERE namespace=? AND key=?", (namespace,key))
|
||||
d.addErrback(lambda ignore: error(_("Can't delete general private binary value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
d.addErrback(lambda ignore: error(_("Can't delete general private binary value (%(key)s) [namespace:%(namespace)s] in database" %
|
||||
{"namespace":namespace, "key":key})))
|
||||
return d
|
||||
|
||||
|
|
|
|||
|
|
@ -83,7 +83,7 @@ class CS_Plugin():
|
|||
def dataLoaded(ignore):
|
||||
if not self.data[profile]:
|
||||
self.data[profile] = {'cookies':{}}
|
||||
|
||||
|
||||
self.data[profile].load().addCallback(dataLoaded)
|
||||
|
||||
def profileDisconnected(self, profile):
|
||||
|
|
@ -104,10 +104,10 @@ class CS_Plugin():
|
|||
self.host.bridge.actionResult("ERROR", id, message_data)
|
||||
return
|
||||
|
||||
post_data = urllib.urlencode({'auth_login[un]':login,'auth_login[pw]':password,'auth_login[action]':'Login...'})
|
||||
|
||||
post_data = urllib.urlencode({'auth_login[un]':login,'auth_login[pw]':password,'auth_login[action]':'Login...'})
|
||||
|
||||
self.data[profile]['cookies'] = {}
|
||||
|
||||
|
||||
d = getPage('http://www.couchsurfing.org/login.html', method='POST', postdata=post_data, headers={'Content-Type':'application/x-www-form-urlencoded'} , agent=AGENT, cookies=self.data[profile]['cookies'])
|
||||
d.addCallback(self.__connectionCB, id, profile)
|
||||
d.addErrback(self.erroCB, id)
|
||||
|
|
@ -193,7 +193,7 @@ class CS_Plugin():
|
|||
friend_id = regex_href.search(unicode(a_tag)).groups()[0]
|
||||
|
||||
debug(_("CS friend found: %(friend_name)s (id: %(friend_id)s, link: %(friend_link)s)") % {'friend_name':friend_name, 'friend_id':friend_id, 'friend_link':friend_link})
|
||||
friends[friend_name] = {'link':friend_link,'id':friend_id}
|
||||
friends[friend_name] = {'link':friend_link,'id':friend_id}
|
||||
a = soup.find('td','barmiddle next').a #is there several pages ?
|
||||
if a:
|
||||
#yes, we parse the next page
|
||||
|
|
@ -255,7 +255,7 @@ class CS_Plugin():
|
|||
message = data['message']
|
||||
info(_("sending message to %(friends)s with subject [%(subject)s]" % {'friends':friends, 'subject':subject}))
|
||||
self.__sendMessage(None, subject, message, self.data[profile], friends, id, profile)
|
||||
|
||||
|
||||
def __showUnreadMessages2(self, html, id, profile):
|
||||
"""Called when the inbox page has been received"""
|
||||
#FIXME: that's really too fragile, only works if the unread messages are in the first page, and it would be too resources consuming for the website to DL each time all pages. In addition, the show attribute doesn't work as expected.
|
||||
|
|
@ -269,4 +269,4 @@ class CS_Plugin():
|
|||
d = getPage("http://www.couchsurfing.org/messages.html?message_status=inbox&show=10000", agent=AGENT, cookies=self.data[profile]['cookies'])
|
||||
d.addCallback(self.__showUnreadMessages2, id, profile)
|
||||
d.addErrback(self.erroCB, id)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ from twisted.words.protocols.jabber import jid
|
|||
|
||||
|
||||
from sat.core.exceptions import UnknownEntityError
|
||||
from sat.tools.misc import SkipOtherTriggers
|
||||
from sat.tools.misc import SkipOtherTriggers
|
||||
|
||||
PLUGIN_INFO = {
|
||||
"name": "Parrot Plugin",
|
||||
|
|
@ -57,28 +57,28 @@ class Exp_Parrot():
|
|||
# _links = client.parrot_links
|
||||
# except AttributeError:
|
||||
# return True
|
||||
#
|
||||
#
|
||||
# if mess_data['to'].userhostJID() in _links.values():
|
||||
# debug("Parrot link detected, skipping other triggers")
|
||||
# raise SkipOtherTriggers
|
||||
# raise SkipOtherTriggers
|
||||
|
||||
def MessageReceivedTrigger(self, message, profile):
|
||||
""" Check if source is linked and repeat message, else do nothing """
|
||||
client = self.host.getClient(profile)
|
||||
from_jid = jid.JID(message["from"])
|
||||
|
||||
|
||||
try:
|
||||
_links = client.parrot_links
|
||||
except AttributeError:
|
||||
return True
|
||||
|
||||
|
||||
if not from_jid.userhostJID() in _links:
|
||||
return True
|
||||
|
||||
|
||||
for e in message.elements():
|
||||
if e.name == "body":
|
||||
mess_body = e.children[0] if e.children else ""
|
||||
|
||||
|
||||
try:
|
||||
entity_type = self.host.memory.getEntityData(from_jid, ['type'], profile)["type"]
|
||||
except (UnknownEntityError, KeyError):
|
||||
|
|
@ -97,7 +97,7 @@ class Exp_Parrot():
|
|||
self.host.sendMessage(unicode(linked), msg, None, "auto", profile_key=profile)
|
||||
else:
|
||||
warning("No body element found in message, following normal behaviour")
|
||||
|
||||
|
||||
return True
|
||||
|
||||
def addParrot(self, source_jid, dest_jid, profile):
|
||||
|
|
|
|||
|
|
@ -57,9 +57,9 @@ class Exp_Pipe():
|
|||
|
||||
def profileConnected(self, profile):
|
||||
client = self.host.getClient(profile)
|
||||
client._pipe_waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout,
|
||||
client._pipe_waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout,
|
||||
# current stream method, [failed stream methods], profile]
|
||||
|
||||
|
||||
def _kill_id(self, approval_id, profile):
|
||||
"""Delete a waiting_for_approval id, called after timeout
|
||||
@param approval_id: id of _pipe_waiting_for_approval"""
|
||||
|
|
@ -69,7 +69,7 @@ class Exp_Pipe():
|
|||
del client._pipe_waiting_for_approval[approval_id]
|
||||
except KeyError:
|
||||
warning(_("kill id called on a non existant approval id"))
|
||||
|
||||
|
||||
def transferRequest(self, iq_id, from_jid, si_id, si_mime_type, si_el, profile):
|
||||
"""Called when a pipe transfer is requested
|
||||
@param iq_id: id of the iq request
|
||||
|
|
@ -85,12 +85,12 @@ class Exp_Pipe():
|
|||
raise ProfileNotInCacheError
|
||||
pipe_elts = filter(lambda elt: elt.name == 'pipe', si_el.elements())
|
||||
feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_el)
|
||||
|
||||
|
||||
if not pipe_elts:
|
||||
warning(_("No pipe element found"))
|
||||
self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
|
||||
return
|
||||
|
||||
|
||||
if feature_elts:
|
||||
feature_el = feature_elts[0]
|
||||
form = data_form.Form.fromElement(feature_el.firstChildElement())
|
||||
|
|
@ -202,7 +202,7 @@ class Exp_Pipe():
|
|||
if not feature_elts:
|
||||
warning(_("No feature element"))
|
||||
return
|
||||
|
||||
|
||||
choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elts[0])
|
||||
try:
|
||||
stream_method = choosed_options["stream-method"]
|
||||
|
|
@ -236,9 +236,9 @@ class Exp_Pipe():
|
|||
warning(_("Trying to send a file from an unknown profile"))
|
||||
return ""
|
||||
feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m})
|
||||
|
||||
|
||||
pipe_transfer_elts = []
|
||||
|
||||
|
||||
pipe_elt = domish.Element((PROFILE, 'pipe'))
|
||||
pipe_transfer_elts.append(pipe_elt)
|
||||
|
||||
|
|
|
|||
|
|
@ -52,12 +52,12 @@ RESERVED = ['libervia']
|
|||
|
||||
class ProsodyRegisterProtocol(protocol.ProcessProtocol):
|
||||
""" Try to register an account with prosody """
|
||||
|
||||
|
||||
def __init__(self, password, deferred = None):
|
||||
self.password = password
|
||||
self.deferred = deferred
|
||||
self.data = ''
|
||||
|
||||
|
||||
def connectionMade(self):
|
||||
self.transport.write("%s\n%s" % ((self.password.encode('utf-8'),)*2))
|
||||
self.transport.closeStdin()
|
||||
|
|
@ -65,10 +65,10 @@ class ProsodyRegisterProtocol(protocol.ProcessProtocol):
|
|||
|
||||
def outReceived(self, data):
|
||||
self.data += data
|
||||
|
||||
|
||||
def errReceived(self, data):
|
||||
self.data += data
|
||||
|
||||
|
||||
def processEnded(self, reason):
|
||||
if (reason.value.exitCode == 0):
|
||||
info(_('Prosody registration success'))
|
||||
|
|
@ -97,7 +97,7 @@ class MiscAccount():
|
|||
info(_('Prosody path found: %s') % (self._prosody_path,))
|
||||
|
||||
def _registerAccount(self, email, password, profile):
|
||||
|
||||
|
||||
"""
|
||||
#Password Generation
|
||||
#_charset = [chr(i) for i in range(0x21,0x7F)] #XXX: this charset seems to have some issues with openfire
|
||||
|
|
@ -117,13 +117,13 @@ class MiscAccount():
|
|||
return d
|
||||
|
||||
def _profileRegistered(self, result, email, password, profile):
|
||||
|
||||
|
||||
#FIXME: values must be in a config file instead of hardcoded
|
||||
self.host.memory.setParam("JabberID", "%s@%s/%s" % (profile, _NEW_ACCOUNT_DOMAIN, _NEW_ACCOUNT_RESOURCE), "Connection", profile)
|
||||
self.host.memory.setParam("JabberID", "%s@%s/%s" % (profile, _NEW_ACCOUNT_DOMAIN, _NEW_ACCOUNT_RESOURCE), "Connection", profile)
|
||||
self.host.memory.setParam("Server", _NEW_ACCOUNT_SERVER, "Connection", profile)
|
||||
self.host.memory.setParam("Password", password, "Connection", profile)
|
||||
#and the account
|
||||
|
||||
|
||||
#XXX: we use "prosodyctl adduser" because "register" doesn't check conflict
|
||||
# and just change the password if the account already exists
|
||||
d = defer.Deferred()
|
||||
|
|
@ -146,7 +146,7 @@ class MiscAccount():
|
|||
def email_ko(ignore):
|
||||
#TODO: return error code to user
|
||||
error ("Failed to send email to %s" % email)
|
||||
|
||||
|
||||
body = (u"""Welcome to Libervia, a Salut à Toi project part
|
||||
|
||||
/!\\ WARNING, THIS IS ONLY A TECHNICAL DEMO, DON'T USE THIS ACCOUNT FOR ANY SERIOUS PURPOSE /!\\
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ class GroupBlog():
|
|||
|
||||
host.bridge.addMethod("sendGroupBlog", ".plugin", in_sign='sasss', out_sign='',
|
||||
method=self.sendGroupBlog)
|
||||
|
||||
|
||||
host.bridge.addMethod("getLastGroupBlogs", ".plugin",
|
||||
in_sign='sis', out_sign='aa{ss}',
|
||||
method=self.getLastGroupBlogs,
|
||||
|
|
@ -92,21 +92,21 @@ class GroupBlog():
|
|||
in_sign='sasis', out_sign='a{saa{ss}}',
|
||||
method=self.getMassiveLastGroupBlogs,
|
||||
async = True)
|
||||
|
||||
|
||||
host.bridge.addMethod("subscribeGroupBlog", ".plugin", in_sign='ss', out_sign='',
|
||||
method=self.subscribeGroupBlog,
|
||||
async = True)
|
||||
|
||||
|
||||
host.bridge.addMethod("massiveSubscribeGroupBlogs", ".plugin", in_sign='sass', out_sign='',
|
||||
method=self.massiveSubscribeGroupBlogs,
|
||||
async = True)
|
||||
|
||||
|
||||
host.trigger.add("PubSubItemsReceived", self.pubSubItemsReceivedTrigger)
|
||||
|
||||
|
||||
|
||||
|
||||
def getHandler(self, profile):
|
||||
return GroupBlog_handler()
|
||||
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def initialise(self, profile_key):
|
||||
"""Check that this data for this profile are initialised, and do it else
|
||||
|
|
@ -115,14 +115,14 @@ class GroupBlog():
|
|||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
error(_("Unknown profile"))
|
||||
raise Exception("Unknown profile")
|
||||
|
||||
raise Exception("Unknown profile")
|
||||
|
||||
client = self.host.getClient(profile)
|
||||
if not client:
|
||||
error(_('No client for this profile key: %s') % profile_key)
|
||||
raise Exception("Unknown profile")
|
||||
raise Exception("Unknown profile")
|
||||
yield client.client_initialized #we want to be sure that the client is initialized
|
||||
|
||||
|
||||
#we first check that we have a item-access pubsub server
|
||||
if not hasattr(client,"item_access_pubsub"):
|
||||
debug(_('Looking for item-access power pubsub server'))
|
||||
|
|
@ -136,7 +136,7 @@ class GroupBlog():
|
|||
info(_("item-access powered pubsub service found: [%s]") % entity.full())
|
||||
client.item_access_pubsub = entity
|
||||
client._item_access_pubsub_pending.callback(None)
|
||||
|
||||
|
||||
if hasattr(client,"_item_access_pubsub_pending"):
|
||||
#XXX: we need to wait for item access pubsub service check
|
||||
yield client._item_access_pubsub_pending
|
||||
|
|
@ -174,7 +174,7 @@ class GroupBlog():
|
|||
form_elts = filter(lambda elt: elt.name == "x", item.children)
|
||||
for form_elt in form_elts:
|
||||
form = data_form.Form.fromElement(form_elt)
|
||||
|
||||
|
||||
if (form.formNamespace == NS_PUBSUB_ITEM_CONFIG):
|
||||
access_model = form.get(OPT_ACCESS_MODEL, 'open')
|
||||
if access_model == "roster":
|
||||
|
|
@ -183,7 +183,7 @@ class GroupBlog():
|
|||
except KeyError:
|
||||
warning("No group found for roster access-model")
|
||||
microblog_data["groups"] = ''
|
||||
|
||||
|
||||
break
|
||||
|
||||
def item2gbdata(self, item):
|
||||
|
|
@ -258,12 +258,12 @@ class GroupBlog():
|
|||
raise NotImplementedError
|
||||
else:
|
||||
error(_("Unknown access type"))
|
||||
raise BadAccessTypeError
|
||||
|
||||
raise BadAccessTypeError
|
||||
|
||||
self.initialise(profile_key).addCallback(initialised)
|
||||
|
||||
|
||||
|
||||
|
||||
def getLastGroupBlogs(self, pub_jid, max_items=10, profile_key='@DEFAULT@'):
|
||||
"""Get the last published microblogs
|
||||
@param pub_jid: jid of the publisher
|
||||
|
|
@ -271,7 +271,7 @@ class GroupBlog():
|
|||
@param profile_key: profile key
|
||||
@return: list of microblog data (dict)
|
||||
"""
|
||||
|
||||
|
||||
def initialised(result):
|
||||
profile, client = result
|
||||
d = self.host.plugins["XEP-0060"].getItems(client.item_access_pubsub, self.getNodeName(jid.JID(pub_jid)),
|
||||
|
|
@ -292,14 +292,14 @@ class GroupBlog():
|
|||
"""
|
||||
def sendResult(result):
|
||||
"""send result of DeferredList (list of microblogs to the calling method"""
|
||||
|
||||
|
||||
ret = {}
|
||||
|
||||
for (success, value) in result:
|
||||
if success:
|
||||
source_jid, data = value
|
||||
ret[source_jid] = data
|
||||
|
||||
|
||||
return ret
|
||||
|
||||
def initialised(result):
|
||||
|
|
@ -316,9 +316,9 @@ class GroupBlog():
|
|||
jids = publishers
|
||||
else:
|
||||
raise UnknownType
|
||||
|
||||
|
||||
mblogs = []
|
||||
|
||||
|
||||
for _jid in jids:
|
||||
d = self.host.plugins["XEP-0060"].getItems(client.item_access_pubsub, self.getNodeName(jid.JID(_jid)),
|
||||
max_items=max_items, profile_key=profile_key)
|
||||
|
|
@ -326,7 +326,7 @@ class GroupBlog():
|
|||
mblogs.append(d)
|
||||
dlist = defer.DeferredList(mblogs)
|
||||
dlist.addCallback(sendResult)
|
||||
|
||||
|
||||
return dlist
|
||||
|
||||
|
||||
|
|
@ -391,7 +391,7 @@ class GroupBlog():
|
|||
|
||||
class GroupBlog_handler(XMPPHandler):
|
||||
implements(iwokkel.IDisco)
|
||||
|
||||
|
||||
def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
|
||||
return [disco.DiscoFeature(NS_GROUPBLOG)]
|
||||
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ PLUGIN_INFO = {
|
|||
|
||||
class IMAP_server():
|
||||
#TODO: connect profile on mailbox request, once password is accepted
|
||||
|
||||
|
||||
params = """
|
||||
<params>
|
||||
<general>
|
||||
|
|
@ -65,13 +65,13 @@ class IMAP_server():
|
|||
def __init__(self, host):
|
||||
info(_("Plugin Imap Server initialization"))
|
||||
self.host = host
|
||||
|
||||
|
||||
#parameters
|
||||
host.memory.importParams(self.params)
|
||||
|
||||
port = int(self.host.memory.getParamA("IMAP Port", "Mail Server"))
|
||||
info(_("Launching IMAP server on port %d"), port)
|
||||
|
||||
|
||||
self.server_factory = ImapServerFactory(self.host)
|
||||
reactor.listenTCP(port, self.server_factory)
|
||||
|
||||
|
|
@ -84,7 +84,7 @@ class Message():
|
|||
self.flags=flags
|
||||
self.mess_fp=mess_fp
|
||||
self.message=Parser().parse(mess_fp)
|
||||
|
||||
|
||||
def getUID(self):
|
||||
"""Retrieve the unique identifier associated with this message.
|
||||
"""
|
||||
|
|
@ -221,7 +221,7 @@ class SatMailbox:
|
|||
"""Called before this mailbox is deleted, permanently.
|
||||
"""
|
||||
debug('destroy')
|
||||
|
||||
|
||||
|
||||
def requestStatus(self, names):
|
||||
"""Return status information about this mailbox.
|
||||
|
|
@ -340,7 +340,7 @@ class SatMailbox:
|
|||
setF(mess_id, new_flags)
|
||||
ret[mess_id] = tuple(new_flags)
|
||||
return ret
|
||||
|
||||
|
||||
if uid:
|
||||
messages.last = self.mailbox.getMaxUid()
|
||||
messages.getnext = self.mailbox.getNextExistingUid
|
||||
|
|
@ -348,7 +348,7 @@ class SatMailbox:
|
|||
for listener in self.listeners:
|
||||
listener.flagsChanged(ret)
|
||||
return ret
|
||||
|
||||
|
||||
else:
|
||||
messages.last = self.getMessageCount()
|
||||
ret = updateFlags(self.mailbox.getFlags,self.mailbox.setFlags)
|
||||
|
|
@ -412,7 +412,7 @@ class SatProfileCredentialChecker:
|
|||
credentialInterfaces = (credentials.IUsernamePassword,
|
||||
credentials.IUsernameHashedPassword)
|
||||
|
||||
|
||||
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ class MaildirError(Exception):
|
|||
pass
|
||||
|
||||
class MaildirBox():
|
||||
|
||||
|
||||
def __init__(self, host):
|
||||
info(_("Plugin Maildir initialization"))
|
||||
self.host = host
|
||||
|
|
@ -184,14 +184,14 @@ class MaildirBox():
|
|||
if idx>box_data['cur_idx']:
|
||||
return None
|
||||
return idx
|
||||
|
||||
|
||||
def getMaxUid(self, boxname, profile):
|
||||
"""Give the max existing uid
|
||||
@param boxname: name of the box where the message is
|
||||
@return: uid"""
|
||||
box_data = self.__getBoxData(boxname, profile)
|
||||
return box_data['cur_idx']
|
||||
|
||||
|
||||
def getIdFromUid(self, boxname, message_uid, profile):
|
||||
"""Return the message unique id from it's integer UID
|
||||
@param boxname: name of the box where the message is
|
||||
|
|
@ -251,9 +251,9 @@ class MaildirBox():
|
|||
"""
|
||||
box_data = self.__getBoxData(boxname, profile)
|
||||
for mess_id in self.getMessageIdsWithFlag(boxname,"\\Deleted", profile):
|
||||
del(box_data[mess_id])
|
||||
del(box_data[mess_id])
|
||||
self.data[profile].force(boxname)
|
||||
|
||||
|
||||
def cleanTable(self, boxname, existant_id, profile):
|
||||
"""Remove mails which no longuer exist from the table
|
||||
@param boxname: name of the box to clean
|
||||
|
|
@ -265,7 +265,7 @@ class MaildirBox():
|
|||
to_remove.append(key)
|
||||
for key in to_remove:
|
||||
del box_data[key]
|
||||
|
||||
|
||||
def addObserver(self, callback, profile, boxname, signal="NEW_MESSAGE"):
|
||||
"""Add an observer for maildir box changes
|
||||
@param callback: method to call when the the box is updated
|
||||
|
|
@ -327,7 +327,7 @@ class MailboxUser:
|
|||
elif e.name == "subject":
|
||||
mail['Subject'] = e.children[0].encode('utf-8')
|
||||
return mail.as_string()
|
||||
|
||||
|
||||
def __init__(self, _maildir, name, observer=None, profile="@NONE@"):
|
||||
"""@param _maildir: the main MaildirBox instance
|
||||
@param name: name of the mailbox
|
||||
|
|
@ -350,7 +350,7 @@ class MailboxUser:
|
|||
self.mailbox = maildir.MaildirMailbox(mailbox_path)
|
||||
self.observer=observer
|
||||
self.__uid_table_update()
|
||||
|
||||
|
||||
if observer:
|
||||
debug("adding observer for %s (%s)" % (name,profile))
|
||||
self.maildir.addObserver(observer, profile, name, "NEW_MESSAGE")
|
||||
|
|
@ -362,7 +362,7 @@ class MailboxUser:
|
|||
existant_id.append(self.getId(mess_idx))
|
||||
self.getUid(mess_idx)
|
||||
self.maildir.cleanTable(self.name, existant_id, profile=self.profile)
|
||||
|
||||
|
||||
|
||||
def __del__(self):
|
||||
if observer:
|
||||
|
|
@ -417,7 +417,7 @@ class MailboxUser:
|
|||
if self.getUid(mess_idx) == mess_uid:
|
||||
return mess_idx
|
||||
raise IndexError
|
||||
|
||||
|
||||
def getIdxFromId(self, mess_id):
|
||||
"""Return the message index from the unique index
|
||||
@param mess_id: message unique index as given by MaildirMailbox
|
||||
|
|
@ -426,7 +426,7 @@ class MailboxUser:
|
|||
if self.mailbox.getUidl(mess_idx) == mess_id:
|
||||
return mess_idx
|
||||
raise IndexError
|
||||
|
||||
|
||||
def getMessage(self, mess_idx):
|
||||
"""Return the full message
|
||||
@param mess_idx: message index"""
|
||||
|
|
@ -443,7 +443,7 @@ class MailboxUser:
|
|||
@return: list of strings"""
|
||||
id = self.getId(mess_idx)
|
||||
return self.maildir.getFlags(self.name, id, profile=self.profile)
|
||||
|
||||
|
||||
def getFlagsUid(self, mess_uid):
|
||||
"""Return the flags of the message
|
||||
@param mess_uid: message unique identifier
|
||||
|
|
@ -487,4 +487,4 @@ class MailboxUser:
|
|||
"""Delete everything in the .Trash dir"""
|
||||
import shutils
|
||||
pdb.set_trace()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
SAT plugin for managing Quiz game
|
||||
SAT plugin for managing Quiz game
|
||||
Copyright (C) 2009, 2010, 2011, 2012, 2013 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
|
|
@ -133,7 +133,7 @@ class Quiz():
|
|||
for data in game_data:
|
||||
data_elt = domish.Element((None,data))
|
||||
data_elt.addContent(game_data[data])
|
||||
game_data_elt.addChild(data_elt)
|
||||
game_data_elt.addChild(data_elt)
|
||||
return game_data_elt
|
||||
|
||||
def __xml_to_game_data(self, game_data_elt):
|
||||
|
|
@ -161,17 +161,17 @@ class Quiz():
|
|||
score = {}
|
||||
for player in game_data['players']:
|
||||
score[player] = players_data[player]['score']
|
||||
|
||||
|
||||
answer_result_elt = domish.Element((None,'answer_result'))
|
||||
answer_result_elt['player'] = player_answering
|
||||
answer_result_elt['good_answer'] = str(good_answer)
|
||||
|
||||
|
||||
for player in score:
|
||||
score_elt = domish.Element((None,"score"))
|
||||
score_elt['player'] = player
|
||||
score_elt['score'] = str(score[player])
|
||||
answer_result_elt.addChild(score_elt)
|
||||
|
||||
answer_result_elt.addChild(score_elt)
|
||||
|
||||
return answer_result_elt
|
||||
|
||||
def __create_started_elt(self, players):
|
||||
|
|
@ -193,7 +193,7 @@ class Quiz():
|
|||
question_elt['timer'] = str(timer)
|
||||
question_elt.addContent(question)
|
||||
return question_elt
|
||||
|
||||
|
||||
def __start_play(self, room_jid, game_data, profile):
|
||||
"""Start the game (tell to the first player after dealer to play"""
|
||||
game_data['stage'] = "play"
|
||||
|
|
@ -231,14 +231,14 @@ class Quiz():
|
|||
for player in players:
|
||||
self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Quiz"}, profile)
|
||||
self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data
|
||||
|
||||
|
||||
def after_init(ignore):
|
||||
room_name = "sat_quiz_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
|
||||
print "\n\n===> room_name:", room_name
|
||||
muc_service = None
|
||||
for service in self.host.memory.getServerServiceEntities("conference", "text", profile):
|
||||
if not ".irc." in service.userhost():
|
||||
#FIXME:
|
||||
#FIXME:
|
||||
#This awfull ugly hack is here to avoid an issue with openfire: the irc gateway
|
||||
#use "conference/text" identity (instead of "conference/irc"), there is certainly a better way
|
||||
#to manage this, but this hack fill do it for test purpose
|
||||
|
|
@ -247,7 +247,7 @@ class Quiz():
|
|||
if not muc_service:
|
||||
error(_("Can't find a MUC service"))
|
||||
return
|
||||
|
||||
|
||||
_jid, xmlstream = self.host.getJidNStream(profile)
|
||||
d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile).addCallback(quizRoomJoined)
|
||||
|
||||
|
|
@ -355,18 +355,18 @@ class Quiz():
|
|||
game_data["timer"] = reactor.callLater(timer, self.timerExpired, room_jid, profile)
|
||||
game_data["time_left"] = None
|
||||
|
||||
def checkAnswer(self, room_jid, player, answer, profile):
|
||||
def checkAnswer(self, room_jid, player, answer, profile):
|
||||
"""Check if the answer given is right"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
players_data = game_data['players_data']
|
||||
good_answer = game_data['question_id'] == "1" and answer=="42"
|
||||
players_data[player]['score'] += 1 if good_answer else -1
|
||||
players_data[player]['score'] = min(9, max(0, players_data[player]['score']))
|
||||
|
||||
|
||||
mess = self.createGameElt(room_jid)
|
||||
mess.firstChildElement().addChild(self.__answer_result(player, good_answer, game_data))
|
||||
self.host.profiles[profile].xmlstream.send(mess)
|
||||
|
||||
|
||||
if good_answer:
|
||||
reactor.callLater(4, self.askQuestion, room_jid, profile)
|
||||
else:
|
||||
|
|
@ -382,7 +382,7 @@ class Quiz():
|
|||
|
||||
for player in players:
|
||||
players_data[player]['game_score'] = 0
|
||||
|
||||
|
||||
new_game_data = {"instructions": _(u"""Bienvenue dans cette partie rapide de quizz, le premier à atteindre le score de 9 remporte le jeu
|
||||
|
||||
Attention, tu es prêt ?""")}
|
||||
|
|
@ -393,20 +393,20 @@ Attention, tu es prêt ?""")}
|
|||
reactor.callLater(10, self.askQuestion, room_jid, profile)
|
||||
|
||||
def quiz_game_cmd(self, mess_elt, profile):
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
game_elt = mess_elt.firstChildElement()
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
players_data = game_data['players_data']
|
||||
|
||||
|
||||
for elt in game_elt.elements():
|
||||
|
||||
|
||||
if elt.name == 'started': #new game created
|
||||
players = []
|
||||
for player in elt.elements():
|
||||
players.append(unicode(player))
|
||||
self.host.bridge.quizGameStarted(room_jid.userhost(), from_jid.full(), players, profile)
|
||||
|
||||
|
||||
elif elt.name == 'player_ready': #ready to play
|
||||
player = elt['player']
|
||||
status = self.games[room_jid.userhost()]['status']
|
||||
|
|
@ -418,10 +418,10 @@ Attention, tu es prêt ?""")}
|
|||
|
||||
elif elt.name == 'game_data':
|
||||
self.host.bridge.quizGameNew(room_jid.userhost(), self.__xml_to_game_data(elt), profile)
|
||||
|
||||
|
||||
elif elt.name == 'question': #A question is asked
|
||||
self.host.bridge.quizGameQuestion(room_jid.userhost(), elt["id"], unicode(elt), int(elt["timer"]), profile )
|
||||
|
||||
|
||||
elif elt.name == 'player_answer':
|
||||
player = elt['player']
|
||||
pause = game_data['stage'] == 'question' #we pause the game only if we are have a question at the moment
|
||||
|
|
@ -429,7 +429,7 @@ Attention, tu es prêt ?""")}
|
|||
mess = self.createGameElt(room_jid)
|
||||
buzzer_elt = mess.firstChildElement().addElement('player_buzzed')
|
||||
buzzer_elt['player'] = player
|
||||
buzzer_elt['pause'] = str(pause)
|
||||
buzzer_elt['pause'] = str(pause)
|
||||
self.host.profiles[profile].xmlstream.send(mess)
|
||||
if pause:
|
||||
self.pauseTimer(room_jid)
|
||||
|
|
@ -442,17 +442,17 @@ Attention, tu es prêt ?""")}
|
|||
say_elt['delay'] = "3"
|
||||
reactor.callLater(2, self.host.profiles[profile].xmlstream.send, mess)
|
||||
reactor.callLater(6, self.checkAnswer, room_jid, player, _answer, profile=profile)
|
||||
|
||||
|
||||
elif elt.name == 'player_buzzed':
|
||||
self.host.bridge.quizGamePlayerBuzzed(room_jid.userhost(), elt["player"], elt['pause'] == str(True), profile)
|
||||
|
||||
|
||||
elif elt.name == 'player_says':
|
||||
self.host.bridge.quizGamePlayerSays(room_jid.userhost(), elt["player"], unicode(elt), int(elt["delay"]), profile)
|
||||
|
||||
|
||||
elif elt.name == 'answer_result':
|
||||
player, good_answer, score = self.__answer_result_to_signal_args(elt)
|
||||
self.host.bridge.quizGameAnswerResult(room_jid.userhost(), player, good_answer, score, profile)
|
||||
|
||||
|
||||
elif elt.name == 'timer_expired':
|
||||
self.host.bridge.quizGameTimerExpired(room_jid.userhost(), profile)
|
||||
|
||||
|
|
@ -461,13 +461,13 @@ Attention, tu es prêt ?""")}
|
|||
|
||||
else:
|
||||
error (_('Unmanaged game element: %s') % elt.name)
|
||||
|
||||
|
||||
def getHandler(self, profile):
|
||||
return QuizGameHandler(self)
|
||||
|
||||
class QuizGameHandler (XMPPHandler):
|
||||
implements(iwokkel.IDisco)
|
||||
|
||||
|
||||
def __init__(self, plugin_parent):
|
||||
self.plugin_parent = plugin_parent
|
||||
self.host = plugin_parent.host
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
SAT plugin for managing Radiocol
|
||||
SAT plugin for managing Radiocol
|
||||
Copyright (C) 2009, 2010, 2011, 2012, 2013 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
|
|
@ -80,7 +80,7 @@ class Radiocol():
|
|||
elt["type"] = type
|
||||
elt.addElement((NC_RADIOCOL, RADIOC_TAG))
|
||||
return elt
|
||||
|
||||
|
||||
def __create_started_elt(self):
|
||||
"""Create a game_started domish element"""
|
||||
started_elt = domish.Element((None,'started'))
|
||||
|
|
@ -122,14 +122,14 @@ class Radiocol():
|
|||
self.radiocolCreate(_room_jid.userhost(), profile_key=profile)
|
||||
for occupant in occupants:
|
||||
self.host.plugins["XEP-0249"].invite(jid.JID(occupant), room.occupantJID.userhostJID(), {"game":"Radiocol"}, profile)
|
||||
|
||||
|
||||
def after_init(ignore):
|
||||
room_name = "sat_radiocol_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
|
||||
print "\n\n===> room_name:", room_name
|
||||
muc_service = None
|
||||
for service in self.host.memory.getServerServiceEntities("conference", "text", profile):
|
||||
if not ".irc." in service.userhost():
|
||||
#FIXME:
|
||||
#FIXME:
|
||||
#This awfull ugly hack is here to avoid an issue with openfire: the irc gateway
|
||||
#use "conference/text" identity (instead of "conference/irc"), there is certainly a better way
|
||||
#to manage this, but this hack fill do it for test purpose
|
||||
|
|
@ -138,7 +138,7 @@ class Radiocol():
|
|||
if not muc_service:
|
||||
error(_("Can't find a MUC service"))
|
||||
return
|
||||
|
||||
|
||||
_jid, xmlstream = self.host.getJidNStream(profile)
|
||||
d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile)
|
||||
d.addCallback(radiocolRoomJoined)
|
||||
|
|
@ -184,7 +184,7 @@ class Radiocol():
|
|||
client = self.host.getClient(profile)
|
||||
if not client:
|
||||
error(_("Can't access profile's data"))
|
||||
return
|
||||
return
|
||||
try:
|
||||
song = OggVorbis(song_path)
|
||||
except OggVorbisHeaderError:
|
||||
|
|
@ -213,7 +213,7 @@ class Radiocol():
|
|||
self.host.profiles[profile].xmlstream.send(mess)
|
||||
|
||||
radio_data = self.radios[jid.JID(referee).userhost()] #FIXME: referee comes from Libervia's client side, it's unsecure
|
||||
radio_data['to_delete'][filename] = song_path #FIXME: works only because of the same host trick, see the note under the docstring
|
||||
radio_data['to_delete'][filename] = song_path #FIXME: works only because of the same host trick, see the note under the docstring
|
||||
|
||||
def playNext(self, room_jid, profile):
|
||||
""""Play next sont in queue if exists, and put a timer
|
||||
|
|
@ -248,22 +248,22 @@ class Radiocol():
|
|||
except KeyError:
|
||||
error(_("INTERNAL ERROR: can't find full path of the song to delete"))
|
||||
return
|
||||
|
||||
#we wait more than the song length to delete the file, to manage poorly reactive networks/clients
|
||||
|
||||
#we wait more than the song length to delete the file, to manage poorly reactive networks/clients
|
||||
reactor.callLater(length + 90, unlink, file_to_delete) #FIXME: same host trick (see above)
|
||||
|
||||
|
||||
def radiocol_game_cmd(self, mess_elt, profile):
|
||||
#FIXME: we should check sender (is it referee ?) here before accepting commands
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
radio_elt = mess_elt.firstChildElement()
|
||||
radio_data = self.radios[room_jid.userhost()]
|
||||
occupants_data = radio_data['occupants_data']
|
||||
queue = radio_data['queue']
|
||||
|
||||
|
||||
for elt in radio_elt.elements():
|
||||
|
||||
|
||||
if elt.name == 'started': #new game created
|
||||
self.host.bridge.radiocolStarted(room_jid.userhost(), from_jid.full(), profile)
|
||||
elif elt.name == 'preload': #a song is in queue and must be preloaded
|
||||
|
|
@ -279,7 +279,7 @@ class Radiocol():
|
|||
elif elt.name == 'song_added': #a song has been added
|
||||
#FIXME: we are KISS for the proof of concept: every song is added, to a limit of 3 in queue.
|
||||
# Need to manage some sort of rules to allow peoples to send songs
|
||||
|
||||
|
||||
if len(queue) >= QUEUE_LIMIT:
|
||||
#there are already too many songs in queue, we reject this one
|
||||
mess = self.createRadiocolElt(room_jid)
|
||||
|
|
@ -289,7 +289,7 @@ class Radiocol():
|
|||
#FIXME: add an error code
|
||||
self.host.profiles[profile].xmlstream.send(mess)
|
||||
return
|
||||
|
||||
|
||||
#The song is accepted and added in queue
|
||||
queue.append((elt['filename'], float(elt['length'])))
|
||||
|
||||
|
|
@ -317,13 +317,13 @@ class Radiocol():
|
|||
self.playNext(room_jid, profile)
|
||||
else:
|
||||
error (_('Unmanaged game element: %s') % elt.name)
|
||||
|
||||
|
||||
def getHandler(self, profile):
|
||||
return RadiocolHandler(self)
|
||||
|
||||
class RadiocolHandler (XMPPHandler):
|
||||
implements(iwokkel.IDisco)
|
||||
|
||||
|
||||
def __init__(self, plugin_parent):
|
||||
self.plugin_parent = plugin_parent
|
||||
self.host = plugin_parent.host
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue