core: use of the new core.log module:

/!\ this is a massive refactoring and was largely automated, it probably did bring some bugs /!\
This commit is contained in:
Goffi 2014-04-19 19:19:19 +02:00
commit 501bc92528
40 changed files with 707 additions and 941 deletions

View file

@ -1,271 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# SAT plugin for managing xep-0045
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 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 logging import debug, info, warning, error
from twisted.words.xish import domish
from twisted.internet import protocol, defer, threads, reactor
from twisted.words.protocols.jabber import client, jid, xmlstream
from twisted.words.protocols.jabber import error as jab_error
from twisted.words.protocols.jabber.xmlstream import IQ
from twisted.web.client import getPage
from sat.memory.persistent import PersistentBinaryDict
import os.path
import pdb
from zope.interface import implements
from wokkel import disco, iwokkel, data_form
from sat.tools.xml_tools import XMLUI
import urllib
import webbrowser
from BeautifulSoup import BeautifulSoup
import re
PLUGIN_INFO = {
"name": "CouchSurfing plugin",
"import_name": "CS",
"type": "Misc",
"protocols": [],
"dependencies": [],
"main": "CS_Plugin",
"handler": "no",
"description": _(u"""This plugin allow to manage your CouchSurfing account throught your SàT frontend""")
}
AGENT = 'Salut à Toi XMPP/CS Plugin'
class CS_Plugin(object):
params = """
<params>
<individual>
<category name="CouchSurfing">
<param name="Login" type="string" />
<param name="Password" type="password" />
</category>
</individual>
</params>
"""
def __init__(self, host):
info(_("Plugin CS initialization"))
self.host = host
#parameters
host.memory.updateParams(CS_Plugin.params)
#menu
host.importMenu(_("Plugin"), "CouchSurfing", self.menuSelected, help_string=_("Launch CoushSurfing management interface"))
self.data = {} # TODO: delete cookies/data after a while
self.host.registerGeneralCB("plugin_CS_sendMessage", self.sendMessage)
self.host.registerGeneralCB("plugin_CS_showUnreadMessages", self.showUnreadMessages)
def profileConnected(self, profile):
self.data[profile] = PersistentBinaryDict("plugin_CS", profile)
def dataLoaded(ignore):
if not self.data[profile]:
self.data[profile] = {'cookies': {}}
self.data[profile].load().addCallback(dataLoaded)
def profileDisconnected(self, profile):
del self.data[profile]
def erroCB(self, e, id):
"""Called when something is going wrong when contacting CS website"""
#pdb.set_trace()
message_data = {"reason": "connection error", "message": _(u"Impossible to contact CS website, please check your login/password, connection or try again later")}
self.host.bridge.actionResult("ERROR", id, message_data)
def menuSelected(self, id, profile):
"""Called when the couchsurfing menu item is selected"""
login = self.host.memory.getParamA("Login", "CouchSurfing", profile_key=profile)
password = self.host.memory.getParamA("Password", "CouchSurfing", profile_key=profile)
if not login or not password:
message_data = {"reason": "uncomplete", "message": _(u"You have to fill your CouchSurfing login & password in parameters before using this interface")}
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...'})
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)
#self.host.bridge.actionResult("SUPPRESS", id, {})
#pages parsing callbacks
def savePage(self, name, html):
f = open('/tmp/CS_' + name + '.html', 'w')
f.write(html)
f.close()
print "page [%s] sauvee" % name
#pdb.set_trace()
def __connectionCB(self, html, id, profile):
print 'Response received'
#self.savePage('principale',html)
soup = BeautifulSoup(html)
self.data[profile]['user_nick'] = soup.find('a', 'item_link', href='/home.html').contents[0]
self.data[profile]['user_name'] = soup.html.head.title.string.split(' - ')[1]
#unread messages
try:
self.data[profile]['unread_messages'] = int(soup.find(lambda tag: tag.name == 'div' and ('class', 'item_bubble') in tag.attrs and tag.find('a', href="/messages.html?message_status=inbox")).find(text=True))
except:
self.data[profile]['unread_messages'] = 0
#unread couchrequest messages
try:
self.data[profile]['unread_CR_messages'] = int(soup.find(lambda tag: tag.name == 'div' and ('class', 'item_bubble') in tag.attrs and tag.find('a', href="/couchmanager")).find(text=True))
except:
self.data[profile]['unread_CR_messages'] = 0
#if we have already the list of friend, no need to make new requests
if 'friends' not in self.data[profile]:
self.data[profile]['friends'] = {}
d = getPage('http://www.couchsurfing.org/connections.html?type=myfriends&show=10000', agent=AGENT, cookies=self.data[profile]['cookies'])
d.addCallback(self.__friendsPageCB, id=id, profile=profile)
d.addErrback(self.erroCB, id)
else:
self.host.bridge.actionResult("XMLUI", id, {"type": "window", "xml": self.__buildUI(self.data[profile])})
def __buildUI(self, data):
"""Build the XML UI of the plugin
@param data: data store for the profile"""
user_nick = data['user_nick']
user_name = data['user_name']
unread_mess = data['unread_messages']
unread_CR_mess = data['unread_CR_messages']
friends_list = data['friends'].keys()
friends_list.sort()
interface = XMLUI('window', 'tabs', title='CouchSurfing management')
interface.addCategory(_("Messages"), "vertical")
interface.addText(_("G'day %(name)s, you have %(nb_message)i unread message%(plural_mess)s and %(unread_CR_mess)s unread couch request message%(plural_CR)s\nIf you want to send a message, select the recipient(s) in the list below") % {'name': user_name, 'nb_message': unread_mess, 'plural_mess': 's' if unread_mess > 1 else '', 'unread_CR_mess': unread_CR_mess, 'plural_CR': 's' if unread_CR_mess > 1 else ''})
if unread_mess:
interface.addButton('plugin_CS_showUnreadMessages', 'showUnreadMessages', _('Show unread message%(plural)s in external web browser') % {'plural': 's' if unread_mess > 1 else ''})
interface.addList(friends_list, 'friends', None, style=['multi'])
interface.changeLayout('pairs')
interface.addLabel(_("Subject"))
interface.addString('subject')
interface.changeLayout('vertical')
interface.addLabel(_("Message"))
interface.addText("(use %name% for contact name and %firstname% for guessed first name)")
interface.addTextBox('message')
interface.addButton('plugin_CS_sendMessage', 'sendMessage', _('send'), fields_back=['friends', 'subject', 'message'])
#interface.addCategory(_("Events"), "vertical") #TODO: coming soon, hopefuly :)
#interface.addCategory(_("Couch search"), "vertical")
return interface.toXml()
def __meetingPageCB(self, html):
"""Called when the meeting page has been received"""
def __friendsPageCB(self, html, id, profile):
"""Called when the friends list page has been received"""
self.savePage('friends', html)
soup = BeautifulSoup(html.replace('"formtable width="400', '"formtable" width="400"')) # CS html fix #TODO: report the bug to CS dev team
friends = self.data[profile]['friends']
for _tr in soup.findAll('tr', {'class': re.compile("^msgRow*")}): # we parse the row with friends infos
_nobr = _tr.find('nobr') # contain the friend name
friend_name = unicode(_nobr.string)
friend_link = u'http://www.couchsurfing.org' + _nobr.parent['href']
regex_href = re.compile(r'/connections\.html\?id=([^&]+)')
a_tag = _tr.find('a', href=regex_href)
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}
a = soup.find('td', 'barmiddle next').a # is there several pages ?
if a:
#yes, we parse the next page
d = getPage('http://www.couchsurfing.org/' + str(a['href']), agent=AGENT, cookies=self.data[profile]['cookies'])
d.addCallback(self.__friendsPageCB, id=id, profile=profile)
d.addErrback(self.erroCB, id)
else:
#no, we show the result
self.host.bridge.actionResult("XMLUI", id, {"type": "window", "xml": self.__buildUI(self.data[profile])})
def __sendMessage(self, answer, subject, message, data, recipient_list, id, profile):
"""Send actually the message
@param subject: subject of the message
@param message: body of the message
@param data: data of the profile
@param recipient_list: list of friends names, names are removed once message is sent
@param id: id of the action
@param profile: profile who launched the action
"""
if answer:
if not 'Here is a copy of the email that was sent' in answer:
error(_("INTERNAL ERROR: no confirmation of message sent by CS, maybe the site has been modified ?"))
#TODO: throw a warning to the frontend, saying that maybe the message has not been sent and to contact dev of this plugin
#debug(_('HTML answer: %s') % answer)
if recipient_list:
recipient = recipient_list.pop()
try:
friend_id = data['friends'][recipient]['id']
except KeyError:
error('INTERNAL ERROR: unknown friend')
return # send an error to the frontend
mess = message.replace('%name%', recipient).replace('%firstname%', recipient.split(' ')[0])
info(_('Sending message to %s') % recipient)
debug(_("\nsubject: %(subject)s\nmessage: \n---\n%(message)s\n---\n\n") % {'subject': subject, 'message': mess})
post_data = urllib.urlencode({'email[subject]': subject.encode('utf-8'), 'email[body]': mess.encode('utf-8'), 'email[id]': friend_id, 'email[action]': 'Send Message', 'email[replied_id]': '', 'email[couchsurf]': '', 'email[directions_to_add]': ''})
d = getPage("http://www.couchsurfing.org/send_message.html", method='POST', postdata=post_data, headers={'Content-Type': 'application/x-www-form-urlencoded'}, agent=AGENT, cookies=data['cookies'])
d.addCallback(self.__sendMessage, subject, message, data, recipient_list, id, profile)
d.addErrback(self.erroCB, id)
else:
interface = XMLUI('window', title=_('Message sent')) # TODO: create particular actionResult for alerts ?
interface.addText(_('The message has been sent to every recipients'))
self.host.bridge.actionResult("XMLUI", id, {"type": "window", "xml": interface.toXml()})
def sendMessage(self, id, data, profile):
"""Called to send a message to a friend
@param data: dict with the following keys:
friend: name of the recipient
subject: subject of the message
message: body of the message, with the following special keywords:
- %name%: name of the friend
- %firstname%: guessed first name of the friend (currently the first part of the name)
"""
if not data['friends']:
message_data = {"reason": "bad data", "message": _(u"There is not recipient selected for this message !")}
self.host.bridge.actionResult("ERROR", id, message_data)
return
friends = data['friends'].split('\t')
subject = data['subject']
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.
soup = BeautifulSoup(html)
for tag in soup.findAll(lambda tag: tag.name == 'strong' and tag.a and tag.a['href'].startswith('messages.html?message_status=inbox')):
link = "http://www.couchsurfing.org/" + str(tag.a['href'])
webbrowser.open_new_tab(link) # TODO: the web browser need to already have CS cookies (i.e. already be opened & logged on CS, or be permanently loggued), a warning to the user should be sent/or a balloon-tip
def showUnreadMessages(self, id, data, profile):
"""Called when user want to see all unread messages in the external browser"""
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)

