Commit 0eb75eb7 authored by Philipp Hörist's avatar Philipp Hörist

Modules: Use LogAdapter

- Make all modules inherit from BaseModule
- Use LogAdapter in BaseModule
parent 6e672c99
......@@ -19,18 +19,15 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
import logging
import nbxmpp
from nbxmpp.structs import StanzaHandler
from gajim.common import app
from gajim.common import helpers
from gajim.common.i18n import _
from gajim.common.modules import dataforms
from gajim.common.nec import NetworkIncomingEvent
log = logging.getLogger('gajim.c.m.commands')
from gajim.common.modules import dataforms
from gajim.common.modules.base import BaseModule
class AdHocCommand:
......@@ -298,13 +295,15 @@ class LeaveGroupchatsCommand(AdHocCommand):
return False
class AdHocCommands:
class AdHocCommands(BaseModule):
def __init__(self, con):
self._con = con
self._account = con.name
BaseModule.__init__(self, con)
self.handlers = [
('iq', self._execute_command_received, 'set', nbxmpp.NS_COMMANDS)
StanzaHandler(name='iq',
callback=self._execute_command_received,
typ='set',
ns=nbxmpp.NS_COMMANDS),
]
# a list of all commands exposed: node -> command class
......@@ -350,7 +349,7 @@ class AdHocCommands:
try:
jid = helpers.get_full_jid_from_iq(stanza)
except helpers.InvalidFormat:
log.warning('Invalid JID: %s, ignoring it', stanza.getFrom())
self._log.warning('Invalid JID: %s, ignoring it', stanza.getFrom())
return
node = stanza.getTagAttr('query', 'node')
......@@ -393,17 +392,17 @@ class AdHocCommands:
return False
def _execute_command_received(self, _con, stanza):
def _execute_command_received(self, _con, stanza, _properties):
jid = helpers.get_full_jid_from_iq(stanza)
cmd = stanza.getTag('command')
if cmd is None:
log.error('Malformed stanza (no command node) %s', stanza)
self._log.error('Malformed stanza (no command node) %s', stanza)
raise nbxmpp.NodeProcessed
node = cmd.getAttr('node')
if node is None:
log.error('Malformed stanza (no node attr) %s', stanza)
self._log.error('Malformed stanza (no node attr) %s', stanza)
raise nbxmpp.NodeProcessed
sessionid = cmd.getAttr('sessionid')
......@@ -414,12 +413,12 @@ class AdHocCommands:
self._con.connection.send(
nbxmpp.Error(
stanza, nbxmpp.NS_STANZAS + ' item-not-found'))
log.warning('Comand %s does not exist: %s', node, jid)
self._log.warning('Comand %s does not exist: %s', node, jid)
raise nbxmpp.NodeProcessed
newcmd = self._commands[node]
if not newcmd.is_visible_for(self.is_same_jid(jid)):
log.warning('Command not visible for jid: %s', jid)
self._log.warning('Command not visible for jid: %s', jid)
raise nbxmpp.NodeProcessed
# generate new sessionid
......@@ -430,14 +429,14 @@ class AdHocCommands:
rc = obj.execute(stanza)
if rc:
self._sessions[(jid, sessionid, node)] = obj
log.info('Comand %s executed: %s', node, jid)
self._log.info('Comand %s executed: %s', node, jid)
raise nbxmpp.NodeProcessed
else:
# the command is already running, check for it
magictuple = (jid, sessionid, node)
if magictuple not in self._sessions:
# we don't have this session... ha!
log.warning('Invalid session %s', magictuple)
self._log.warning('Invalid session %s', magictuple)
raise nbxmpp.NodeProcessed
action = cmd.getAttr('action')
......@@ -461,7 +460,7 @@ class AdHocCommands:
# the command probably doesn't handle invoked action...
# stop the session, return error
del self._sessions[magictuple]
log.warning('Wrong action %s %s', node, jid)
self._log.warning('Wrong action %s %s', node, jid)
raise nbxmpp.NodeProcessed
# delete the session if rc is False
......@@ -474,7 +473,7 @@ class AdHocCommands:
"""
Request the command list.
"""
log.info('Request Command List: %s', jid)
self._log.info('Request Command List: %s', jid)
query = nbxmpp.Iq(typ='get', to=jid, queryNS=nbxmpp.NS_DISCO_ITEMS)
query.setQuerynode(nbxmpp.NS_COMMANDS)
......@@ -483,7 +482,7 @@ class AdHocCommands:
def _command_list_received(self, stanza):
if not nbxmpp.isResultNode(stanza):
log.info('Error: %s', stanza.getError())
self._log.info('Error: %s', stanza.getError())
app.nec.push_incoming_event(
AdHocCommandError(None, conn=self._con,
......@@ -497,7 +496,7 @@ class AdHocCommands:
(t.getAttr('node'), t.getAttr('name')) for t in items
]
log.info('Received: %s', commandlist)
self._log.info('Received: %s', commandlist)
app.nec.push_incoming_event(
AdHocCommandListReceived(
None, conn=self._con, commandlist=commandlist))
......@@ -507,7 +506,7 @@ class AdHocCommands:
"""
Send the command with data form. Wait for reply
"""
log.info('Send Command: %s %s %s %s', jid, node, session_id, action)
self._log.info('Send Command: %s %s %s %s', jid, node, session_id, action)
stanza = nbxmpp.Iq(typ='set', to=jid)
cmdnode = stanza.addChild('command',
namespace=nbxmpp.NS_COMMANDS,
......@@ -525,13 +524,13 @@ class AdHocCommands:
def _action_response_received(self, stanza):
if not nbxmpp.isResultNode(stanza):
log.info('Error: %s', stanza.getError())
self._log.info('Error: %s', stanza.getError())
app.nec.push_incoming_event(
AdHocCommandError(None, conn=self._con,
error=stanza.getError()))
return
log.info('Received action response')
self._log.info('Received action response')
command = stanza.getTag('command')
app.nec.push_incoming_event(
AdHocCommandActionResponse(
......@@ -541,7 +540,7 @@ class AdHocCommands:
"""
Send the command with action='cancel'
"""
log.info('Cancel: %s %s %s', jid, node, session_id)
self._log.info('Cancel: %s %s %s', jid, node, session_id)
stanza = nbxmpp.Iq(typ='set', to=jid)
stanza.addChild('command', namespace=nbxmpp.NS_COMMANDS,
attrs={
......@@ -553,12 +552,11 @@ class AdHocCommands:
self._con.connection.SendAndCallForResponse(
stanza, self._cancel_result_received)
@staticmethod
def _cancel_result_received(stanza):
def _cancel_result_received(self, stanza):
if not nbxmpp.isResultNode(stanza):
log.warning('Error: %s', stanza.getError())
self._log.warning('Error: %s', stanza.getError())
else:
log.info('Cancel successful')
self._log.info('Cancel successful')
class AdHocCommandError(NetworkIncomingEvent):
......
......@@ -18,15 +18,11 @@ from typing import Any
from typing import Dict # pylint: disable=unused-import
from typing import Tuple
import logging
from nbxmpp.util import is_error_result
from gajim.common.types import ConnectionT
from gajim.common.modules.base import BaseModule
log = logging.getLogger('gajim.c.m.annotations')
class Annotations(BaseModule):
......
......@@ -26,29 +26,33 @@ from nbxmpp.structs import StanzaHandler
from gajim.common import app
from gajim.common.modules.util import LogAdapter
log = logging.getLogger('gajim.c.m.base')
class BaseModule:
_nbxmpp_extends = ''
_nbxmpp_methods = [] # type: List[str]
def __init__(self, con, logger=None):
def __init__(self, con, *args, plugin=False, **kwargs):
self._con = con
self._account = con.name
if logger is not None:
self._log = LogAdapter(logger, {'account': self._account})
self._log = self._set_logger(plugin)
self._nbxmpp_callbacks = {} # type: Dict[str, Any]
self._stored_publish = None # type: Callable
self.handlers = [] # type: List[str]
def _set_logger(self, plugin):
logger_name = 'gajim.c.m.%s'
if plugin:
logger_name = 'gajim.p.%s'
logger_name = logger_name % self.__class__.__name__.lower()
logger = logging.getLogger(logger_name)
return LogAdapter(logger, {'account': self._account})
def __getattr__(self, key):
if key not in self._nbxmpp_methods:
raise AttributeError
if not app.account_is_connected(self._account):
log.warning('Account %s not connected, cant use %s',
self._account, key)
self._log.warning('Account not connected, cant use %s', key)
return
module = self._con.connection.get_module(self._nbxmpp_extends)
......@@ -60,8 +64,7 @@ class BaseModule:
def _nbxmpp(self, module_name=None):
if not app.account_is_connected(self._account):
log.warning('Account %s not connected, cant use nbxmpp method',
self._account)
self._log.warning('Account not connected, cant use nbxmpp method')
return Mock()
if module_name is None:
......@@ -81,5 +84,5 @@ class BaseModule:
def send_stored_publish(self):
if self._stored_publish is None:
return
log.info('Send stored publish')
self._log.info('Send stored publish')
self._stored_publish()
......@@ -20,31 +20,35 @@ from base64 import b64decode
from pathlib import Path
import nbxmpp
from nbxmpp.structs import StanzaHandler
from gajim.common import app
from gajim.common import configpaths
from gajim.common.modules.base import BaseModule
log = logging.getLogger('gajim.c.m.bob')
class BitsOfBinary:
class BitsOfBinary(BaseModule):
def __init__(self, con):
self._con = con
self._account = con.name
BaseModule.__init__(self, con)
self.handlers = [
('iq', self._answer_bob_request, 'get', nbxmpp.NS_BOB)
StanzaHandler(name='iq',
callback=self._answer_bob_request,
typ='get',
ns=nbxmpp.NS_BOB),
]
# Used to track which cids are in-flight.
self.awaiting_cids = {}
def _answer_bob_request(self, _con, stanza):
log.info('Request from %s for BoB data', stanza.getFrom())
def _answer_bob_request(self, _con, stanza, _properties):
self._log.info('Request from %s for BoB data', stanza.getFrom())
iq = stanza.buildReply('error')
err = nbxmpp.ErrorNode(nbxmpp.ERR_ITEM_NOT_FOUND)
iq.addChild(node=err)
log.info('Sending item-not-found')
self._log.info('Sending item-not-found')
self._con.connection.send(iq)
raise nbxmpp.NodeProcessed
......
......@@ -14,9 +14,8 @@
# XEP-0191: Blocking Command
import logging
import nbxmpp
from nbxmpp.structs import StanzaHandler
from nbxmpp.util import is_error_result
from gajim.common import app
......@@ -24,8 +23,6 @@ from gajim.common.nec import NetworkEvent
from gajim.common.nec import NetworkIncomingEvent
from gajim.common.modules.base import BaseModule
log = logging.getLogger('gajim.c.m.blocking')
class Blocking(BaseModule):
......@@ -42,7 +39,10 @@ class Blocking(BaseModule):
self.blocked = []
self.handlers = [
('iq', self._blocking_push_received, 'set', nbxmpp.NS_BLOCKING)
StanzaHandler(name='iq',
callback=self._blocking_push_received,
typ='set',
ns=nbxmpp.NS_BLOCKING),
]
self._register_callback('get_blocking_list',
......@@ -60,18 +60,18 @@ class Blocking(BaseModule):
account=self._account,
feature=nbxmpp.NS_BLOCKING))
log.info('Discovered blocking: %s', from_)
self._log.info('Discovered blocking: %s', from_)
def _blocking_list_received(self, result):
if is_error_result(result):
log.info('Error: %s', result)
self._log.info('Error: %s', result)
return
self.blocked = result.blocking_list
app.nec.push_incoming_event(
BlockingEvent(None, conn=self._con, changed=self.blocked))
def _blocking_push_received(self, _con, stanza):
def _blocking_push_received(self, _con, stanza, _properties):
reply = stanza.buildReply('result')
childs = reply.getChildren()
for child in childs:
......@@ -89,7 +89,7 @@ class Blocking(BaseModule):
self.blocked = []
for jid in self.blocked:
self._presence_probe(jid)
log.info('Unblock all Push')
self._log.info('Unblock all Push')
raise nbxmpp.NodeProcessed
for item in items:
......@@ -100,7 +100,7 @@ class Blocking(BaseModule):
continue
self.blocked.remove(jid)
self._presence_probe(jid)
log.info('Unblock Push: %s', jid)
self._log.info('Unblock Push: %s', jid)
block = stanza.getTag('block', namespace=nbxmpp.NS_BLOCKING)
if block is not None:
......@@ -111,7 +111,7 @@ class Blocking(BaseModule):
changed_list.append(jid)
self.blocked.append(jid)
self._set_contact_offline(jid)
log.info('Block Push: %s', jid)
self._log.info('Block Push: %s', jid)
app.nec.push_incoming_event(
BlockingEvent(None, conn=self._con, changed=changed_list))
......@@ -124,7 +124,7 @@ class Blocking(BaseModule):
contact.show = 'offline'
def _presence_probe(self, jid: str) -> None:
log.info('Presence probe: %s', jid)
self._log.info('Presence probe: %s', jid)
# Send a presence Probe to get the current Status
probe = nbxmpp.Presence(jid, 'probe', frm=self._con.get_own_jid())
self._nbxmpp().send(probe)
......
......@@ -18,7 +18,6 @@ from typing import Any
from typing import List
from typing import Optional
import logging
import copy
import nbxmpp
......@@ -33,9 +32,6 @@ from gajim.common.modules.base import BaseModule
from gajim.common.modules.util import event_node
log = logging.getLogger('gajim.c.m.bookmarks')
class Bookmarks(BaseModule):
_nbxmpp_extends = 'Bookmarks'
......@@ -69,14 +65,15 @@ class Bookmarks(BaseModule):
bookmarks = properties.pubsub_event.data
if not properties.is_self_message:
log.warning('%s has an open access bookmarks node', properties.jid)
self._log.warning('%s has an open access bookmarks node',
properties.jid)
return
if not self._pubsub_support() or not self.conversion:
return
if self._request_in_progress:
log.info('Ignore update, pubsub request in progress')
self._log.info('Ignore update, pubsub request in progress')
return
old_bookmarks = self._convert_to_set(self._bookmarks)
......@@ -89,7 +86,7 @@ class Bookmarks(BaseModule):
if nbxmpp.NS_BOOKMARK_CONVERSION not in features:
return
self._conversion = True
log.info('Discovered Bookmarks Conversion: %s', from_)
self._log.info('Discovered Bookmarks Conversion: %s', from_)
def _act_on_changed_bookmarks(self, old_bookmarks):
new_bookmarks = self._convert_to_set(self._bookmarks)
......@@ -100,7 +97,7 @@ class Bookmarks(BaseModule):
join = [jid for jid, autojoin in changed if autojoin]
bookmarks = []
for jid in join:
log.info('Schedule autojoin in 10s for: %s', jid)
self._log.info('Schedule autojoin in 10s for: %s', jid)
bookmarks.append(self.get_bookmark_from_jid(jid))
# If another client creates a MUC, the MUC is locked until the
# configuration is finished. Give the user some time to finish
......@@ -163,7 +160,7 @@ class Bookmarks(BaseModule):
def _bookmarks_received(self, bookmarks):
if is_error_result(bookmarks):
log.info('Error: %s', bookmarks)
self._log.info('Error: %s', bookmarks)
bookmarks = []
self._request_in_progress = False
......@@ -202,7 +199,7 @@ class Bookmarks(BaseModule):
# auto-joined on re-connection
if bookmark.jid not in app.gc_connected[self._account]:
# we are not already connected
log.info('Autojoin Bookmark: %s', bookmark.jid)
self._log.info('Autojoin Bookmark: %s', bookmark.jid)
minimize = app.config.get_per('rooms', bookmark.jid,
'minimize_on_autojoin', True)
app.interface.join_gc_room(
......@@ -237,8 +234,8 @@ class Bookmarks(BaseModule):
return self.get_bookmark_from_jid(jid) is not None
def purge_pubsub_bookmarks(self) -> None:
log.info('Purge/Delete Bookmarks on PubSub, '
'because publish options are not available')
self._log.info('Purge/Delete Bookmarks on PubSub, '
'because publish options are not available')
self._con.get_module('PubSub').send_pb_purge('', 'storage:bookmarks')
self._con.get_module('PubSub').send_pb_delete('', 'storage:bookmarks')
......
......@@ -17,22 +17,18 @@
# XEP-0115: Entity Capabilities
import logging
import nbxmpp
from nbxmpp.structs import StanzaHandler
from gajim.common import caps_cache
from gajim.common import app
from gajim.common.nec import NetworkEvent
log = logging.getLogger('gajim.c.m.caps')
from gajim.common.modules.base import BaseModule
class Caps:
class Caps(BaseModule):
def __init__(self, con):
self._con = con
self._account = con.name
BaseModule.__init__(self, con)
self.handlers = [
StanzaHandler(name='presence',
......@@ -57,8 +53,9 @@ class Caps:
node = properties.entity_caps.node
caps_hash = properties.entity_caps.ver
log.info('Received from %s, type: %s, method: %s, node: %s, hash: %s',
jid, properties.type, hash_method, node, caps_hash)
self._log.info(
'Received from %s, type: %s, method: %s, node: %s, hash: %s',
jid, properties.type, hash_method, node, caps_hash)
client_caps = self._create_suitable_client_caps(
node, caps_hash, hash_method, jid)
......@@ -85,7 +82,7 @@ class Caps:
if contact is not None:
contact.client_caps = client_caps
else:
log.info('Received Caps from unknown contact %s', from_)
self._log.info('Received Caps from unknown contact %s', from_)
def _get_contact_or_gc_contact_for_jid(self, from_):
contact = app.contacts.get_contact_from_full_jid(self._account,
......@@ -106,7 +103,7 @@ class Caps:
contact = self._get_contact_or_gc_contact_for_jid(from_)
if not contact:
log.info('Received Disco from unknown contact %s', from_)
self._log.info('Received Disco from unknown contact %s', from_)
return
lookup = contact.client_caps.get_cache_lookup_strategy()
......@@ -126,7 +123,7 @@ class Caps:
node = caps_hash = hash_method = None
contact.client_caps = self._create_suitable_client_caps(
node, caps_hash, hash_method)
log.warning(
self._log.warning(
'Computed and retrieved caps hash differ. Ignoring '
'caps of contact %s', contact.get_full_jid())
......
......@@ -14,21 +14,15 @@
# XEP-0280: Message Carbons
import logging
import nbxmpp
from gajim.common import app
log = logging.getLogger('gajim.c.m.carbons')
from gajim.common.modules.base import BaseModule
class Carbons:
class Carbons(BaseModule):
def __init__(self, con):
self._con = con
self._account = con.name
self.handlers = []
BaseModule.__init__(self, con)
self.supported = False
......@@ -37,16 +31,16 @@ class Carbons:
return
self.supported = True
log.info('Discovered carbons: %s', from_)
self._log.info('Discovered carbons: %s', from_)
if app.config.get_per('accounts', self._account,
'enable_message_carbons'):
iq = nbxmpp.Iq('set')
iq.setTag('enable', namespace=nbxmpp.NS_CARBONS)
log.info('Activate')
self._log.info('Activate')
self._con.connection.send(iq)
else:
log.warning('Carbons deactivated (user setting)')
self._log.warning('Carbons deactivated (user setting)')
def get_instance(*args, **kwargs):
......
......@@ -21,23 +21,23 @@ from typing import Optional
from typing import Tuple
import time
import logging
from functools import wraps
import nbxmpp
from nbxmpp.structs import StanzaHandler
from gi.repository import GLib
from gajim.common import app
from gajim.common.nec import NetworkEvent
from gajim.common.const import Chatstate as State
from gajim.common.modules.misc import parse_delay
from gajim.common.modules.base import BaseModule
from gajim.common.connection_handlers_events import MessageOutgoingEvent
from gajim.common.connection_handlers_events import GcMessageOutgoingEvent
from gajim.common.types import ContactT
from gajim.common.types import ConnectionT
log = logging.getLogger('gajim.c.m.chatstates')
INACTIVE_AFTER = 60
PAUSED_AFTER = 10
......@@ -63,13 +63,13 @@ def parse_chatstate(stanza: nbxmpp.Message) -> Optional[str]:
return None
class Chatstate:
class Chatstate(BaseModule):
def __init__(self, con: ConnectionT) -> None:
self._con = con
self._account = con.name
BaseModule.__init__(self, con)
self.handlers = [
('presence', self._presence_received),
StanzaHandler(name='presence',
callback=self._presence_received),
]
# Our current chatstate with a specific contact
......@@ -90,7 +90,7 @@ class Chatstate:
def enabled(self, value):
if self._enabled == value:
return
log.info('Chatstate module %s', 'enabled' if value else 'disabled')
self._log.info('Chatstate module %s', 'enabled' if value else 'disabled')
self._enabled = value
if value:
......@@ -106,7 +106,8 @@ class Chatstate:
@ensure_enabled
def _presence_received(self,
_con: ConnectionT,
stanza: nbxmpp.Presence) -> None:
stanza: nbxmpp.Presence,
_properties: Any) -> None:
if stanza.getType() not in ('unavailable', 'error'):
return
......@@ -136,7 +137,7 @@ class Chatstate:
self._last_mouse_activity.pop(jid, None)
self._last_keyboard_activity.pop(jid, None)
log.info('Reset chatstate for %s', jid)
self._log.info('Reset chatstate for %s', jid)
app.nec.push_outgoing_event(
NetworkEvent('chatstate-received',
......@@ -166,7 +167,7 @@ class Chatstate:
return
contact.chatstate = chatstate
log.info('Recv: %-10s - %s', chatstate, event.fjid)
self._log.info('Recv: %-10s - %s', chatstate, event.fjid)
app.nec.push_outgoing_event(
NetworkEvent('chatstate-received',
account=self._account,
......@@ -207,7 +208,7 @@ class Chatstate:
else:
# Contact not found, maybe we left the group chat
# or the contact was removed from the roster
log.info(
self._log.info(
'Contact %s not found, reset chatstate', jid)
self._chatstates.pop(jid, None)
self._last_mouse_activity.pop(jid, None)
......@@ -275,9 +276,9 @@ class Chatstate:
if setting == 'disabled':
# Send a last 'active' state after user disabled chatstates
if current_state is not None:
log.info('Disabled for %s', contact.jid)
log.info('Send last state: %-10s - %s',
State.ACTIVE, contact.jid)
self._log.info('Disabled for %s', contact.jid)
self._log.info('Send last state: %-10s - %s',
State.ACTIVE, contact.jid)
event_attrs = {'account': self._account,
'jid': contact.jid,
......@@ -301,15 +302,15 @@ class Chatstate:
# which are not allowed to see our status
if not contact.is_pm_contact:
if contact and contact.sub in ('to', 'none'):
log.info('Contact not subscribed: %s', contact.jid)
self._log.info('Contact not subscribed: %s', contact.jid)
return
if contact.show == 'offline':
log.info('Contact offline: %s', contact.jid)
self._log.info('Contact offline: %s', contact.jid)
return
if not contact.supports(nbxmpp.NS_CHATSTATES):
log.info('Chatstates not supported: %s', contact.jid)
self._log.info('Chatstates not supported: %s', contact.jid)
return
if state in (State.ACTIVE, State.COMPOSING):
......@@ -322,7 +323,7 @@ class Chatstate:
if current_state == state:
return
log.info('Send: %-10s - %s', state, contact.jid)
self._log.info('Send: %-10s - %s', state, contact.jid)
event_attrs = {'account': self._account,
'jid': contact.jid,
......
......@@ -14,25 +14,19 @@
# XEP-0083: Nested Roster Groups