diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..3f2acb3 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,2 @@ +[run] +source_pkgs = transWhat diff --git a/setup.py b/setup.py index e406a87..ccd3b3b 100755 --- a/setup.py +++ b/setup.py @@ -35,7 +35,6 @@ def read_file(filename, encoding="utf8"): packages=["transWhat"], scripts=["transWhat/transwhat.py"], install_requires=[ - "protobuf", "yowsup", "pyspectrum2", "python-dateutil", diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e188cbe --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,99 @@ +import pytest +from asyncio import Transport +from spectrum2 import Backend +from transWhat.session import Session +from unittest.mock import create_autospec +from yowsup.stacks import YowStack +from collections import deque +from transWhat.yowsupwrapper import YowsupAppLayer + + +class MockYowstack: + def __init__(self): + self.events = deque() + self.props = {} + + def setProp(self, key, value): + self.props[key] = value + + def broadcastEvent(self, event): + self.events.append(event) + + def assert_event_called(self, event_name, **kwargs): + for event in self.events: + if event.name != event_name: + continue + + if event.args != kwargs: + continue + + return + + raise AssertionError( + f"event name={event_name}, args={kwargs} not found in {self.events}" + ) + + def assert_entity_called(self, entity): + _qualname = type(entity).__qualname__ + + for event in self.events: + if event.name != YowsupAppLayer.TO_LOWER_EVENT: + continue + + got_entity = event.args["entity"] + + is_equal = all( + ( + _qualname == type(got_entity).__qualname__, + got_entity.__dict__ == entity.__dict__, + ) + ) + + if is_equal: + return + + raise AssertionError(f"entity {entity} not found in {self.events}") + + def assert_iq_called(self, iq_type, success=None, failure=None): + _qualname = iq_type.__qualname__ + + for event in self.events: + if event.name != YowsupAppLayer.SEND_IQ: + continue + + iq = event.args["iq"] + + if type(iq).__qualname__ != _qualname: + continue + + if event.args["success"] != success: + continue + + if event.args["failure"] != failure: + continue + + return + + raise AssertionError( + f"iq type={iq_type} success={success} error={error} not found in {self.events}" + ) + + +@pytest.fixture +def mock_transport() -> Transport: + yield create_autospec(Transport) + + +@pytest.fixture +def mock_session() -> Session: + yield create_autospec(Session) + + +@pytest.fixture +def mock_backend() -> Backend: + yield create_autospec(Backend) + + +@pytest.fixture +def mock_yowstack(): + return MockYowstack() diff --git a/tests/spectrum2_utils.py b/tests/spectrum2_utils.py new file mode 100644 index 0000000..15dbb59 --- /dev/null +++ b/tests/spectrum2_utils.py @@ -0,0 +1,21 @@ +from faker import Faker +from spectrum2.protocol_pb2 import ( + Buddy, Buddies +) + + +def generate_buddy(faker: Faker) -> Buddy: + """ + Generate a fake buddy. + """ + return Buddy( + userName=faker.user_name(), + buddyName=faker.user_name(), + + ) + +def generate_buddies(faker: Faker, count: int = 10) -> Buddies: + """ + Generate fake buddies + """ + return Buddies(buddy=[generate_buddy(faker) for _ in range(count)]) \ No newline at end of file diff --git a/tests/test_deferred.py b/tests/test_deferred.py new file mode 100644 index 0000000..6ce7c2a --- /dev/null +++ b/tests/test_deferred.py @@ -0,0 +1,51 @@ +from pytest import raises +from unittest.mock import Mock +from transWhat.deferred import Deferred, DeferredHasValue, call + + +def test_deferred_argument_forwarding_works(): + test_cases = [[], [1], [1, 2], [1, 2, 3]] + + for test_case in test_cases: + cb = Mock() + + fut = Deferred() + fut.then(cb) + + fut.run(*test_case) + + cb.assert_called_with(*test_case) + + +def test_deferred_pipelining_works(): + cb = Mock() + + fut = Deferred() + fut.append(2) + fut.then(cb) + fut.run([1]) + + cb.assert_called_with([1, 2]) + + +def test_deferred_raises_when_running_twice(): + cb = Mock() + + fut = Deferred() + fut.then(cb) + fut.run() + + with raises(DeferredHasValue): + fut.run() + + +def test_call_appends_arguments(): + cb = Mock() + + fut = Deferred() + fut.extend((1, 2)) + fut.run([]) + + call(cb, fut) + + cb.assert_called_with([1, 2]) diff --git a/tests/test_session.py b/tests/test_session.py new file mode 100644 index 0000000..ebf7ac8 --- /dev/null +++ b/tests/test_session.py @@ -0,0 +1,149 @@ +import pytest + +from unittest.mock import patch, Mock, create_autospec +from transWhat.session import Session +from typing import Optional +from yowsup.structs import ProtocolEntity +from yowsup.stacks import YowStack +from yowsup.layers import YowLayerEvent +from yowsup.layers.network import YowNetworkLayer +from yowsup.layers.protocol_privacy.protocolentities.privacylist_iq import ( + PrivacyListIqProtocolEntity, +) +from yowsup.layers.protocol_iq.protocolentities.iq_push import PushIqProtocolEntity +from yowsup.layers.protocol_iq.protocolentities.iq_props import PropsIqProtocolEntity +from transWhat.yowsupwrapper import YowsupAppLayer +from contextlib import contextmanager +from yowsup.layers.protocol_presence.protocolentities import ( + AvailablePresenceProtocolEntity, + UnavailablePresenceProtocolEntity, +) + +from yowsup.layers.protocol_media.protocolentities import ( + MediaMessageProtocolEntity, + DownloadableMediaMessageProtocolEntity, + ImageDownloadableMediaMessageProtocolEntity, +) + + +@pytest.fixture +def session_instance(mock_backend, mock_yowstack): + mock_user = "mock@user.com" + mock_legacy_name = "legacy name" + + sess = Session( + backend=mock_backend, user=mock_user, legacyName=mock_legacy_name, extra=[] + ) + sess.stack = mock_yowstack + + yield sess + + +def test_login_works(session_instance, mock_yowstack): + password = "test password" + + session_instance.login(password) + assert session_instance.password == password + mock_yowstack.assert_event_called(YowNetworkLayer.EVENT_STATE_CONNECT) + + +def test_logout_works(session_instance, mock_yowstack): + session_instance.loggedIn = True + + session_instance.logout() + assert not session_instance.loggedIn + + mock_yowstack.assert_event_called(YowNetworkLayer.EVENT_STATE_DISCONNECT) + + +def test_send_message_to_xmpp_queued(session_instance, mock_backend): + session_instance.initialized = False + + session_instance.sendMessageToXMPP( + buddy="test@jid.com", + message="this is a random message", + timestamp=1, + ) + + assert not mock_backend.handle_message.called + + +def test_send_message_to_xmpp_proper(session_instance, mock_backend): + session_instance.initialized = True + + session_instance.sendMessageToXMPP( + buddy="test@jid.com", message="this is a random message", timestamp=1 + ) + + mock_backend.handle_message.assert_called_with( + "mock@user.com", + "test@jid.com", + "this is a random message", + "", # why + "", # why + "19700101T000001", + ) + + +@pytest.mark.skip("updateRoomList and _updateGroups are broken and do not work") +def test_update_room_list(session_instance): + raise NotImplementedError() + + +@pytest.mark.skip("joinRoom depends on updateRoomList which does not work yet") +def test_join_room(session_instance): + raise NotImplementedError() + + +@pytest.mark.skip("leaveRoom depends on updateRoomList which does not work yet") +def test_leave_room(session_instance): + raise NotImplementedError() + + +def test_callback_on_auth_success(session_instance, mock_backend, mock_yowstack): + session_instance.onAuthSuccess("success", 123, 1, 1, 1, 1, 1) + + assert session_instance.initialized + assert session_instance.loggedIn + + # Interaction with backend works + mock_backend.handle_connected.assert_called_with(session_instance.user) + mock_backend.handle_buddy_changed.assert_called() + + # Interaction with Yowsup, these are called in subfunctions + # TODO: check for toLower call + mock_yowstack.assert_iq_called(PushIqProtocolEntity) + mock_yowstack.assert_iq_called(PrivacyListIqProtocolEntity) + mock_yowstack.assert_iq_called(PropsIqProtocolEntity) + + # .. and presence is true now + mock_yowstack.assert_entity_called(AvailablePresenceProtocolEntity()) + + +def test_callback_on_auth_failed(session_instance, mock_backend): + session_instance.onAuthFailed("reason") + + mock_backend.handle_disconnected.assert_called() + + assert not session_instance.loggedIn + assert session_instance.password is None + + +def test_callback_on_disconnect(session_instance, mock_backend): + session_instance.onDisconnect() + + mock_backend.handle_disconnected.assert_called() + + +def test_callback_on_media_works_with_images(session_instance, mock_backend): + media_inst = create_autospec(DownloadableMediaMessageProtocolEntity) + + media_inst.media_type = MediaMessageProtocolEntity.TYPE_MEDIA_IMAGE + media_inst.url = "http://test.com/a-picture" + media_inst.caption = "my first image" + media_inst.participant = None + media_inst.getFrom.return_value = "buddy" + media_inst.getTimestamp.return_value = 1 + # media_inst.isEncrypted.return_value = False + + session_instance.onMedia(media_inst, "image") diff --git a/tests/test_threadutils.py b/tests/test_threadutils.py new file mode 100644 index 0000000..709c90d --- /dev/null +++ b/tests/test_threadutils.py @@ -0,0 +1,16 @@ +from unittest.mock import Mock +from transWhat.threadutils import eventQueue, runInThread + + +def test_runInThread(): + magic = object() + + def thread_func(): + return magic + + def callback(result): + return result == magic + + runInThread(thread_func, callback) + result = eventQueue.get(timeout=1.0) + assert result diff --git a/tests/test_whatsappbackend.py b/tests/test_whatsappbackend.py new file mode 100644 index 0000000..6e9db59 --- /dev/null +++ b/tests/test_whatsappbackend.py @@ -0,0 +1,99 @@ +import pytest +from spectrum2 import Backend +from transWhat.session import Session +from transWhat.whatsappbackend import WhatsAppBackend +from unittest.mock import Mock, create_autospec, patch +from spectrum2_utils import generate_buddies + + +@patch("transWhat.whatsappbackend.Session") +def test_login_logout_work(mock_session_cls, mock_backend, mock_session): + jid = "magic@jid.com" + + user_name = "user@jid.com" + password = "password" + legacy_name = "0000" + extra = [] + + backend = WhatsAppBackend(mock_backend, user_name, {}) + + # Login + backend.handle_login_request(user_name, legacy_name, password, extra) + mock_session = mock_session_cls(backend, user_name, legacy_name, extra) + assert user_name in backend.sessions + mock_session.login.assert_called_with(password) + + # Logout + backend.handle_logout_request(user_name, legacy_name) + mock_session.logout.assert_called() + + +def test_handle_message_send_request(mock_backend, mock_session): + user_name = "user@jid.com" + + mock_user = "mock@jid.com" + mock_sender = "sender@jid.com" + mock_message = "my message" + mock_id = "id" + + backend = WhatsAppBackend(mock_backend, user_name, {}) + backend.sessions[user_name] = mock_session + + backend.handle_message_send_request(user_name, mock_sender, mock_message, mock_id) + mock_session.sendMessageToWA.assert_called_with( + mock_sender, mock_message, "", mock_id + ) + + +def test_handle_join_and_leave_room(mock_backend, mock_session): + user_name = "user@jid.com" + room_name = "test room" + nick_name = "test nick" + password = "password" # why? + + backend = WhatsAppBackend(mock_backend, user_name, {}) + backend.sessions[user_name] = mock_session + + # Join room + backend.handle_join_room_request(user_name, room_name, nick_name, password) + mock_session.joinRoom.assert_called_with(room_name, nick_name) + + # Leave room + backend.handle_leave_room_request(user_name, room_name) + mock_session.leaveRoom.assert_called_with(room_name) + + +def test_handle_status_change(mock_backend, mock_session): + user_name = "user@jid.com" + + backend = WhatsAppBackend(mock_backend, user_name, {}) + backend.sessions[user_name] = mock_session + + backend.handle_status_change_request(user_name, 123, "this is status message") + + mock_session.changeStatus.assert_called_with(123) + mock_session.changeStatusMessage.assert_called_with("this is status message") + + +def test_sendData(mock_backend): + user_name = "user@jid.com" + + backend = WhatsAppBackend(mock_backend, user_name, {}) + backend.sendData(b"1234") + + mock_backend.send_data.assert_called_with(b"1234") + + +def test_relogin(mock_backend): + user_name = "user@jid.com" + + backend = WhatsAppBackend(mock_backend, user_name, {}) + + + +def test_handle_buddies(faker, mock_backend): + user_name = "user@jid.com" + buddies = generate_buddies(faker, 10) + + backend = WhatsAppBackend(mock_backend, user_name, {}) + backend.handle_buddies(buddies) \ No newline at end of file diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..609b370 --- /dev/null +++ b/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py37 + +[testenv:tests] +deps = + pytest + pytest-cov +commands = + pytest --cov {posargs} diff --git a/transWhat/buddy.py b/transWhat/buddy.py index 65ee7e3..ba5cdc7 100644 --- a/transWhat/buddy.py +++ b/transWhat/buddy.py @@ -2,7 +2,7 @@ import time import base64 import hashlib -import Spectrum2 +import spectrum2 from . import deferred diff --git a/transWhat/group.py b/transWhat/group.py index 61e4b21..bdfdfbd 100644 --- a/transWhat/group.py +++ b/transWhat/group.py @@ -1,4 +1,4 @@ -import Spectrum2 +import spectrum2 class Group: diff --git a/transWhat/registersession.py b/transWhat/registersession.py index 8c11abd..7854bfb 100644 --- a/transWhat/registersession.py +++ b/transWhat/registersession.py @@ -1,6 +1,6 @@ import sys import logging -import Spectrum2 +import spectrum2 from .yowsupwrapper import YowsupApp diff --git a/transWhat/session.py b/transWhat/session.py index 236b498..82d293c 100644 --- a/transWhat/session.py +++ b/transWhat/session.py @@ -6,7 +6,7 @@ from yowsup.layers.protocol_media.mediauploader import MediaUploader from yowsup.layers.protocol_media.mediadownloader import MediaDownloader -import Spectrum2 +import spectrum2 from . import deferred from .buddy import BuddyList @@ -45,7 +45,8 @@ class Session(YowsupApp): broadcast_prefix = "\U0001F4E2 " def __init__(self, backend, user, legacyName, extra): - super(Session, self).__init__() + super().__init__() + self.logger = logging.getLogger(self.__class__.__name__) self.logger.info("Created: %s" % legacyName) @@ -53,7 +54,7 @@ def __init__(self, backend, user, legacyName, extra): self.user = user self.legacyName = legacyName - self.status = Spectrum2.protocol_pb2.STATUS_NONE + self.status = spectrum2.protocol_pb2.STATUS_NONE self.statusMessage = "" self.groups = {} @@ -86,15 +87,21 @@ def __del__(self): # handleLogoutRequest self.logout() def logout(self): + # Do not logout when there is no way that we are logged in + if not self.loggedIn: + self.logger.info("%s already logged out, ignoring" % self.user) + return + + # Log out otherwise self.logger.info("%s logged out" % self.user) - super(Session, self).logout() + super().logout() self.loggedIn = False def login(self, password): self.logger.info("%s attempting login" % self.user) self.password = password self.shouldBeConncted = True - super(Session, self).login(self.legacyName, self.password) + super().login(self.legacyName, self.password) def _shortenGroupId(self, gid): # FIXME: might have problems if number begins with 0 @@ -111,7 +118,7 @@ def _lengthenGroupId(self, gid): def updateRoomList(self): rooms = [] text = [] - for room, group in self.groups.iteritems(): + for room, group in self.groups.items(): rooms.append([self._shortenGroupId(room), group.subject]) text.append( self._shortenGroupId(room) @@ -220,13 +227,13 @@ def sendReadReceipts(self, buddy): def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t): self.logger.info("Auth success: %s" % self.user) - self.backend.handleConnected(self.user) - self.backend.handleBuddyChanged( + self.backend.handle_connected(self.user) + self.backend.handle_buddy_changed( self.user, "bot", self.bot.name, ["Admin"], - Spectrum2.protocol_pb2.STATUS_ONLINE, + spectrum2.protocol_pb2.STATUS_ONLINE, ) # Initialisation? self.requestPrivacyList() @@ -235,7 +242,13 @@ def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t): # ? self.logger.debug("Requesting groups list") - self.requestGroupsList(self._updateGroups) + + # TODO: updateGroups is broken + # TODO: + # TODO: it also calls methods which do not + # TODO: exist in pyspectrum2 + # self.requestGroupsList(self._updateGroups) + # self.requestBroadcastList() # This should handle, sync, statuses, and presence @@ -253,14 +266,14 @@ def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t): # Called by superclass def onAuthFailed(self, reason): self.logger.info("Auth failed: %s (%s)" % (self.user, reason)) - self.backend.handleDisconnected(self.user, 0, reason) + self.backend.handle_disconnected(self.user, 0, reason) self.password = None self.loggedIn = False # Called by superclass def onDisconnect(self): self.logger.debug("Disconnected") - self.backend.handleDisconnected( + self.backend.handle_disconnected( self.user, 0, "Disconnected for unknown reasons" ) @@ -327,34 +340,25 @@ def onVideo(self, video): def onMedia(self, media, type): self.logger.debug("Received %s message: %s" % (type, media)) - buddy = media._from.split("@")[0] + buddy = media.getFrom(full=False) participant = media.participant + url = media.url caption = "" - if media.isEncrypted(): - self.logger.debug("Received encrypted media message") - if ( - self.backend.specConf is not None - and self.backend.specConf.__getitem__("service.web_directory") - is not None - and self.backend.specConf.__getitem__("service.web_url") is not None - ): - ipath = "/" + str(media.timestamp) + media.getExtension() - - with open( - self.backend.specConf.__getitem__("service.web_directory") + ipath, - "wb", - ) as f: - f.write(media.getMediaContent()) - url = self.backend.specConf.__getitem__("service.web_url") + ipath - else: - self.logger.warn( - "Received encrypted media: web storage not set in config!" - ) - url = media.url + # TODO: media.isEncrypted does not exist anymore(?) + # if media.isEncrypted(): + # self.logger.debug('Received encrypted media message') + # if self.backend.specConf is not None and self.backend.specConf.__getitem__("service.web_directory") is not None and self.backend.specConf.__getitem__("service.web_url") is not None : + # ipath = "/" + str(media.timestamp) + media.getExtension() - else: - url = media.url + # with open(self.backend.specConf.__getitem__("service.web_directory") + ipath,"wb") as f: + # f.write(media.getMediaContent()) + # url = self.backend.specConf.__getitem__("service.web_url") + ipath + # else: + # self.logger.warn('Received encrypted media: web storage not set in config!') + # url = media.url + + # else: if type == "image": caption = media.caption @@ -362,19 +366,23 @@ def onMedia(self, media, type): if participant is not None: # Group message partname = participant.split("@")[0] if media._from.split("@")[1] == "broadcast": # Broadcast message - self.sendMessageToXMPP(partname, self.broadcast_prefix, media.timestamp) - self.sendMessageToXMPP(partname, url, media.timestamp) - self.sendMessageToXMPP(partname, caption, media.timestamp) + self.sendMessageToXMPP( + partname, self.broadcast_prefix, media.getTimestamp() + ) + self.sendMessageToXMPP(partname, url, media.getTimestamp()) + self.sendMessageToXMPP(partname, caption, media.getTimestamp()) else: # Group message - self.sendGroupMessageToXMPP(buddy, partname, url, media.timestamp) - self.sendGroupMessageToXMPP(buddy, partname, caption, media.timestamp) + self.sendGroupMessageToXMPP(buddy, partname, url, media.getTimestamp()) + self.sendGroupMessageToXMPP( + buddy, partname, caption, media.getTimestamp() + ) else: - self.sendMessageToXMPP(buddy, url, media.timestamp) - self.sendMessageToXMPP(buddy, caption, media.timestamp) + self.sendMessageToXMPP(buddy, url, media.getTimestamp()) + self.sendMessageToXMPP(buddy, caption, media.getTimestamp()) - self.sendReceipt(media._id, media._from, None, media.participant) + self.sendReceipt(media.getId(), media.getFrom(), None, media.participant) self.recvMsgIDs.append( - (media._id, media._from, media.participant, media.timestamp) + (media.getId(), media.getFrom(), media.participant, media.getTimestamp()) ) def onLocation(self, location): @@ -637,7 +645,7 @@ def sendImage(self, message, ID, to): call(os.remove, pathWithExt) call(self.logger.info, "Sending image to %s" % to) waId = deferred.Deferred() - call(super(Session, self).sendImage, to, pathJpg, onSuccess=waId.run) + call(super().sendImage, to, pathJpg, onSuccess=waId.run) call(self.setWaId, ID, waId) waId.when(call, os.remove, pathJpg) waId.when(self.logger.info, "Image sent") @@ -749,24 +757,20 @@ def _sendLocation(self, buddy, message, ID): self.msgIDs[waId] = MsgIDs(ID, waId) self.logger.info("WA Location Message send to %s with ID %s", buddy, waId) - def sendMessageToXMPP(self, buddy, messageContent, timestamp="", nickname=""): + def sendMessageToXMPP(self, buddy, message, timestamp="", nickname=""): if timestamp: timestamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime(timestamp)) if self.initialized == False: self.logger.debug( - "Message queued from %s to %s: %s" - % (buddy, self.legacyName, messageContent) + "Message queued from %s to %s: %s" % (buddy, self.legacyName, message) ) - self.offlineQueue.append((buddy, messageContent, timestamp)) + self.offlineQueue.append((buddy, message, timestamp)) else: self.logger.debug( - "Message sent from %s to %s: %s" - % (buddy, self.legacyName, messageContent) - ) - self.backend.handleMessage( - self.user, buddy, messageContent, "", "", timestamp + "Message sent from %s to %s: %s" % (buddy, self.legacyName, message) ) + self.backend.handle_message(self.user, buddy, message, "", "", timestamp) def sendGroupMessageToXMPP( self, room, number, messageContent, timestamp="", defaultname="" @@ -827,8 +831,8 @@ def changeStatus(self, status): self.status = status if ( - status == Spectrum2.protocol_pb2.STATUS_ONLINE - or status == Spectrum2.protocol_pb2.STATUS_FFC + status == spectrum2.protocol_pb2.STATUS_ONLINE + or status == spectrum2.protocol_pb2.STATUS_FFC ): self.sendPresence(True) else: @@ -935,8 +939,8 @@ def onGroupParticipantRemoved( self.user, buddy, room, - Spectrum2.protocol_pb2.PARTICIPANT_FLAG_NONE, - Spectrum2.protocol_pb2.STATUS_NONE, + spectrum2.protocol_pb2.PARTICIPANT_FLAG_NONE, + spectrum2.protocol_pb2.STATUS_NONE, ) # TODO if receiptRequested: diff --git a/transWhat/transwhat.py b/transWhat/transwhat.py index 403d002..ef9ddab 100755 --- a/transWhat/transwhat.py +++ b/transWhat/transwhat.py @@ -7,12 +7,12 @@ import sys import queue -import Spectrum2 +import spectrum2 from yowsup.common import YowConstants from yowsup.stacks import YowStack -from .whatsappbackend import WhatsAppBackend -from . import threadutils +from transWhat.whatsappbackend import WhatsAppBackend +from transWhat import threadutils # Arguments parser = argparse.ArgumentParser() diff --git a/transWhat/whatsappbackend.py b/transWhat/whatsappbackend.py index 8ae2a29..55cf333 100644 --- a/transWhat/whatsappbackend.py +++ b/transWhat/whatsappbackend.py @@ -1,13 +1,14 @@ import logging -import Spectrum2 +import spectrum2 from .session import Session from .registersession import RegisterSession -class WhatsAppBackend(Spectrum2.Backend): +class WhatsAppBackend(spectrum2.Backend): def __init__(self, io, spectrum_jid, specConf): - Spectrum2.Backend.__init__(self) + super().__init__(self) + self.logger = logging.getLogger(self.__class__.__name__) self.io = io self.specConf = specConf @@ -19,7 +20,7 @@ def __init__(self, io, spectrum_jid, specConf): self.logger.debug("Backend started") # RequestsHandlers - def handleLoginRequest(self, user, legacyName, password, extra): + def handle_login_request(self, user, legacyName, password, extra): self.logger.debug( "handleLoginRequest(user=%s, legacyName=%s)" % (user, legacyName) ) @@ -33,7 +34,7 @@ def handleLoginRequest(self, user, legacyName, password, extra): self.sessions[user].login(password) - def handleLogoutRequest(self, user, legacyName): + def handle_logout_request(self, user, legacyName): self.logger.debug( "handleLogoutRequest(user=%s, legacyName=%s)" % (user, legacyName) ) @@ -41,7 +42,7 @@ def handleLogoutRequest(self, user, legacyName): self.sessions[user].logout() del self.sessions[user] - def handleMessageSendRequest(self, user, buddy, message, xhtml="", ID=""): + def handle_message_send_request(self, user, buddy, message, xhtml="", ID=""): self.logger.debug( "handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml=%s, ID=%s)" % (user, buddy, message, xhtml, ID) @@ -56,18 +57,18 @@ def handleMessageSendRequest(self, user, buddy, message, xhtml="", ID=""): self.sessions[user].sendMessageToWA(buddy, message, ID, xhtml) self.lastMsgId[user] = ID - def handleJoinRoomRequest(self, user, room, nickname, pasword): + def handle_join_room_request(self, user, room, nickname, pasword): self.logger.debug( "handleJoinRoomRequest(user=%s, room=%s, nickname=%s)" % (user, room, nickname) ) self.sessions[user].joinRoom(room, nickname) - def handleLeaveRoomRequest(self, user, room): + def handle_leave_room_request(self, user, room): self.logger.debug("handleLeaveRoomRequest(user=%s, room=%s)" % (user, room)) self.sessions[user].leaveRoom(room) - def handleStatusChangeRequest(self, user, status, statusMessage): + def handle_status_change_request(self, user, status, statusMessage): self.logger.debug( "handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)" % (user, status, statusMessage) @@ -136,7 +137,7 @@ def relogin(self, user, legacyName, password, extra): """ self.logger.debug("relogin(user=%s, legacyName=%s)" % (user, legacyName)) # Change password in spectrum database - self.handleQuery("register %s %s %s" % (user, legacyName, password)) + self.handle_query("register %s %s %s" % (user, legacyName, password)) # Key word means we should register a new password if password == "register": # This shouldn't happen, but just in case self.sessions[user] = RegisterSession(self, user, legacyName, extra) @@ -170,4 +171,4 @@ def handleMessageAckRequest(self, user, legacyName, ID=0): self.logger.info("Meassage ACK request for %s !!" % legacyName) def sendData(self, data): - self.io.sendData(data) + self.io.send_data(data)