View file

@ -19,7 +19,8 @@
from sat.core.i18n import _, D_
from sat.core.constants import Const as C
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.protocols.jabber import jid
from twisted.internet import defer, reactor
from wokkel import data_form
@ -53,7 +54,7 @@ PLUGIN_INFO = {
class AdHocDBus(object):
def __init__(self, host):
info(_("plugin Ad-Hoc D-Bus initialization"))
log.info(_("plugin Ad-Hoc D-Bus initialization"))
self.host = host
host.bridge.addMethod("adHocDBusAddAuto", ".plugin", in_sign='sasasasasasass', out_sign='(sa(sss))',
method=self._adHocDBusAddAuto,
@ -97,7 +98,7 @@ class AdHocDBus(object):
@defer.inlineCallbacks
def _introspect(self, methods, bus_name, proxy):
debug("introspecting path [%s]" % proxy.object_path)
log.debug("introspecting path [%s]" % proxy.object_path)
introspect_xml = yield self._DBusIntrospect(proxy)
el = etree.fromstring(introspect_xml)
for node in el.iterchildren('node', 'interface'):
@ -108,13 +109,13 @@ class AdHocDBus(object):
elif node.tag == 'interface':
name = node.get('name')
if any(name.startswith(ignored) for ignored in IGNORED_IFACES_START):
debug('interface [%s] is ignored' % name)
log.debug('interface [%s] is ignored' % name)
continue
debug("introspecting interface [%s]" % name)
log.debug("introspecting interface [%s]" % name)
for method in node.iterchildren('method'):
if self._acceptMethod(method):
method_name = method.get('name')
debug("method accepted: [%s]" % method_name)
log.debug("method accepted: [%s]" % method_name)
methods.add((proxy.object_path, name, method_name))
def _adHocDBusAddAuto(self, prog_name, allowed_jids, allowed_groups, allowed_magics, forbidden_jids, forbidden_groups, flags, profile_key):
@ -125,13 +126,13 @@ class AdHocDBus(object):
bus_names = yield self._DBusListNames()
bus_names = [bus_name for bus_name in bus_names if '.' + prog_name in bus_name]
if not bus_names:
info("Can't find any bus for [%s]" % prog_name)
log.info("Can't find any bus for [%s]" % prog_name)
return
bus_names.sort()
for bus_name in bus_names:
if bus_name.endswith(prog_name):
break
info("bus name found: [%s]" % bus_name)
log.info("bus name found: [%s]" % bus_name)
proxy = self.session_bus.get_object(bus_name, '/', introspect=False)
methods = set()

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.protocols.jabber import jid
from twisted.internet import reactor, protocol
@ -47,13 +48,13 @@ class ExportCommandProtocol(protocol.ProcessProtocol):
def _clean(self, data):
if not data:
error ("data should not be empty !")
log.error ("data should not be empty !")
return u""
decoded = data.decode('utf-8', 'ignore')[:-1 if data[-1] == '\n' else None]
return clean_ustr(decoded)
def connectionMade(self):
info("connectionMade :)")
log.info("connectionMade :)")
def outReceived(self, data):
self.parent.host.sendMessage(self.target, self._clean(data), no_trigger=True, profile_key=self.profile)
@ -62,7 +63,7 @@ class ExportCommandProtocol(protocol.ProcessProtocol):
self.parent.host.sendMessage(self.target, self._clean(data), no_trigger=True, profile_key=self.profile)
def processEnded(self, reason):
info (u"process finished: %d" % (reason.value.exitCode,))
log.info (u"process finished: %d" % (reason.value.exitCode,))
self.parent.removeProcess(self.target, self)
def write(self, message):
@ -83,7 +84,7 @@ class CommandExport(object):
# this is specially true if we have other triggers.
def __init__(self, host):
info(_("Plugin command export initialization"))
log.info(_("Plugin command export initialization"))
self.host = host
self.spawned = {} # key = entity
host.trigger.add("MessageReceived", self.MessageReceivedTrigger, priority=10000)
@ -109,7 +110,7 @@ class CommandExport(object):
body = [e for e in message.elements() if e.name == 'body'][0]
except IndexError:
# do not block message without body (chat state notification...)
warning("No body element found in message, following normal behaviour")
log.warning("No body element found in message, following normal behaviour")
return True
mess_data = unicode(body) + '\n'
@ -141,7 +142,7 @@ class CommandExport(object):
"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
warning("Unknown profile [%s]" % (profile,))
log.warning("Unknown profile [%s]" % (profile,))
return
for target in targets:
@ -151,7 +152,7 @@ class CommandExport(object):
raise jid.InvalidFormat
_jid = _jid.userhostJID()
except (jid.InvalidFormat, RuntimeError):
info(u"invalid target ignored: %s" % (target,))
log.info(u"invalid target ignored: %s" % (target,))
continue
process_prot = ExportCommandProtocol(self, _jid, options, profile)
self.spawned.setdefault((_jid, profile),set()).add(process_prot)

View file

@ -19,7 +19,8 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.protocols.jabber import jid
from sat.core.exceptions import UnknownEntityError
@ -46,14 +47,14 @@ class Exp_Parrot(object):
# /unparrot command in text commands plugin.
def __init__(self, host):
info(_("Plugin Parrot initialization"))
log.info(_("Plugin Parrot initialization"))
self.host = host
host.trigger.add("MessageReceived", self.MessageReceivedTrigger, priority=100)
#host.trigger.add("sendMessage", self.sendMessageTrigger, priority=100)
try:
self.host.plugins[C.TEXT_CMDS].registerTextCommands(self)
except KeyError:
info(_("Text commands not available"))
log.info(_("Text commands not available"))
#def sendMessageTrigger(self, mess_data, treatments, profile):
# """ Deactivate other triggers if recipient is in parrot links """
@ -64,7 +65,7 @@ class Exp_Parrot(object):
# return True
#
# if mess_data['to'].userhostJID() in _links.values():
# debug("Parrot link detected, skipping other triggers")
# log.debug("Parrot link detected, skipping other triggers")
# raise SkipOtherTriggers
def MessageReceivedTrigger(self, message, post_treat, profile):
@ -101,7 +102,7 @@ class Exp_Parrot(object):
self.host.sendMessage(jid.JID(unicode(linked)), msg, None, "auto", no_trigger=True, profile_key=profile)
else:
warning("No body element found in message, following normal behaviour")
log.warning("No body element found in message, following normal behaviour")
return True
@ -117,7 +118,7 @@ class Exp_Parrot(object):
_links = client.parrot_links = {}
_links[source_jid.userhostJID()] = dest_jid
info("Parrot mode: %s will be repeated to %s" % (source_jid.userhost(), unicode(dest_jid)))
log.info("Parrot mode: %s will be repeated to %s" % (source_jid.userhost(), unicode(dest_jid)))
def removeParrot(self, source_jid, profile):
"""Remove parrot link
@ -131,7 +132,7 @@ class Exp_Parrot(object):
def cmd_parrot(self, mess_data, profile):
"""activate Parrot mode between 2 entities, in both directions."""
debug("Catched parrot command")
log.debug("Catched parrot command")
txt_cmd = self.host.plugins[C.TEXT_CMDS]
try:
@ -153,7 +154,7 @@ class Exp_Parrot(object):
def cmd_unparrot(self, mess_data, profile):
"""remove Parrot mode between 2 entities, in both directions."""
debug("Catched unparrot command")
log.debug("Catched unparrot command")
txt_cmd = self.host.plugins[C.TEXT_CMDS]
try:

View file

@ -19,10 +19,11 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.xish import domish
from twisted.words.protocols.jabber import jid
from twisted.words.protocols.jabber import error as jab_error
from twisted.words.protocols import jabber
from twisted.internet import reactor
from wokkel import data_form
@ -47,7 +48,7 @@ class Exp_Pipe(object):
"""This is a modified version of XEP-0096 to work with named pipes instead of files"""
def __init__(self, host):
info(_("Plugin Pipe initialization"))
log.info(_("Plugin Pipe initialization"))
self.host = host
self.managed_stream_m = [self.host.plugins["XEP-0065"].NAMESPACE,
self.host.plugins["XEP-0047"].NAMESPACE] # Stream methods managed
@ -62,12 +63,12 @@ class Exp_Pipe(object):
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"""
info(_("SI Pipe Transfer: TimeOut reached for id %s") % approval_id)
log.info(_("SI Pipe Transfer: TimeOut reached for id %s") % approval_id)
try:
client = self.host.getClient(profile)
del client._pipe_waiting_for_approval[approval_id]
except KeyError:
warning(_("kill id called on a non existant approval id"))
log.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
@ -77,14 +78,14 @@ class Exp_Pipe(object):
@param si_mime_type: Mime type of the pipe (or default "application/octet-stream" if unknown)
@param si_el: domish.Element of the request
@param profile: %(doc_profile)s"""
info(_("EXP-PIPE file transfer requested"))
debug(si_el.toXml())
log.info(_("EXP-PIPE file transfer requested"))
log.debug(si_el.toXml())
client = self.host.getClient(profile)
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"))
log.warning(_("No pipe element found"))
self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
return
@ -94,15 +95,15 @@ class Exp_Pipe(object):
try:
stream_method = self.host.plugins["XEP-0020"].negociate(feature_el, 'stream-method', self.managed_stream_m)
except KeyError:
warning(_("No stream method found"))
log.warning(_("No stream method found"))
self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
return
if not stream_method:
warning(_("Can't find a valid stream method"))
log.warning(_("Can't find a valid stream method"))
self.host.plugins["XEP-0095"].sendFailedError(iq_id, from_jid, profile)
return
else:
warning(_("No feature element found"))
log.warning(_("No feature element found"))
self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
return
@ -125,7 +126,7 @@ class Exp_Pipe(object):
try:
dest_path = frontend_data['dest_path']
except KeyError:
error(_('dest path not found in frontend_data'))
log.error(_('dest path not found in frontend_data'))
del(client._pipe_waiting_for_approval[sid])
return
if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
@ -135,7 +136,7 @@ class Exp_Pipe(object):
file_obj = open(dest_path, 'w+')
self.host.plugins["XEP-0047"].prepareToReceive(jid.JID(data['from']), sid, file_obj, None, self._transferSucceeded, self._transferFailed, profile)
else:
error(_("Unknown stream method, this should not happen at this stage, cancelling transfer"))
log.error(_("Unknown stream method, this should not happen at this stage, cancelling transfer"))
del(client._pipe_waiting_for_approval[sid])
return
@ -145,7 +146,7 @@ class Exp_Pipe(object):
misc_elts.append(domish.Element((PROFILE, "file")))
self.host.plugins["XEP-0095"].acceptStream(data["id"], data['from'], feature_elt, misc_elts, profile)
else:
debug(_("Transfer [%s] refused"), sid)
log.debug(_("Transfer [%s] refused"), sid)
self.host.plugins["XEP-0095"].sendRejectedError(data["id"], data['from'], profile=profile)
del(client._pipe_waiting_for_approval[sid])
@ -154,7 +155,7 @@ class Exp_Pipe(object):
@param id: stream id"""
client = self.host.getClient(profile)
file_obj.close()
info(_('Transfer %s successfuly finished') % sid)
log.info(_('Transfer %s successfuly finished') % sid)
del(client._pipe_waiting_for_approval[sid])
def _transferFailed(self, sid, file_obj, stream_method, reason, profile):
@ -163,41 +164,41 @@ class Exp_Pipe(object):
@param reason: can be TIMEOUT, IO_ERROR, PROTOCOL_ERROR"""
client = self.host.getClient(profile)
data, timeout, stream_method, failed_methods, profile = client._pipe_waiting_for_approval[sid]
warning(_('Transfer %(id)s failed with stream method %(s_method)s') % {'id': sid,
log.warning(_('Transfer %(id)s failed with stream method %(s_method)s') % {'id': sid,
's_method': stream_method})
# filepath = file_obj.name
file_obj.close()
#TODO: session remenber (within a time limit) when a stream method fail, and avoid that stream method with full jid for the rest of the session
warning(_("All stream methods failed, can't transfer the file"))
log.warning(_("All stream methods failed, can't transfer the file"))
del(client._pipe_waiting_for_approval[sid])
def pipeCb(self, filepath, sid, profile, IQ):
if IQ['type'] == "error":
stanza_err = jab_error.exceptionFromStanza(IQ)
stanza_err = jabber.error.exceptionFromStanza(IQ)
if stanza_err.code == '403' and stanza_err.condition == 'forbidden':
debug(_("Pipe transfer refused by %s") % IQ['from'])
log.debug(_("Pipe transfer refused by %s") % IQ['from'])
self.host.bridge.newAlert(_("The contact %s refused your pipe stream") % IQ['from'], _("Pipe stream refused"), "INFO", profile)
else:
warning(_("Error during pipe stream transfer with %s") % IQ['from'])
log.warning(_("Error during pipe stream transfer with %s") % IQ['from'])
self.host.bridge.newAlert(_("Something went wrong during the pipe stream session intialisation with %s") % IQ['from'], _("Pipe stream error"), "ERROR", profile)
return
si_elt = IQ.firstChildElement()
if IQ['type'] != "result" or not si_elt or si_elt.name != "si":
error(_("Protocol error during file transfer"))
log.error(_("Protocol error during file transfer"))
return
feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_elt)
if not feature_elts:
warning(_("No feature element"))
log.warning(_("No feature element"))
return
choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elts[0])
try:
stream_method = choosed_options["stream-method"]
except KeyError:
warning(_("No stream method choosed"))
log.warning(_("No stream method choosed"))
return
if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
@ -211,7 +212,7 @@ class Exp_Pipe(object):
file_obj = open(filepath, 'r') # XXX: we have to be sure that filepath is well opened, as reading can block it
self.host.plugins["XEP-0047"].startStream(file_obj, jid.JID(IQ['from']), sid, None, self.sendSuccessCb, self.sendFailureCb, None, profile)
else:
warning(_("Invalid stream method received"))
log.warning(_("Invalid stream method received"))
def pipeOut(self, to_jid, filepath, data={}, profile_key=C.PROF_KEY_NONE):
"""send a file using EXP-PIPE
@ -223,7 +224,7 @@ class Exp_Pipe(object):
"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
warning(_("Trying to send a file from an unknown profile"))
log.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})
@ -237,9 +238,9 @@ class Exp_Pipe(object):
return sid
def sendSuccessCb(self, sid, file_obj, stream_method, profile):
info(_('Transfer %s successfuly finished') % sid)
log.info(_('Transfer %s successfuly finished') % sid)
file_obj.close()
def sendFailureCb(self, sid, file_obj, stream_method, reason, profile):
file_obj.close()
warning(_('Transfer %(id)s failed with stream method %(s_method)s %(profile)s') % {'id': sid, "s_method": stream_method, "profile": profile})
log.warning(_('Transfer %(id)s failed with stream method %(s_method)s %(profile)s') % {'id': sid, "s_method": stream_method, "profile": profile})

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _, D_
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from twisted.internet import reactor, defer, protocol
from os.path import join, dirname
@ -88,10 +89,10 @@ class ProsodyRegisterProtocol(protocol.ProcessProtocol):
def processEnded(self, reason):
if (reason.value.exitCode == 0):
info(_('Prosody command succeed'))
log.info(_('Prosody command succeed'))
self.deferred.callback(None)
else:
error(_(u"Can't complete Prosody command (error code: %(code)d): %(message)s") % {'code': reason.value.exitCode, 'message': self.data})
log.error(_(u"Can't complete Prosody command (error code: %(code)d): %(message)s") % {'code': reason.value.exitCode, 'message': self.data})
self.deferred.errback(Failure(exceptions.InternalError))
@classmethod
@ -117,7 +118,7 @@ class MiscAccount(object):
# only focused on Prosody) is planed
def __init__(self, host):
info(_(u"Plugin Account initialization"))
log.info(_(u"Plugin Account initialization"))
self.host = host
host.bridge.addMethod("registerSatAccount", ".plugin", in_sign='sss', out_sign='', method=self._registerAccount, async=True)
host.bridge.addMethod("getNewAccountDomain", ".plugin", in_sign='', out_sign='s', method=self.getNewAccountDomain, async=False)
@ -126,10 +127,10 @@ class MiscAccount(object):
if self._prosody_path is None:
paths = which(self.getConfig('prosodyctl'))
if not paths:
error(_("Can't find %s") % (self.getConfig('prosodyctl'), ))
log.error(_("Can't find %s") % (self.getConfig('prosodyctl'), ))
else:
self._prosody_path = dirname(paths[0])
info(_('Prosody path found: %s') % (self._prosody_path, ))
log.info(_('Prosody path found: %s') % (self._prosody_path, ))
self.__account_cb_id = host.registerCallback(self._accountDialogCb, with_data=True)
self.__delete_account_id = host.registerCallback(self.__deleteAccountCb, with_data=True)
@ -193,7 +194,7 @@ class MiscAccount(object):
def email_ko(ignore):
#TODO: return error code to user
error("Failed to send email to %s" % email)
log.error("Failed to send email to %s" % email)
body = (u"""Welcome to Libervia, a Salut à Toi project part

View file

@ -19,7 +19,8 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet import defer
from twisted.words.protocols.jabber import jid
from twisted.words.xish.domish import Element, generateElementsNamed
@ -83,7 +84,7 @@ class GroupBlog(object):
"""This class use a SàT PubSub Service to manage access on microblog"""
def __init__(self, host):
info(_("Group blog plugin initialization"))
log.info(_("Group blog plugin initialization"))
self.host = host
host.bridge.addMethod("sendGroupBlog", ".plugin", in_sign='sassa{ss}s', out_sign='',
@ -157,18 +158,18 @@ class GroupBlog(object):
#we first check that we have a item-access pubsub server
if not hasattr(client, "item_access_pubsub"):
debug(_('Looking for item-access powered pubsub server'))
log.debug(_('Looking for item-access powered pubsub server'))
#we don't have any pubsub server featuring item access yet
item_access_pubsubs = yield self.host.findFeaturesSet((NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK), "pubsub", "service", profile_key=profile)
# item_access_pubsubs = yield self.host.findFeaturesSet((NS_PUBSUB_ITEM_ACCESS, NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK), "pubsub", "service", profile_key=profile)
try:
client.item_access_pubsub = item_access_pubsubs.pop()
info(_("item-access powered pubsub service found: [%s]") % client.item_access_pubsub.full())
log.info(_("item-access powered pubsub service found: [%s]") % client.item_access_pubsub.full())
except KeyError:
client.item_access_pubsub = None
if not client.item_access_pubsub:
error(_("No item-access powered pubsub server found, can't use group blog"))
log.error(_("No item-access powered pubsub server found, can't use group blog"))
raise NoCompatiblePubSubServerFound
defer.returnValue((profile, client))
@ -186,7 +187,7 @@ class GroupBlog(object):
if (not (origin_host)
or len(event_host) < len(origin_host)
or event_host[-len(origin_host):] != origin_host):
warning("Host incoherence between %s and %s (hack attempt ?)" % (unicode(event.sender),
log.warning("Host incoherence between %s and %s (hack attempt ?)" % (unicode(event.sender),
unicode(publisher)))
return False
@ -243,7 +244,7 @@ class GroupBlog(object):
try:
microblog_data["groups"] = '\n'.join(form.fields[P.OPT_ROSTER_GROUPS_ALLOWED].values)
except KeyError:
warning("No group found for roster access-model")
log.warning("No group found for roster access-model")
microblog_data["groups"] = ''
break
@ -317,7 +318,7 @@ class GroupBlog(object):
elif access_type == "JID":
raise NotImplementedError
else:
error(_("Unknown access_type"))
log.error(_("Unknown access_type"))
raise BadAccessTypeError
defer_blog = self.host.plugins["XEP-0060"].publish(service, node_name, items=[mblog_item], profile_key=client.profile)
@ -373,7 +374,7 @@ class GroupBlog(object):
elif access_type == "JID":
raise NotImplementedError
else:
error(_("Unknown access type"))
log.error(_("Unknown access type"))
raise BadAccessTypeError
return self._initialise(profile_key).addCallback(initialised)
@ -395,10 +396,10 @@ class GroupBlog(object):
# remove the associated comments node
comments_service, comments_node = self.host.plugins["XEP-0277"].parseCommentUrl(comments)
d = self.host.plugins["XEP-0060"].deleteNode(comments_service, comments_node, profile_key=profile)
d.addErrback(lambda failure: error("Deletion of node %s failed: %s" % (comments_node, failure.getErrorMessage())))
d.addErrback(lambda failure: log.error("Deletion of node %s failed: %s" % (comments_node, failure.getErrorMessage())))
# remove the item itself
d = self.host.plugins["XEP-0060"].retractItems(service_jid, node, [item_id], profile_key=profile)
d.addErrback(lambda failure: error("Deletion of item %s from %s failed: %s" % (item_id, node, failure.getErrorMessage())))
d.addErrback(lambda failure: log.error("Deletion of item %s from %s failed: %s" % (item_id, node, failure.getErrorMessage())))
return d
def notify(d):
@ -447,7 +448,7 @@ class GroupBlog(object):
self.__fillCommentsElement(mblog_data, entry_id, node, service_jid)
entry_d = self.host.plugins["XEP-0277"].data2entry(mblog_data, profile)
entry_d.addCallback(lambda mblog_item: self.host.plugins["XEP-0060"].publish(service_jid, node, items=[mblog_item], profile_key=profile))
entry_d.addErrback(lambda failure: error("Modification of %s failed: %s" % (pub_data, failure.getErrorMessage())))
entry_d.addErrback(lambda failure: log.error("Modification of %s failed: %s" % (pub_data, failure.getErrorMessage())))
return entry_d
return self._initialise(profile_key).addCallback(initialised)
@ -501,7 +502,7 @@ class GroupBlog(object):
self.host.plugins["XEP-0060"].subscribe(jid.JID(gbdata["comments_service"]), gbdata["comments_node"],
profile_key=client.profile)
except KeyError:
warning("Missing key for comments")
log.warning("Missing key for comments")
defer.returnValue(ret)
def __getGroupBlogs(self, pub_jid_s, max_items=10, item_ids=None, profile_key=C.PROF_KEY_NONE):
@ -775,8 +776,8 @@ class GroupBlog(object):
main_node = self.getNodeName(jid_)
d = self.host.plugins["XEP-0060"].deleteNode(service, main_node, profile_key=profile)
d.addCallback(lambda dummy: info(_("All microblog's main items from %s have been deleted!") % jid_.userhost()))
d.addErrback(lambda failure: error(_("Deletion of node %(node)s failed: %(message)s") %
d.addCallback(lambda dummy: log.info(_("All microblog's main items from %s have been deleted!") % jid_.userhost()))
d.addErrback(lambda failure: log.error(_("Deletion of node %(node)s failed: %(message)s") %
{'node': main_node, 'message': failure.getErrorMessage()}))
return d
@ -799,7 +800,7 @@ class GroupBlog(object):
main_node = self.getNodeName(jid_)
d = self.host.plugins["XEP-0060"].getItems(service, main_node, profile_key=profile)
d.addCallback(getComments, client)
d.addErrback(lambda failure, main_node: error(_("Retrieval of items for node %(node)s failed: %(message)s") %
d.addErrback(lambda failure, main_node: log.error(_("Retrieval of items for node %(node)s failed: %(message)s") %
{'node': main_node, 'message': failure.getErrorMessage()}), main_node)
blogs.append(d)
@ -822,7 +823,7 @@ class GroupBlog(object):
service, node = self.host.plugins['XEP-0277'].parseCommentUrl(href)
d = self.host.plugins["XEP-0060"].getItems(service, node, profile_key=profile_key)
d.addCallback(lambda items, service, node: (service, node, items), service, node)
d.addErrback(lambda failure, node: error(_("Retrieval of comments for node %(node)s failed: %(message)s") %
d.addErrback(lambda failure, node: log.error(_("Retrieval of comments for node %(node)s failed: %(message)s") %
{'node': node, 'message': failure.getErrorMessage()}), node)
comments.append(d)
dlist = defer.DeferredList(comments)
@ -854,9 +855,9 @@ class GroupBlog(object):
deletions = []
if item_ids: # remove the comments of the user on the given post
d = self.host.plugins['XEP-0060'].retractItems(service, node_id, item_ids, profile_key=profile_key)
d.addCallback(lambda dummy, node_id: debug(_('Comments of user %(user)s in node %(node)s have been retracted') %
d.addCallback(lambda dummy, node_id: log.debug(_('Comments of user %(user)s in node %(node)s have been retracted') %
{'user': user_jid_s, 'node': node_id}), node_id)
d.addErrback(lambda failure, node_id: error(_("Retraction of comments from %(user)s in node %(node)s failed: %(message)s") %
d.addErrback(lambda failure, node_id: log.error(_("Retraction of comments from %(user)s in node %(node)s failed: %(message)s") %
{'user': user_jid_s, 'node': node_id, 'message': failure.getErrorMessage()}), node_id)
deletions.append(d)
return defer.DeferredList(deletions)

View file

@ -18,20 +18,17 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from logging import debug, info, error
import warnings
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet import protocol, defer
from twisted.words.protocols.jabber import error as jab_error
from twisted.cred import portal, checkers, credentials
from twisted.cred import error as cred_error
from twisted.mail import imap4
from twisted.python import failure
from email.parser import Parser
import email.message
import os
from cStringIO import StringIO
from twisted.internet import reactor
import pdb
from zope.interface import implements
@ -61,14 +58,14 @@ class IMAP_server(object):
"""
def __init__(self, host):
info(_("Plugin Imap Server initialization"))
log.info(_("Plugin Imap Server initialization"))
self.host = host
#parameters
host.memory.updateParams(self.params)
port = int(self.host.memory.getParamA("IMAP Port", "Mail Server"))
info(_("Launching IMAP server on port %d"), port)
log.info(_("Launching IMAP server on port %d") % port)
self.server_factory = ImapServerFactory(self.host)
reactor.listenTCP(port, self.server_factory)
@ -78,7 +75,7 @@ class Message(object):
implements(imap4.IMessage)
def __init__(self, uid, flags, mess_fp):
debug('Message Init')
log.debug('Message Init')
self.uid = uid
self.flags = flags
self.mess_fp = mess_fp
@ -87,21 +84,21 @@ class Message(object):
def getUID(self):
"""Retrieve the unique identifier associated with this message.
"""
debug('getUID (message)')
log.debug('getUID (message)')
return self.uid
def getFlags(self):
"""Retrieve the flags associated with this message.
@return: The flags, represented as strings.
"""
debug('getFlags')
log.debug('getFlags')
return self.flags
def getInternalDate(self):
"""Retrieve the date internally associated with this message.
@return: An RFC822-formatted date string.
"""
debug('getInternalDate')
log.debug('getInternalDate')
return self.message['Date']
def getHeaders(self, negate, *names):
@ -111,7 +108,7 @@ class Message(object):
should be omitted from the return value, rather than included.
@return: A mapping of header field names to header field values
"""
debug('getHeaders %s - %s' % (negate, names))
log.debug('getHeaders %s - %s' % (negate, names))
final_dict = {}
to_check = [name.lower() for name in names]
for header in self.message.keys():
@ -123,20 +120,20 @@ class Message(object):
def getBodyFile(self):
"""Retrieve a file object containing only the body of this message.
"""
debug('getBodyFile')
log.debug('getBodyFile')
return StringIO(self.message.get_payload())
def getSize(self):
"""Retrieve the total size, in octets, of this message.
"""
debug('getSize')
log.debug('getSize')
self.mess_fp.seek(0, os.SEEK_END)
return self.mess_fp.tell()
def isMultipart(self):
"""Indicate whether this message has subparts.
"""
debug('isMultipart')
log.debug('isMultipart')
return False
def getSubPart(self, part):
@ -144,7 +141,7 @@ class Message(object):
@param part: The number of the part to retrieve, indexed from 0.
@return: The specified sub-part.
"""
debug('getSubPart')
log.debug('getSubPart')
return TypeError
@ -154,14 +151,14 @@ class SatMailbox(object):
def __init__(self, host, name, profile):
self.host = host
self.listeners = set()
debug('Mailbox init (%s)', name)
log.debug('Mailbox init (%s)', name)
if name != "INBOX":
raise imap4.MailboxException("Only INBOX is managed for the moment")
self.mailbox = self.host.plugins["Maildir"].accessMessageBox(name, self.newMessage, profile)
def newMessage(self):
"""Called when a new message is in the mailbox"""
debug("newMessage signal received")
log.debug("newMessage signal received")
nb_messages = self.getMessageCount()
for listener in self.listeners:
listener.newMessages(nb_messages, None)
@ -169,13 +166,13 @@ class SatMailbox(object):
def getUIDValidity(self):
"""Return the unique validity identifier for this mailbox.
"""
debug('getUIDValidity')
log.debug('getUIDValidity')
return 0
def getUIDNext(self):
"""Return the likely UID for the next message added to this mailbox.
"""
debug('getUIDNext')
log.debug('getUIDNext')
return self.mailbox.getNextUid()
def getUID(self, message):
@ -183,41 +180,41 @@ class SatMailbox(object):
@param message: The message sequence number
@return: The UID of the message.
"""
debug('getUID (%i)' % message)
log.debug('getUID (%i)' % message)
#return self.mailbox.getUid(message-1) #XXX: it seems that this method get uid and not message sequence number
return message
def getMessageCount(self):
"""Return the number of messages in this mailbox.
"""
debug('getMessageCount')
log.debug('getMessageCount')
ret = self.mailbox.getMessageCount()
debug("count = %i" % ret)
log.debug("count = %i" % ret)
return ret
def getRecentCount(self):
"""Return the number of messages with the 'Recent' flag.
"""
debug('getRecentCount')
log.debug('getRecentCount')
return len(self.mailbox.getMessageIdsWithFlag('\\Recent'))
def getUnseenCount(self):
"""Return the number of messages with the 'Unseen' flag.
"""
debug('getUnseenCount')
log.debug('getUnseenCount')
return self.getMessageCount() - len(self.mailbox.getMessageIdsWithFlag('\\SEEN'))
def isWriteable(self):
"""Get the read/write status of the mailbox.
@return: A true value if write permission is allowed, a false value otherwise.
"""
debug('isWriteable')
log.debug('isWriteable')
return True
def destroy(self):
"""Called before this mailbox is deleted, permanently.
"""
debug('destroy')
log.debug('destroy')
def requestStatus(self, names):
"""Return status information about this mailbox.
@ -229,7 +226,7 @@ class SatMailbox(object):
information up would be costly, a deferred whose callback will
eventually be passed this dictionary is returned instead.
"""
debug('requestStatus')
log.debug('requestStatus')
return imap4.statusRequestHelper(self, names)
def addListener(self, listener):
@ -239,7 +236,7 @@ class SatMailbox(object):
@param listener: An object to add to the set of those which will
be notified when the contents of this mailbox change.
"""
debug('addListener %s' % listener)
log.debug('addListener %s' % listener)
self.listeners.add(listener)
def removeListener(self, listener):
@ -252,7 +249,7 @@ class SatMailbox(object):
@raise ValueError: Raised when the given object is not a listener for
this mailbox.
"""
debug('removeListener')
log.debug('removeListener')
if listener in self.listeners:
self.listeners.remove(listener)
else:
@ -267,7 +264,7 @@ class SatMailbox(object):
id if the message is added successfully and whose errback is
invoked otherwise.
"""
debug('addMessage')
log.debug('addMessage')
raise imap4.MailboxException("Client message addition not implemented yet")
def expunge(self):
@ -275,7 +272,7 @@ class SatMailbox(object):
@return: The list of message sequence numbers which were deleted,
or a Deferred whose callback will be invoked with such a list.
"""
debug('expunge')
log.debug('expunge')
self.mailbox.removeDeleted()
def fetch(self, messages, uid):
@ -284,13 +281,13 @@ class SatMailbox(object):
about
@param uid: If true, the IDs specified in the query are UIDs;
"""
debug('fetch (%s, %s)' % (messages, uid))
log.debug('fetch (%s, %s)' % (messages, uid))
if uid:
messages.last = self.mailbox.getMaxUid()
messages.getnext = self.mailbox.getNextExistingUid
for mess_uid in messages:
if mess_uid is None:
debug('stopping iteration')
log.debug('stopping iteration')
raise StopIteration
try:
yield (mess_uid, Message(mess_uid, self.mailbox.getFlagsUid(mess_uid), self.mailbox.getMessageUid(mess_uid)))
@ -318,7 +315,7 @@ class SatMailbox(object):
been performed, or a Deferred whose callback will be invoked with
such a dict.
"""
debug('store')
log.debug('store')
flags = [flag.upper() for flag in flags]
@ -361,13 +358,13 @@ class SatMailbox(object):
Flags with the \\ prefix are reserved for use as system flags.
@return: A list of the flags that can be set on messages in this mailbox.
"""
debug('getFlags')
log.debug('getFlags')
return ['\\SEEN', '\\ANSWERED', '\\FLAGGED', '\\DELETED', '\\DRAFT'] # TODO: add '\\RECENT'
def getHierarchicalDelimiter(self):
"""Get the character which delimits namespaces for in this mailbox.
"""
debug('getHierarchicalDelimiter')
log.debug('getHierarchicalDelimiter')
return '.'
@ -375,12 +372,12 @@ class ImapSatAccount(imap4.MemoryAccount):
#implements(imap4.IAccount)
def __init__(self, host, profile):
debug("ImapAccount init")
log.debug("ImapAccount init")
self.host = host
self.profile = profile
imap4.MemoryAccount.__init__(self, profile)
self.addMailbox("Inbox") # We only manage Inbox for the moment
debug('INBOX added')
log.debug('INBOX added')
def _emptyMailbox(self, name, id):
return SatMailbox(self.host, name, self.profile)
@ -393,7 +390,7 @@ class ImapRealm(object):
self.host = host
def requestAvatar(self, avatarID, mind, *interfaces):
debug('requestAvatar')
log.debug('requestAvatar')
profile = avatarID.decode('utf-8')
if imap4.IAccount not in interfaces:
raise NotImplementedError
@ -436,13 +433,13 @@ class ImapServerFactory(protocol.ServerFactory):
self.host = host
def startedConnecting(self, connector):
debug(_("IMAP server connection started"))
log.debug(_("IMAP server connection started"))
def clientConnectionLost(self, connector, reason):
debug(_("IMAP server connection lost (reason: %s)"), reason)
log.debug(_("IMAP server connection lost (reason: %s)"), reason)
def buildProtocol(self, addr):
debug("Building protocol")
log.debug("Building protocol")
prot = protocol.ServerFactory.buildProtocol(self, addr)
prot.portal = portal.Portal(ImapRealm(self.host))
prot.portal.registerChecker(SatProfileCredentialChecker(self.host))

View file

@ -19,11 +19,12 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, info, error
from sat.core.log import getLogger
log = getLogger(__name__)
import warnings
warnings.filterwarnings('ignore', 'the MimeWriter', DeprecationWarning, 'twisted') # FIXME: to be removed, see http://twistedmatrix.com/trac/ticket/4038
from twisted.internet import protocol
from twisted.words.protocols.jabber import error as jab_error
from twisted.words.protocols import jabber
from twisted.cred import portal, checkers
from twisted.mail import imap4, maildir
from email.parser import Parser
@ -58,7 +59,7 @@ class MaildirError(Exception):
class MaildirBox(object):
def __init__(self, host):
info(_("Plugin Maildir initialization"))
log.info(_("Plugin Maildir initialization"))
self.host = host
self.__observed = {}
@ -126,7 +127,7 @@ class MaildirBox(object):
@param mailboxUser: MailboxUser instance"""
if boxname not in self.__mailboxes:
err_msg = _("Trying to remove an mailboxUser not referenced")
error(_("INTERNAL ERROR: ") + err_msg)
log.error(_("INTERNAL ERROR: ") + err_msg)
raise MaildirError(err_msg)
assert self.__mailboxes[profile][boxname] == mailboxUser
del self.__mailboxes[profile][boxname]
@ -145,7 +146,7 @@ class MaildirBox(object):
return self.data[profile][boxname] # the boxname MUST exist in the data
except KeyError:
err_msg = _("Boxname doesn't exist in internal data")
error(_("INTERNAL ERROR: ") + err_msg)
log.error(_("INTERNAL ERROR: ") + err_msg)
raise MaildirError(err_msg)
def getUid(self, boxname, message_id, profile):
@ -284,21 +285,21 @@ class MaildirBox(object):
@param signal: which signal was observed by the caller"""
if (profile, boxname) not in self.__observed:
err_msg = _("Trying to remove an observer for an inexistant mailbox")
error(_("INTERNAL ERROR: ") + err_msg)
log.error(_("INTERNAL ERROR: ") + err_msg)
raise MaildirError(err_msg)
if signal not in self.__observed[(profile, boxname)]:
err_msg = _("Trying to remove an inexistant observer, no observer for this signal")
error(_("INTERNAL ERROR: ") + err_msg)
log.error(_("INTERNAL ERROR: ") + err_msg)
raise MaildirError(err_msg)
if not callback in self.__observed[(profile, boxname)][signal]:
err_msg = _("Trying to remove an inexistant observer")
error(_("INTERNAL ERROR: ") + err_msg)
log.error(_("INTERNAL ERROR: ") + err_msg)
raise MaildirError(err_msg)
self.__observed[(profile, boxname)][signal].remove(callback)
def emitSignal(self, profile, boxname, signal_name):
"""Emit the signal to observer"""
debug('emitSignal %s %s %s' % (profile, boxname, signal_name))
log.debug('emitSignal %s %s %s' % (profile, boxname, signal_name))
try:
for observer_cb in self.__observed[(profile, boxname)][signal_name]:
observer_cb()
@ -334,7 +335,7 @@ class MailboxUser(object):
@param profile: real profile (ie not a profile_key)
THIS OBJECT MUST NOT BE USED DIRECTLY: use MaildirBox.accessMessageBox instead"""
if _maildir._checkBoxReference(name, profile):
error("INTERNAL ERROR: MailboxUser MUST NOT be instancied directly")
log.error("INTERNAL ERROR: MailboxUser MUST NOT be instancied directly")
raise MaildirError('double MailboxUser instanciation')
if name != "INBOX":
raise NotImplementedError
@ -352,7 +353,7 @@ class MailboxUser(object):
self.__uid_table_update()
if observer:
debug("adding observer for %s (%s)" % (name, profile))
log.debug("adding observer for %s (%s)" % (name, profile))
self.maildir.addObserver(observer, profile, name, "NEW_MESSAGE")
def __uid_table_update(self):
@ -365,7 +366,7 @@ class MailboxUser(object):
def __del__(self):
if self.observer:
debug("removing observer for %s" % self.name)
log.debug("removing observer for %s" % self.name)
self._maildir.removeObserver(self.observer, self.name, "NEW_MESSAGE")
self.maildir._removeBoxAccess(self.name, self, profile=self.profile)

View file

@ -19,11 +19,12 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.xish import domish
from twisted.internet import protocol, defer, threads, reactor
from twisted.words.protocols.jabber import client, jid, xmlstream
from twisted.words.protocols.jabber import error as jab_error
from twisted.words.protocols import jabber
from twisted.words.protocols.jabber.xmlstream import IQ
import random
@ -54,7 +55,7 @@ class Quiz(object):
self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {})
def __init__(self, host):
info(_("Plugin Quiz initialization"))
log.info(_("Plugin Quiz initialization"))
self.inheritFromRoomGame(host)
RoomGame._init_(self, host, PLUGIN_INFO, (NS_QG, QG_TAG), game_init={'stage': None}, player_init={'score': 0})
host.bridge.addMethod("quizGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom) # args: players, room_jid, profile
@ -180,9 +181,9 @@ class Quiz(object):
"""Called when a player give an answer"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error(_("profile %s is unknown") % profile_key)
log.error(_("profile %s is unknown") % profile_key)
return
debug('new player answer (%(profile)s): %(answer)s' % {'profile': profile, 'answer': answer})
log.debug('new player answer (%(profile)s): %(answer)s' % {'profile': profile, 'answer': answer})
mess = self.createGameElt(jid.JID(referee))
answer_elt = mess.firstChildElement().addElement('player_answer')
answer_elt['player'] = player
@ -280,7 +281,7 @@ Attention, tu es prêt ?""")}
status = self.games[room_jid.userhost()]['status']
nb_players = len(self.games[room_jid.userhost()]['players'])
status[player] = 'ready'
debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
self.newGame(room_jid, profile)
@ -328,4 +329,4 @@ Attention, tu es prêt ?""")}
self.host.bridge.quizGameTimerRestarted(room_jid.userhost(), int(elt['time_left']), profile)
else:
error(_('Unmanaged game element: %s') % elt.name)
log.error(_('Unmanaged game element: %s') % elt.name)

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _, D_
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.xish import domish
from twisted.internet import reactor
from twisted.words.protocols.jabber import jid
@ -63,7 +64,7 @@ class Radiocol(object):
self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {})
def __init__(self, host):
info(_("Radio collective initialization"))
log.info(_("Radio collective initialization"))
self.inheritFromRoomGame(host)
RoomGame._init_(self, host, PLUGIN_INFO, (NC_RADIOCOL, RADIOC_TAG),
game_init={'queue': [], 'upload': True, 'playing': None, 'playing_time': 0, 'to_delete': {}})
@ -135,7 +136,7 @@ class Radiocol(object):
# ==> unlink done the Q&D way with the same host trick (see above)
radio_data = self.games[room_jid.userhost()]
if len(radio_data['players']) == 0:
debug(_('No more participants in the radiocol: cleaning data'))
log.debug(_('No more participants in the radiocol: cleaning data'))
radio_data['queue'] = []
for filename in radio_data['to_delete']:
self.deleteFile(filename, radio_data)
@ -171,14 +172,14 @@ class Radiocol(object):
try:
file_to_delete = radio_data['to_delete'][filename]
except KeyError:
error(_("INTERNAL ERROR: can't find full path of the song to delete"))
log.error(_("INTERNAL ERROR: can't find full path of the song to delete"))
return False
else:
file_to_delete = filename
try:
unlink(file_to_delete)
except OSError:
error(_("INTERNAL ERROR: can't find %s on the file system" % file_to_delete))
log.error(_("INTERNAL ERROR: can't find %s on the file system" % file_to_delete))
return False
return True
@ -241,7 +242,7 @@ class Radiocol(object):
# songs in queue. We can now start the party :)
self.playNext(room_jid, profile)
else:
error(_('Unmanaged game element: %s') % elt.name)
log.error(_('Unmanaged game element: %s') % elt.name)
def getSyncDataForPlayer(self, room_jid_s, nick):
game_data = self.games[room_jid_s]

View file

@ -19,7 +19,8 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.protocols.jabber.jid import JID
from twisted.words.xish import domish
from twisted.internet import defer
@ -199,7 +200,7 @@ class RoomGame(object):
break
if not auth and (verbose or _DEBUG):
debug(_("%(user)s not allowed to join the game %(game)s in %(room)s") % {'user': user_jid_s or nick, 'game': self.name, 'room': room_jid_s})
log.debug(_("%(user)s not allowed to join the game %(game)s in %(room)s") % {'user': user_jid_s or nick, 'game': self.name, 'room': room_jid_s})
return auth
def _updatePlayers(self, room_jid_s, nicks, sync, profile):
@ -335,7 +336,7 @@ class RoomGame(object):
elif self.invite_mode == self.FROM_PLAYERS:
auth = self.isPlayer(room_jid_s, nick)
if not auth and (verbose or _DEBUG):
debug(_("%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid_s})
log.debug(_("%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid_s})
return auth
def isReferee(self, room_jid_s, nick):
@ -381,7 +382,7 @@ class RoomGame(object):
(nicks, missing) = self.host.plugins["XEP-0045"].getRoomNicksOfUsers(room, other_players, secure=False)
result = (len(nicks) == len(other_players), nicks, missing)
if not result[0] and (verbose or _DEBUG):
debug(_("Still waiting for %(users)s before starting the game %(game)s in %(room)s") % {'users': result[2], 'game': self.name, 'room': room.occupantJID.userhost()})
log.debug(_("Still waiting for %(users)s before starting the game %(game)s in %(room)s") % {'users': result[2], 'game': self.name, 'room': room.occupantJID.userhost()})
return result
def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
@ -402,10 +403,10 @@ class RoomGame(object):
@param room_jid_s: JID userhost of the room, or None to generate a unique name
@param profile_key
"""
debug(_('Preparing room for %s game') % self.name)
log.debug(_('Preparing room for %s game') % self.name)
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error(_("Unknown profile"))
log.error(_("Unknown profile"))
return
if other_players is None:
other_players = []
@ -446,7 +447,7 @@ class RoomGame(object):
# considering the last batch of invitations
batch = len(self.invitations[room_jid_s]) - 1
if batch < 0:
error("Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid_s))
log.error("Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid_s))
return True
other_players = self.invitations[room_jid_s][batch][1]
(auth, nicks, dummy) = self._checkWaitAuth(room, other_players)
@ -500,15 +501,15 @@ class RoomGame(object):
"""
user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
if not user_nick:
error('Internal error: profile %s has not joined the room %s' % (profile, room_jid_s))
log.error('Internal error: profile %s has not joined the room %s' % (profile, room_jid_s))
return False, False
if self._gameExists(room_jid_s):
is_referee = self.isReferee(room_jid_s, user_nick)
if self._gameExists(room_jid_s, started=True):
warning(_("%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid_s})
log.warning(_("%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid_s})
return False, is_referee
elif not is_referee:
warning(_("%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid_s, 'user': user_nick})
log.warning(_("%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid_s, 'user': user_nick})
return False, False
else:
self._initGame(room_jid_s, user_nick)
@ -523,10 +524,10 @@ class RoomGame(object):
@param nicks: list of players nicks in the room (referee included, in first position)
@param profile_key: %(doc_profile_key)s
"""
debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid_s})
log.debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid_s})
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error(_("profile %s is unknown") % profile_key)
log.error(_("profile %s is unknown") % profile_key)
return
(create, sync) = self._checkCreateGameAndInit(room_jid_s, profile)
if nicks is None:
@ -552,9 +553,9 @@ class RoomGame(object):
"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error(_("profile %s is unknown") % profile_key)
log.error(_("profile %s is unknown") % profile_key)
return
debug('new player ready: %s' % profile)
log.debug('new player ready: %s' % profile)
# TODO: we probably need to add the game and room names in the sent message
self.send(JID(referee), 'player_ready', {'player': player}, profile=profile)
@ -567,7 +568,7 @@ class RoomGame(object):
- msg_elts: dict to map each user to his specific initialization message
@param profile
"""
debug(_('new round for %s game') % self.name)
log.debug(_('new round for %s game') % self.name)
game_data = self.games[room_jid.userhost()]
players = game_data['players']
players_data = game_data['players_data']
@ -635,7 +636,7 @@ class RoomGame(object):
@return: a Deferred instance
"""
if profile is None:
error(_("Message can not be sent without a sender profile"))
log.error(_("Message can not be sent without a sender profile"))
return defer.fail(None)
msg = self._createGameElt(to_jid)
for elem, attrs, content in data:

View file

@ -18,10 +18,9 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from logging import debug, info, error
import warnings
from twisted.internet import protocol, defer
from twisted.words.protocols.jabber import error as jab_error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet import defer
from twisted.cred import portal, checkers, credentials
from twisted.cred import error as cred_error
from twisted.mail import smtp
@ -29,7 +28,6 @@ from twisted.python import failure
from email.parser import Parser
from email.utils import parseaddr
from twisted.mail.imap4 import LOGINCredentials, PLAINCredentials
import os
from twisted.internet import reactor
import sys
@ -60,14 +58,14 @@ class SMTP_server(object):
"""
def __init__(self, host):
info(_("Plugin SMTP Server initialization"))
log.info(_("Plugin SMTP Server initialization"))
self.host = host
#parameters
host.memory.updateParams(self.params)
port = int(self.host.memory.getParamA("SMTP Port", "Mail Server"))
info(_("Launching SMTP server on port %d"), port)
log.info(_("Launching SMTP server on port %d") % port)
self.server_factory = SmtpServerFactory(self.host)
reactor.listenTCP(port, self.server_factory)
@ -93,7 +91,7 @@ class SatSmtpMessage(object):
subject=mail['subject'].decode('utf-8', 'replace'), mess_type='normal', profile_key=self.profile)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
error(_("Can't send message: %s") % exc_value) # The email is invalid or incorreclty parsed
log.error(_("Can't send message: %s") % exc_value) # The email is invalid or incorreclty parsed
return defer.fail()
self.message = None
return defer.succeed(None)
@ -152,7 +150,7 @@ class SmtpRealm(object):
self.host = host
def requestAvatar(self, avatarID, mind, *interfaces):
debug('requestAvatar')
log.debug('requestAvatar')
profile = avatarID.decode('utf-8')
if smtp.IMessageDelivery not in interfaces:
raise NotImplementedError
@ -198,11 +196,11 @@ class SmtpServerFactory(smtp.SMTPFactory):
smtp.SMTPFactory.__init__(self, _portal)
def startedConnecting(self, connector):
debug(_("SMTP server connection started"))
log.debug(_("SMTP server connection started"))
smtp.SMTPFactory.startedConnecting(self, connector)
def clientConnectionLost(self, connector, reason):
debug(_("SMTP server connection lost (reason: %s)"), reason)
log.debug(_("SMTP server connection lost (reason: %s)"), reason)
smtp.SMTPFactory.clientConnectionLost(self, connector, reason)
def buildProtocol(self, addr):

View file

@ -19,7 +19,8 @@
from sat.core.i18n import _
from sat.core.constants import Const as C
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.xish import domish
from twisted.words.protocols.jabber import jid
from twisted.internet import defer
@ -28,7 +29,6 @@ from wokkel import data_form
from sat.memory import memory
from sat.tools import xml_tools
from sat_frontends.tools.games import TarotCard
from time import time
import random
@ -55,7 +55,7 @@ class Tarot(object):
self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {})
def __init__(self, host):
info(_("Plugin Tarot initialization"))
log.info(_("Plugin Tarot initialization"))
self._sessions = memory.Sessions()
self.inheritFromRoomGame(host)
RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
@ -199,7 +199,7 @@ class Tarot(object):
pl_waiting = players_data[player]['wait_for_low']
played.remove(card)
players_data[pl_waiting]['levees'].append(card)
debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": player, "card_waited": card, "player_waiting": pl_waiting})
log.debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": player, "card_waited": card, "player_waiting": pl_waiting})
return
return
@ -230,12 +230,12 @@ class Tarot(object):
low_card = owner_levees[card_idx]
del owner_levees[card_idx]
players_data[winner]['levees'].append(low_card)
debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": excuse_player, "card_waited": low_card, "player_waiting": winner})
log.debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": excuse_player, "card_waited": low_card, "player_waiting": winner})
break
if not low_card: # The player has no low card yet
#TODO: manage case when player never win a trick with low card
players_data[excuse_player]['wait_for_low'] = winner
debug(_("%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one") % {'excuse_owner': excuse_player, 'winner': winner})
log.debug(_("%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one") % {'excuse_owner': excuse_player, 'winner': winner})
def __draw_game(self, game_data):
"""The game is draw, no score change
@ -246,7 +246,7 @@ class Tarot(object):
scores_str += '\n'
for player in game_data['players']:
scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': 0, 'total_score': players_data[player]['score']}
debug(scores_str)
log.debug(scores_str)
return (scores_str, [], [])
@ -295,7 +295,7 @@ class Tarot(object):
elif game_data['contrat'] == 'Garde Contre':
contrat_mult = 6
else:
error(_('INTERNAL ERROR: contrat not managed (mispelled ?)'))
log.error(_('INTERNAL ERROR: contrat not managed (mispelled ?)'))
assert(False)
victory = (score >= point_limit)
@ -318,7 +318,7 @@ class Tarot(object):
scores_str += '\n'
for player in game_data['players']:
scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': player_score[player], 'total_score': players_data[player]['score']}
debug(scores_str)
log.debug(scores_str)
return (scores_str, winners, loosers)
@ -375,7 +375,7 @@ class Tarot(object):
if card.suit == "atout" and card < biggest_atout and biggest_hand_atout > biggest_atout and card.value != "excuse":
forbidden_cards.append(card)
else:
error(_('Internal error: unmanaged game stage'))
log.error(_('Internal error: unmanaged game stage'))
return forbidden_cards
def __start_play(self, room_jid, game_data, profile):
@ -394,7 +394,7 @@ class Tarot(object):
try:
session_data = self._sessions.profileGet(raw_data["session_id"], profile)
except KeyError:
warning(_("session id doesn't exist, session has probably expired"))
log.warning(_("session id doesn't exist, session has probably expired"))
# TODO: send error dialog
return defer.succeed({})
@ -403,7 +403,7 @@ class Tarot(object):
player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
data = xml_tools.XMLUIResult2DataFormResult(raw_data)
contrat = data['contrat']
debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
d.addCallback(lambda ignore: {})
del self._sessions[raw_data["session_id"]]
@ -417,7 +417,7 @@ class Tarot(object):
try:
session_data = self._sessions.profileGet(raw_data["session_id"], profile)
except KeyError:
warning(_("session id doesn't exist, session has probably expired"))
log.warning(_("session id doesn't exist, session has probably expired"))
# TODO: send error dialog
return defer.succeed({})
@ -436,9 +436,9 @@ class Tarot(object):
"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error(_("profile %s is unknown") % profile_key)
log.error(_("profile %s is unknown") % profile_key)
return
debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards})
log.debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards})
elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played')
self.send(jid.JID(referee), elem, {'player': player}, profile=profile)
@ -504,7 +504,7 @@ class Tarot(object):
status = self.games[room_jid.userhost()]['status']
nb_players = len(self.games[room_jid.userhost()]['players'])
status[player] = 'ready'
debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
self.newRound(room_jid, profile)
@ -539,14 +539,14 @@ class Tarot(object):
best_contrat[0] = player
best_contrat[1] = contrat
if best_contrat[1] == "Passe":
debug(_("Everybody is passing, round ended"))
log.debug(_("Everybody is passing, round ended"))
to_jid = jid.JID(room_jid.userhost())
self.send(to_jid, self.__give_scores(*self.__draw_game(game_data)), profile=profile)
game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
for player in game_data['players']:
game_data['status'][player] = "init"
return
debug(_("%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]})
log.debug(_("%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]})
game_data['contrat'] = best_contrat[1]
if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre":
@ -567,7 +567,7 @@ class Tarot(object):
del game_data['chien'][:]
elif elt.name == 'chien': # we have received the chien
debug(_("tarot: chien received"))
log.debug(_("tarot: chien received"))
data = {"attaquant": elt['attaquant']}
game_data['stage'] = "ecart"
game_data['attaquant'] = elt['attaquant']
@ -618,7 +618,7 @@ class Tarot(object):
if all(played):
#everybody has played
winner = self.__winner(game_data)
debug(_('The winner of this trick is %s') % winner)
log.debug(_('The winner of this trick is %s') % winner)
#the winner win the trick
self.__excuse_hack(game_data, played, winner)
players_data[elt['player']]['levees'].extend(played)
@ -664,9 +664,9 @@ class Tarot(object):
invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next())
self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile)
else:
error(_('Unmanaged error type: %s') % elt['type'])
log.error(_('Unmanaged error type: %s') % elt['type'])
else:
error(_('Unmanaged card game element: %s') % elt.name)
log.error(_('Unmanaged card game element: %s') % elt.name)
def getSyncDataForPlayer(self, room_jid_s, nick):
return []

View file

@ -23,7 +23,8 @@ from sat.core.sat_main import MessageSentAndStored
from twisted.words.protocols.jabber import jid
from twisted.internet import defer
from twisted.python.failure import Failure
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
PLUGIN_INFO = {
"name": "Text commands",
@ -43,7 +44,7 @@ class TextCommands(object):
# should be downloadable independently)
def __init__(self, host):
info(_("Text commands initialization"))
log.info(_("Text commands initialization"))
self.host = host
host.trigger.add("sendMessage", self.sendMessageTrigger)
self._commands = {}
@ -59,20 +60,20 @@ class TextCommands(object):
if attr.startswith('cmd_'):
cmd = getattr(instance, attr)
if not callable(cmd):
warning(_("Skipping not callable [%s] attribute") % attr)
log.warning(_("Skipping not callable [%s] attribute") % attr)
continue
cmd_name = attr[4:]
if not cmd_name:
warning(_("Skipping cmd_ method"))
log.warning(_("Skipping cmd_ method"))
if cmd_name in self._commands:
suff=2
while (cmd_name + str(suff)) in self._commands:
suff+=1
new_name = cmd_name + str(suff)
warning(_("Conflict for command [%(old_name)s], renaming it to [%(new_name)s]") % {'old_name': cmd_name, 'new_name': new_name})
log.warning(_("Conflict for command [%(old_name)s], renaming it to [%(new_name)s]") % {'old_name': cmd_name, 'new_name': new_name})
cmd_name = new_name
self._commands[cmd_name] = cmd
info(_("Registered text command [%s]") % cmd_name)
log.info(_("Registered text command [%s]") % cmd_name)
def addWhoIsCb(self, callback, priority=0):
"""Add a callback which give information to the /whois command
@ -160,7 +161,7 @@ class TextCommands(object):
def cmd_whois(self, mess_data, profile):
"""show informations on entity"""
debug("Catched whois command")
log.debug("Catched whois command")
entity = mess_data["unparsed"].strip()
@ -170,7 +171,7 @@ class TextCommands(object):
if self.host.plugins["XEP-0045"].isNickInRoom(room, entity, profile):
entity = u"%s/%s" % (room, entity)
except KeyError:
warning("plugin XEP-0045 is not present")
log.warning("plugin XEP-0045 is not present")
if not entity:
target_jid = mess_data["to"]

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _, D_
from logging import debug, info, error, warning
from sat.core.log import getLogger
log = getLogger(__name__)
from wokkel import disco, pubsub
from twisted.internet import defer
@ -94,7 +95,7 @@ class TextSyntaxes(object):
}
def __init__(self, host):
info(_("Text syntaxes plugin initialization"))
log.info(_("Text syntaxes plugin initialization"))
self.host = host
self.syntaxes = {}
self.addSyntax(self.SYNTAX_XHTML, lambda xhtml: defer.succeed(xhtml), lambda xhtml: defer.succeed(xhtml),
@ -109,7 +110,7 @@ class TextSyntaxes(object):
return h.handle(html)
self.addSyntax(self.SYNTAX_MARKDOWN, markdown.markdown, _html2text, [TextSyntaxes.OPT_DEFAULT])
except ImportError:
warning("markdown or html2text not found, can't use Markdown syntax")
log.warning("markdown or html2text not found, can't use Markdown syntax")
host.bridge.addMethod("syntaxConvert", ".plugin", in_sign='sssbs', out_sign='s',
async=True, method=self.convert)
@ -173,7 +174,7 @@ class TextSyntaxes(object):
elif isinstance(xhtml, html.HtmlElement):
xhtml_elt = xhtml
else:
error("Only strings and HtmlElements can be cleaned")
log.error("Only strings and HtmlElements can be cleaned")
raise exceptions.DataError
cleaner = clean.Cleaner(style=False,
add_nofollow=False,

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from logging import debug, info, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.protocols.jabber.xmlstream import XmlStream
from twisted.words.xish import domish
@ -43,7 +44,7 @@ class LoggingXmlStream(XmlStream):
elif isinstance(obj, domish.Element):
log = obj.toXml()
else:
error(_('INTERNAL ERROR: Unmanaged XML type'))
log.error(_('INTERNAL ERROR: Unmanaged XML type'))
self._host.bridge.xmlLog("OUT", log, self._profile)
return XmlStream.send(self, obj)
@ -65,7 +66,7 @@ class XmlLog(object):
""" % {"label_xmllog": _("Activate XML log")}
def __init__(self, host):
info(_("Plugin XML Log initialization"))
log.info(_("Plugin XML Log initialization"))
self.host = host
#parameters
@ -76,7 +77,7 @@ class XmlLog(object):
do_log = self.host.memory.getParamA("Xml log", "Debug")
if do_log:
info(_("XML log activated"))
log.info(_("XML log activated"))
host.trigger.add("XML Initialized", self.logXml)
def logXml(self, xmlstream, profile):

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _, D_
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.internet import defer
from twisted.words.protocols.jabber.xmlstream import IQ
from twisted.words.protocols.jabber import jid
@ -74,10 +75,10 @@ class DemoDirectory(object):
}
def __init__(self, host):
info(_(u"Plugin demo directory initialization"))
log.info(_(u"Plugin demo directory initialization"))
activate = host.memory.getConfig(CONFIG_SECTION, CONFIG_ACTIVATE) or 'false'
if not activate.lower() in ('true', 'yes', '1'):
info("not activated")
log.info("not activated")
return
service_str = host.memory.getConfig(CONFIG_SECTION, CONFIG_SERVICE) or 'salut.libervia.org'
self.service = jid.JID(service_str)
@ -95,7 +96,7 @@ class DemoDirectory(object):
"""
client = self.host.getClient(profile)
if not subscribe:
info ("Unsubscribing [%s] from directory" % profile)
log.info ("Unsubscribing [%s] from directory" % profile)
unsub_req = IQ(client.xmlstream, 'set')
unsub_req['from'] = client.jid.full()
unsub_req['to'] = self.service.userhost()
@ -104,7 +105,7 @@ class DemoDirectory(object):
command_elt['action'] = 'execute'
yield unsub_req.send(self.service.userhost())
else:
info ("Subscribing [%s] to directory" % profile)
log.info ("Subscribing [%s] to directory" % profile)
sub_req = IQ(client.xmlstream, 'set')
sub_req['from'] = client.jid.full()
sub_req['to'] = self.service.userhost()

View file

@ -18,7 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from twisted.words.protocols.jabber import client, jid
from twisted.words.xish import domish
@ -47,7 +48,7 @@ PLUGIN_INFO = {
class XEP_0020(object):
def __init__(self, host):
info(_("Plugin XEP_0020 initialization"))
log.info(_("Plugin XEP_0020 initialization"))
def getHandler(self, profile):
return XEP_0020_handler()
@ -68,7 +69,7 @@ class XEP_0020(object):
values = form.fields[field].values
result[field] = values[0] if values else None
if len(values) > 1:
warning(_("More than one value choosed for %s, keeping the first one") % field)
log.warning(_("More than one value choosed for %s, keeping the first one") % field)
return result
def negociate(self, feature_elt, form_type, negociable_values):

View file

@ -18,8 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
import logging
from sat.core import exceptions
from sat.core.log import getLogger
log = getLogger(__name__)
from wokkel import disco, iwokkel
from zope.interface import implements
from twisted.words.protocols.jabber.jid import JID
@ -29,9 +29,8 @@ try:
from twisted.words.protocols.xmlstream import XMPPHandler
except ImportError:
from wokkel.subprotocols import XMPPHandler
from threading import Timer
from twisted.words.xish import domish
from twisted.internet import defer, threads
from twisted.internet import defer
from sat.core.sat_main import MessageSentAndStored, AbortSendMessage
from sat.tools.misc import TriggerManager
@ -70,7 +69,7 @@ class XEP_0033(object):
Implementation for XEP 0033
"""
def __init__(self, host):
logging.info(_("Extended Stanza Addressing plugin initialization"))
log.info(_("Extended Stanza Addressing plugin initialization"))
self.host = host
self.internal_data = {}
host.trigger.add("sendMessage", self.sendMessageTrigger, TriggerManager.MIN_PRIORITY)
@ -87,8 +86,8 @@ class XEP_0033(object):
if entity is None:
return Failure(AbortSendMessage(_("XEP-0033 is being used but the server doesn't support it!")))
if mess_data["to"] != entity:
logging.warning(_("Stanzas using XEP-0033 should be addressed to %(expected)s, not %(current)s!") % {'expected': entity, 'current': mess_data["to"]})
logging.warning(_("TODO: addressing has be fixed by the backend... fix it in the frontend!"))
log.warning(_("Stanzas using XEP-0033 should be addressed to %(expected)s, not %(current)s!") % {'expected': entity, 'current': mess_data["to"]})
log.warning(_("TODO: addressing has be fixed by the backend... fix it in the frontend!"))
mess_data["to"] = entity
element = mess_data['xml'].addElement('addresses', NS_ADDRESS)
entries = [entry.split(':') for entry in mess_data['extra']['address'].split('\n') if entry != '']

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