Hard to find connection bugs are occuring. Reverting changes for now
This commit is contained in:
moyamo 2015-12-31 21:43:10 +02:00
parent bed8214a11
commit 22cebef457
11 changed files with 478 additions and 501 deletions

View file

@ -262,6 +262,7 @@ class SpectrumBackend:
def handleConvMessagePayload(self, data): def handleConvMessagePayload(self, data):
payload = protocol_pb2.ConversationMessage() payload = protocol_pb2.ConversationMessage()
self.logger.error("handleConvMessagePayload")
if (payload.ParseFromString(data) == False): if (payload.ParseFromString(data) == False):
#TODO: ERROR #TODO: ERROR
return return

View file

@ -28,6 +28,7 @@ The bot is one of the contacts every user has in its contact list. It offers you
| ------------ | --------------- | | ------------ | --------------- |
| `\help` | show this message | | `\help` | show this message |
| `\prune` | clear your buddylist | | `\prune` | clear your buddylist |
| `\sync` | sync your imported contacts with WhatsApp |
| `\lastseen` | request last online timestamp from buddy | | `\lastseen` | request last online timestamp from buddy |
| `\leave` | permanently leave group chat | | `\leave` | permanently leave group chat |
| `\groups` | print all attended groups | | `\groups` | print all attended groups |

40
bot.py
View file

@ -1,10 +1,10 @@
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -30,30 +30,30 @@ import os
import utils import utils
class Bot(): class Bot():
def __init__(self, session, name = u"Bot"): def __init__(self, session, name = "Bot"):
self.session = session self.session = session
self.name = name self.name = name
self.commands = { self.commands = {
u"help": self._help, "help": self._help,
u"prune": self._prune, "prune": self._prune,
u"groups": self._groups, "groups": self._groups,
u"getgroups": self._getgroups "getgroups": self._getgroups
} }
def parse(self, message): def parse(self, message):
args = message.split(u" ") args = message.split(" ")
cmd = args.pop(0) cmd = args.pop(0)
if cmd[0] == u'\\': if cmd[0] == '\\':
try: try:
self.call(cmd[1:], args) self.call(cmd[1:], args)
except KeyError: except KeyError:
self.send(u"invalid command") self.send("invalid command")
except TypeError: except TypeError:
self.send(u"invalid syntax") self.send("invalid syntax")
else: else:
self.send(u"a valid command starts with a backslash") self.send("a valid command starts with a backslash")
def call(self, cmd, args = []): def call(self, cmd, args = []):
func = self.commands[cmd] func = self.commands[cmd]
@ -71,7 +71,7 @@ class Bot():
# commands # commands
def _help(self): def _help(self):
self.send(u"""following bot commands are available: self.send("""following bot commands are available:
\\help show this message \\help show this message
\\prune clear your buddylist \\prune clear your buddylist
@ -86,7 +86,7 @@ following group commands are available
def _prune(self): def _prune(self):
self.session.buddies.prune() self.session.buddies.prune()
self.session.updateRoster() self.session.updateRoster()
self.send(u"buddy list cleared") self.send("buddy list cleared")
def _groups(self): def _groups(self):
for group in self.session.groups: for group in self.session.groups:
@ -96,9 +96,9 @@ following group commands are available
except KeyError: except KeyError:
nick = buddy nick = buddy
self.send(self.session.groups[group].id + u"@" + self.session.backend.spectrum_jid + u" " + self.session.groups[group].subject + u" Owner: " + nick ) self.send(self.session.groups[group].id + "@" + self.session.backend.spectrum_jid + " " + self.session.groups[group].subject + " Owner: " + nick )
def _getgroups(self): def _getgroups(self):
#self.session.call(u"group_getGroups", (u"participating",)) #self.session.call("group_getGroups", ("participating",))
self.session.requestGroupsList(self.session._updateGroups) self.session.requestGroupsList(self.session._updateGroups)

View file

@ -1,10 +1,10 @@
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -25,7 +25,6 @@ from Spectrum2 import protocol_pb2
import logging import logging
import time import time
import utils
class Buddy(): class Buddy():
@ -34,8 +33,8 @@ class Buddy():
self.owner = owner self.owner = owner
self.number = number self.number = number
self.groups = groups self.groups = groups
self.image_hash = image_hash if image_hash is not None else u"" self.image_hash = image_hash if image_hash is not None else ""
self.statusMsg = u"" self.statusMsg = ""
self.lastseen = 0 self.lastseen = 0
self.presence = 0 self.presence = 0
@ -47,7 +46,7 @@ class Buddy():
self.image_hash = image_hash self.image_hash = image_hash
def __str__(self): def __str__(self):
return u"%s (nick=%s)" % (self.number, self.nick) return "%s (nick=%s)" % (self.number, self.nick)
class BuddyList(dict): class BuddyList(dict):
@ -63,20 +62,20 @@ class BuddyList(dict):
for buddy in buddies: for buddy in buddies:
number = buddy.buddyName number = buddy.buddyName
nick = buddy.alias nick = buddy.alias
statusMsg = buddy.statusMessage.decode(u'utf-8') statusMsg = buddy.statusMessage
groups = [g for g in buddy.group] groups = [g for g in buddy.group]
image_hash = buddy.iconHash image_hash = buddy.iconHash
self[number] = Buddy(self.owner, number, nick, statusMsg, self[number] = Buddy(self.owner, number, nick, statusMsg,
groups, image_hash) groups, image_hash)
self.logger.debug(u"Update roster") self.logger.debug("Update roster")
# old = self.buddies.keys() # old = self.buddies.keys()
# self.buddies.load() # self.buddies.load()
# new = self.buddies.keys() # new = self.buddies.keys()
# contacts = new # contacts = new
contacts = self.keys() contacts = self.keys()
contacts.remove(u'bot') contacts.remove('bot')
if self.synced == False: if self.synced == False:
self.session.sendSync(contacts, delta = False, interactive = True) self.session.sendSync(contacts, delta = False, interactive = True)
@ -85,11 +84,11 @@ class BuddyList(dict):
# add = set(new) - set(old) # add = set(new) - set(old)
# remove = set(old) - set(new) # remove = set(old) - set(new)
# self.logger.debug(u"Roster remove: %s", str(list(remove))) # self.logger.debug("Roster remove: %s", str(list(remove)))
self.logger.debug(u"Roster add: %s", str(list(contacts))) self.logger.debug("Roster add: %s", str(list(contacts)))
# for number in remove: # for number in remove:
# self.backend.handleBuddyChanged(self.user, number, u"", [], # self.backend.handleBuddyChanged(self.user, number, "", [],
# protocol_pb2.STATUS_NONE) # protocol_pb2.STATUS_NONE)
# self.backend.handleBuddyRemoved(self.user, number) # self.backend.handleBuddyRemoved(self.user, number)
# self.unsubscribePresence(number) # self.unsubscribePresence(number)
@ -98,19 +97,16 @@ class BuddyList(dict):
buddy = self[number] buddy = self[number]
self.backend.handleBuddyChanged(self.user, number, buddy.nick, self.backend.handleBuddyChanged(self.user, number, buddy.nick,
buddy.groups, protocol_pb2.STATUS_NONE, buddy.groups, protocol_pb2.STATUS_NONE,
iconHash = buddy.image_hash if buddy.image_hash is not None else u"") iconHash = buddy.image_hash if buddy.image_hash is not None else "")
self.session.subscribePresence(number) self.session.subscribePresence(number)
self.logger.debug(u"%s is requesting statuses of: %s", self.user, contacts) self.logger.debug("%s is requesting statuses of: %s", self.user, contacts)
self.session.requestStatuses(contacts, success = self.onStatus) self.session.requestStatuses(contacts, success = self.onStatus)
def onStatus(self, contacts): def onStatus(self, contacts):
self.logger.debug(u"%s received statuses of: %s", self.user, contacts) self.logger.debug("%s received statuses of: %s", self.user, contacts)
for number, (status, time) in contacts.iteritems(): for number, (status, time) in contacts.iteritems():
buddy = self[number] buddy = self[number]
if status is None: buddy.statusMsg = status
buddy.statusMsg = ""
else:
buddy.statusMsg = utils.softToUni(status)
self.updateSpectrum(buddy) self.updateSpectrum(buddy)
@ -128,9 +124,9 @@ class BuddyList(dict):
self.session.sendSync([number], delta = True, interactive = True) self.session.sendSync([number], delta = True, interactive = True)
self.session.subscribePresence(number) self.session.subscribePresence(number)
self.session.requestStatuses([number], success = self.onStatus) self.session.requestStatuses([number], success = self.onStatus)
buddy = Buddy(self.owner, number, nick, u"", groups, image_hash) buddy = Buddy(self.owner, number, nick, "", groups, image_hash)
self[number] = buddy self[number] = buddy
self.logger.debug(u"Roster add: %s", buddy) self.logger.debug("Roster add: %s", buddy)
self.updateSpectrum(buddy) self.updateSpectrum(buddy)
return buddy return buddy
@ -138,7 +134,7 @@ class BuddyList(dict):
def updateSpectrum(self, buddy): def updateSpectrum(self, buddy):
if buddy.presence == 0: if buddy.presence == 0:
status = protocol_pb2.STATUS_NONE status = protocol_pb2.STATUS_NONE
elif buddy.presence == u'unavailable': elif buddy.presence == 'unavailable':
status = protocol_pb2.STATUS_AWAY status = protocol_pb2.STATUS_AWAY
else: else:
status = protocol_pb2.STATUS_ONLINE status = protocol_pb2.STATUS_ONLINE
@ -146,18 +142,18 @@ class BuddyList(dict):
statusmsg = buddy.statusMsg statusmsg = buddy.statusMsg
if buddy.lastseen != 0: if buddy.lastseen != 0:
timestamp = time.localtime(buddy.lastseen) timestamp = time.localtime(buddy.lastseen)
statusmsg += time.strftime(u"\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp) statusmsg += time.strftime("\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp)
self.backend.handleBuddyChanged(self.user, buddy.number, buddy.nick, self.backend.handleBuddyChanged(self.user, buddy.number, buddy.nick,
buddy.groups, status, statusMessage = statusmsg, buddy.groups, status, statusMessage = statusmsg,
iconHash = buddy.image_hash if buddy.image_hash is not None else u"") iconHash = buddy.image_hash if buddy.image_hash is not None else "")
def remove(self, number): def remove(self, number):
try: try:
buddy = self[number] buddy = self[number]
del self[number] del self[number]
self.backend.handleBuddyChanged(self.user, number, u"", [], self.backend.handleBuddyChanged(self.user, number, "", [],
protocol_pb2.STATUS_NONE) protocol_pb2.STATUS_NONE)
self.backend.handleBuddyRemoved(self.user, number) self.backend.handleBuddyRemoved(self.user, number)
self.session.unsubscribePresence(number) self.session.unsubscribePresence(number)

View file

@ -1,10 +1,10 @@
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -21,77 +21,14 @@ u"""
along with transWhat. If not, see <http://www.gnu.org/licenses/>. along with transWhat. If not, see <http://www.gnu.org/licenses/>.
""" """
from Spectrum2 import protocol_pb2
class Group(): class Group():
def __init__(self, id, owner, subject, subjectOwner, backend, user): def __init__(self, id, owner, subject, subjectOwner):
self.id = id self.id = id
self.subject = subject self.subject = subject
self.subjectOwner = subjectOwner self.subjectOwner = subjectOwner
self.owner = owner self.owner = owner
self.joined = False self.joined = False
self.backend = backend
self.user = user
self.nick = u"me" self.nick = "me"
# Participants is a number -> nickname dict self.participants = []
self.participants = {}
def addParticipants(self, participants, buddies, yourNumber):
u"""
Adds participants to the group.
Args:
- participants: (Iterable) phone numbers of participants
- buddies: (dict) Used to get the nicknames of the participants
- yourNumber: The number you are using
"""
for jid in participants:
number = jid.split(u'@')[0]
try:
nick = buddies[number].nick
except KeyError:
nick = number
if number == yourNumber:
nick = self.nick
if nick == u"":
nick = number
self.participants[number] = nick
def sendParticipantsToSpectrum(self, yourNumber):
for number, nick in self.participants.iteritems():
if number == self.owner:
flags = protocol_pb2.PARTICIPANT_FLAG_MODERATOR
else:
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
if number == yourNumber:
flags = flags | protocol_pb2.PARTICIPANT_FLAG_ME
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE)
def removeParticipants(self, participants):
for jid in participants:
number = jid.split(u'@')[0]
nick = self.participants[number]
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE)
del self.participants[number]
def changeNick(self, number, new_nick):
if self.participants[number] == new_nick:
return
if number == self.owner:
flags = protocol_pb2.PARTICIPANT_FLAG_MODERATOR
else:
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, new_nick)
self.participants[number] = new_nick
def _updateParticipant(self, number, flags, status, newNick = u""):
nick = self.participants[number]
# Notice the status message is the buddy's number
if self.joined:
self.backend.handleParticipantChanged(
self.user, nick, self.id, flags,
status, number, newname = newNick)

View file

@ -1,10 +1,10 @@
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -24,19 +24,19 @@ u"""
import time import time
def get_token(number, timeout = 30): def get_token(number, timeout = 30):
file = open(u'tokens') file = open('tokens')
file.seek(-1, 2) file.seek(-1, 2)
count = 0 count = 0
while count < timeout: while count < timeout:
line = file.readline() line = file.readline()
if line in [u"", u"\n"]: if line in ["", "\n"]:
time.sleep(1) time.sleep(1)
count += 1 count += 1
continue continue
else: else:
t, n, tk = line[:-1].split(u"\t") t, n, tk = line[:-1].split("\t")
if (n == number): if (n == number):
file.close() file.close()
@ -45,4 +45,4 @@ def get_token(number, timeout = 30):
file.close() file.close()
print get_token(u"4917696978528") print get_token("4917696978528")

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,12 @@
#!/usr/bin/python #!/usr/bin/python
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -42,21 +42,21 @@ from yowsup.stacks import YowStack
# Arguments # Arguments
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument(u'--debug', action=u'store_true') parser.add_argument('--debug', action='store_true')
parser.add_argument(u'--host', type=str, required=True) parser.add_argument('--host', type=str, required=True)
parser.add_argument(u'--port', type=int, required=True) parser.add_argument('--port', type=int, required=True)
parser.add_argument(u'--service.backend_id', metavar=u"ID", type=int, required=True) parser.add_argument('--service.backend_id', metavar="ID", type=int, required=True)
parser.add_argument(u'config', type=str) parser.add_argument('config', type=str)
parser.add_argument(u'-j', type=str, required=True) parser.add_argument('-j', type=str, required=True)
args, unknown = parser.parse_known_args() args, unknown = parser.parse_known_args()
YowConstants.PATH_STORAGE=u'/var/lib/spectrum2/' + args.j YowConstants.PATH_STORAGE='/var/lib/spectrum2/' + args.j
loggingfile = u'/var/log/spectrum2/' + args.j + u'/backends/backend.log' loggingfile = '/var/log/spectrum2/' + args.j + '/backends/backend.log'
# Logging # Logging
logging.basicConfig( \ logging.basicConfig( \
filename=loggingfile,\ filename=loggingfile,\
format = u"%(asctime)-15s %(levelname)s %(name)s: %(message)s", \ format = "%(asctime)-15s %(levelname)s %(name)s: %(message)s", \
level = logging.DEBUG if args.debug else logging.INFO \ level = logging.DEBUG if args.debug else logging.INFO \
) )
@ -77,9 +77,9 @@ io = IOChannel(args.host, args.port, handleTransportData, connectionClosed)
plugin = WhatsAppBackend(io, args.j) plugin = WhatsAppBackend(io, args.j)
plugin.handleBackendConfig({ plugin.handleBackendConfig({
u'features': [ 'features': [
(u'send_buddies_on_login', 1), ('send_buddies_on_login', 1),
(u'muc', u'true'), ('muc', 'true'),
], ],
}) })
@ -87,7 +87,7 @@ while True:
try: try:
asyncore.loop(timeout=1.0, count=10, use_poll = True) asyncore.loop(timeout=1.0, count=10, use_poll = True)
try: try:
callback = YowStack._YowStack__detachedQueue.get(False) #doesnu't block callback = YowStack._YowStack__detachedQueue.get(False) #doesn't block
callback() callback()
except Queue.Empty: except Queue.Empty:
pass pass

View file

@ -1,10 +1,10 @@
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -24,10 +24,9 @@ u"""
import e4u import e4u
import base64 import base64
import hashlib import hashlib
import base64
def ago(secs): def ago(secs):
periods = [u"second", u"minute", u"hour", u"day", u"week", u"month", u"year", u"decade"] periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"]
lengths = [60, 60, 24, 7,4.35, 12, 10] lengths = [60, 60, 24, 7,4.35, 12, 10]
j = 0 j = 0
@ -39,16 +38,16 @@ def ago(secs):
j += 1 j += 1
period = periods[j] period = periods[j]
if diff > 1: period += u"s" if diff > 1: period += "s"
return u"%d %s ago" % (diff, period) return "%d %s ago" % (diff, period)
def softToUni(message): def softToUni(message):
message = message.decode(u"utf-8") message = message.decode("utf-8")
return e4u.translate(message, reverse=False, **e4u.SOFTBANK_TRANSLATE_PROFILE) return e4u.translate(message, reverse=False, **e4u.SOFTBANK_TRANSLATE_PROFILE)
def decodePassword(password): def decodePassword(password):
return base64.b64decode(bytes(password.encode(u"utf-8"))) return base64.b64decode(bytes(password.encode("utf-8")))
def sha1hash(data): def sha1hash(data):
return base64.b64encode(hashlib.sha1(data).digest()) return hashlib.sha1(data).hexdigest()

View file

@ -1,10 +1,10 @@
__author__ = u"Steffen Vogel" __author__ = "Steffen Vogel"
__copyright__ = u"Copyright 2015, Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = u"GPLv3" __license__ = "GPLv3"
__maintainer__ = u"Steffen Vogel" __maintainer__ = "Steffen Vogel"
__email__ = u"post@steffenvogel.de" __email__ = "post@steffenvogel.de"
u""" """
This file is part of transWhat This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify transWhat is free software: you can redistribute it and/or modify
@ -38,11 +38,11 @@ class WhatsAppBackend(SpectrumBackend):
# Used to prevent duplicate messages # Used to prevent duplicate messages
self.lastMessage = {} self.lastMessage = {}
self.logger.debug(u"Backend started") self.logger.debug("Backend started")
# RequestsHandlers # RequestsHandlers
def handleLoginRequest(self, user, legacyName, password, extra): def handleLoginRequest(self, user, legacyName, password, extra):
self.logger.debug(u"handleLoginRequest(user=%s, legacyName=%s)", user, legacyName) self.logger.debug("handleLoginRequest(user=%s, legacyName=%s)", user, legacyName)
if user not in self.sessions: if user not in self.sessions:
self.sessions[user] = Session(self, user, legacyName, extra) self.sessions[user] = Session(self, user, legacyName, extra)
@ -52,13 +52,13 @@ class WhatsAppBackend(SpectrumBackend):
self.sessions[user].login(password) self.sessions[user].login(password)
def handleLogoutRequest(self, user, legacyName): def handleLogoutRequest(self, user, legacyName):
self.logger.debug(u"handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName) self.logger.debug("handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName)
if user in self.sessions: if user in self.sessions:
self.sessions[user].logout() self.sessions[user].logout()
del self.sessions[user] del self.sessions[user]
def handleMessageSendRequest(self, user, buddy, message, xhtml = u"", ID = 0): def handleMessageSendRequest(self, user, buddy, message, xhtml = "", ID = 0):
self.logger.debug(u"handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml) self.logger.debug("handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml)
# For some reason spectrum occasionally sends to identical messages to # For some reason spectrum occasionally sends to identical messages to
# a buddy, one to the bare jid and one to /bot. This causes duplicate # a buddy, one to the bare jid and one to /bot. This causes duplicate
# messages. Since it is unlikely a user wants to send the same message # messages. Since it is unlikely a user wants to send the same message
@ -73,48 +73,48 @@ class WhatsAppBackend(SpectrumBackend):
usersMessage[buddy] = message usersMessage[buddy] = message
def handleJoinRoomRequest(self, user, room, nickname, pasword): def handleJoinRoomRequest(self, user, room, nickname, pasword):
self.logger.debug(u"handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname) self.logger.debug("handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname)
self.sessions[user].joinRoom(room, nickname) self.sessions[user].joinRoom(room, nickname)
def handleLeaveRoomRequest(self, user, room): def handleLeaveRoomRequest(self, user, room):
self.logger.debug(u"handleLeaveRoomRequest(user=%s, room=%s)", user, room) self.logger.debug("handleLeaveRoomRequest(user=%s, room=%s)", user, room)
self.sessions[user].leaveRoom(room) self.sessions[user].leaveRoom(room)
def handleStatusChangeRequest(self, user, status, statusMessage): def handleStatusChangeRequest(self, user, status, statusMessage):
self.logger.debug(u"handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage) self.logger.debug("handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage)
self.sessions[user].changeStatusMessage(statusMessage) self.sessions[user].changeStatusMessage(statusMessage)
self.sessions[user].changeStatus(status) self.sessions[user].changeStatus(status)
def handleBuddies(self, buddies): def handleBuddies(self, buddies):
u"""Called when user logs in. Used to initialize roster.""" """Called when user logs in. Used to initialize roster."""
self.logger.debug(u"handleBuddies(buddies=%s)", buddies) self.logger.debug("handleBuddies(buddies=%s)", buddies)
buddies = [b for b in buddies.buddy] buddies = [b for b in buddies.buddy]
if len(buddies) > 0: if len(buddies) > 0:
user = buddies[0].userName user = buddies[0].userName
self.sessions[user].loadBuddies(buddies) self.sessions[user].loadBuddies(buddies)
def handleBuddyUpdatedRequest(self, user, buddy, nick, groups): def handleBuddyUpdatedRequest(self, user, buddy, nick, groups):
self.logger.debug(u"handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups)) self.logger.debug("handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups))
self.sessions[user].updateBuddy(buddy, nick, groups) self.sessions[user].updateBuddy(buddy, nick, groups)
def handleBuddyRemovedRequest(self, user, buddy, groups): def handleBuddyRemovedRequest(self, user, buddy, groups):
self.logger.debug(u"handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups)) self.logger.debug("handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups))
self.sessions[user].removeBuddy(buddy) self.sessions[user].removeBuddy(buddy)
def handleTypingRequest(self, user, buddy): def handleTypingRequest(self, user, buddy):
self.logger.debug(u"handleTypingRequest(user=%s, buddy=%s)", user, buddy) self.logger.debug("handleTypingRequest(user=%s, buddy=%s)", user, buddy)
self.sessions[user].sendTypingStarted(buddy) self.sessions[user].sendTypingStarted(buddy)
def handleTypedRequest(self, user, buddy): def handleTypedRequest(self, user, buddy):
self.logger.debug(u"handleTypedRequest(user=%s, buddy=%s)", user, buddy) self.logger.debug("handleTypedRequest(user=%s, buddy=%s)", user, buddy)
self.sessions[user].sendTypingStopped(buddy) self.sessions[user].sendTypingStopped(buddy)
def handleStoppedTypingRequest(self, user, buddy): def handleStoppedTypingRequest(self, user, buddy):
self.logger.debug(u"handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy) self.logger.debug("handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy)
self.sessions[user].sendTypingStopped(buddy) self.sessions[user].sendTypingStopped(buddy)
def handleVCardRequest(self, user, buddy, ID): def handleVCardRequest(self, user, buddy, ID):
self.logger.debug(u"handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID) self.logger.debug("handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID)
self.sessions[user].requestVCard(buddy, ID) self.sessions[user].requestVCard(buddy, ID)
@ -129,7 +129,7 @@ class WhatsAppBackend(SpectrumBackend):
pass pass
def handleFTStartRequest(self, user, buddy, fileName, size, ftID): def handleFTStartRequest(self, user, buddy, fileName, size, ftID):
self.logger.debug(u'File send request %s, for user %s, from %s, size: %s', self.logger.debug('File send request %s, for user %s, from %s, size: %s',
fileName, user, buddy, size) fileName, user, buddy, size)
def handleFTFinishRequest(self, user, buddy, fileName, size, ftID): def handleFTFinishRequest(self, user, buddy, fileName, size, ftID):
@ -145,7 +145,7 @@ class WhatsAppBackend(SpectrumBackend):
pass pass
def handleMessageAckRequest(self, user, legacyName, ID = 0): def handleMessageAckRequest(self, user, legacyName, ID = 0):
self.logger.info(u"Meassage ACK request for %s !!",legacyName) self.logger.info("Meassage ACK request for %s !!",legacyName)
def sendData(self, data): def sendData(self, data):
self.io.sendData(data) self.io.sendData(data)

View file

@ -78,7 +78,7 @@ class YowsupApp(object):
) )
def login(self, username, password): def login(self, username, password):
u"""Login to yowsup """Login to yowsup
Should result in onAuthSuccess or onAuthFailure to be called. Should result in onAuthSuccess or onAuthFailure to be called.
@ -102,20 +102,20 @@ class YowsupApp(object):
self.stack.broadcastEvent( self.stack.broadcastEvent(
YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
except TypeError as e: # Occurs when password is not correctly formated except TypeError as e: # Occurs when password is not correctly formated
self.onAuthFailure(u'password not base64 encoded') self.onAuthFailure('password not base64 encoded')
# try: # try:
# self.stack.loop(timeout=0.5, discrete=0.5) # self.stack.loop(timeout=0.5, discrete=0.5)
# except AuthError as e: # For some reason Yowsup throws an exception # except AuthError as e: # For some reason Yowsup throws an exception
# self.onAuthFailure(u"%s" % e) # self.onAuthFailure("%s" % e)
def logout(self): def logout(self):
u""" """
Logout from whatsapp Logout from whatsapp
""" """
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT)) self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
def sendReceipt(self, _id, _from, read, participant): def sendReceipt(self, _id, _from, read, participant):
u""" """
Send a receipt (delivered: double-tick, read: blue-ticks) Send a receipt (delivered: double-tick, read: blue-ticks)
Args: Args:
@ -128,7 +128,7 @@ class YowsupApp(object):
self.sendEntity(receipt) self.sendEntity(receipt)
def sendTextMessage(self, to, message): def sendTextMessage(self, to, message):
u""" """
Sends a text message Sends a text message
Args: Args:
@ -140,7 +140,7 @@ class YowsupApp(object):
return messageEntity.getId() return messageEntity.getId()
def sendLocation(self, to, latitude, longitude): def sendLocation(self, to, latitude, longitude):
messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, u"raw", to = to) messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, "raw", to = to)
self.sendEntity(messageEntity) self.sendEntity(messageEntity)
return messageEntity.getId() return messageEntity.getId()
@ -170,14 +170,14 @@ class YowsupApp(object):
mediaUploader.start() mediaUploader.start()
def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity): def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity):
self.logger.error(u"Request upload for file %s for %s failed" % (path, jid)) self.logger.error("Request upload for file %s for %s failed" % (path, jid))
def onUploadError(self, filePath, jid, url): def onUploadError(self, filePath, jid, url):
#logger.error(u"Upload file %s to %s for %s failed!" % (filePath, url, jid)) #logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid))
self.logger.error(u"Upload Error!") self.logger.error("Upload Error!")
def onUploadProgress(self, filePath, jid, url, progress): def onUploadProgress(self, filePath, jid, url, progress):
#sys.stdout.write(u"%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress)) #sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
#sys.stdout.flush() #sys.stdout.flush()
pass pass
@ -197,7 +197,7 @@ class YowsupApp(object):
def sendPresence(self, available): def sendPresence(self, available):
u""" """
Send presence to whatsapp Send presence to whatsapp
Args: Args:
@ -209,42 +209,42 @@ class YowsupApp(object):
self.sendEntity(UnavailablePresenceProtocolEntity()) self.sendEntity(UnavailablePresenceProtocolEntity())
def subscribePresence(self, phone_number): def subscribePresence(self, phone_number):
u""" """
Subscribe to presence updates from phone_number Subscribe to presence updates from phone_number
Args: Args:
- phone_number: (str) The cellphone number of the person to - phone_number: (str) The cellphone number of the person to
subscribe to subscribe to
""" """
self.logger.debug(u"Subscribing to Presence updates from %s", (phone_number)) self.logger.debug("Subscribing to Presence updates from %s", (phone_number))
jid = phone_number + u'@s.whatsapp.net' jid = phone_number + '@s.whatsapp.net'
entity = SubscribePresenceProtocolEntity(jid) entity = SubscribePresenceProtocolEntity(jid)
self.sendEntity(entity) self.sendEntity(entity)
def unsubscribePresence(self, phone_number): def unsubscribePresence(self, phone_number):
u""" """
Unsubscribe to presence updates from phone_number Unsubscribe to presence updates from phone_number
Args: Args:
- phone_number: (str) The cellphone number of the person to - phone_number: (str) The cellphone number of the person to
unsubscribe from unsubscribe from
""" """
jid = phone_number + u'@s.whatsapp.net' jid = phone_number + '@s.whatsapp.net'
entity = UnsubscribePresenceProtocolEntity(jid) entity = UnsubscribePresenceProtocolEntity(jid)
self.sendEntity(entity) self.sendEntity(entity)
def leaveGroup(self, group): def leaveGroup(self, group):
u""" """
Permanently leave a WhatsApp group Permanently leave a WhatsApp group
Args: Args:
- group: (str) the group id (e.g. 27831788123-144024456) - group: (str) the group id (e.g. 27831788123-144024456)
""" """
entity = LeaveGroupsIqProtocolEntity([group + u'@g.us']) entity = LeaveGroupsIqProtocolEntity([group + '@g.us'])
self.sendEntity(entity) self.sendEntity(entity)
def setStatus(self, statusText): def setStatus(self, statusText):
u""" """
Send status to whatsapp Send status to whatsapp
Args: Args:
@ -254,14 +254,14 @@ class YowsupApp(object):
self.sendIq(iq) self.sendIq(iq)
def sendTyping(self, phoneNumber, typing): def sendTyping(self, phoneNumber, typing):
u""" """
Notify buddy using phoneNumber that you are typing to him Notify buddy using phoneNumber that you are typing to him
Args: Args:
- phoneNumber: (str) cellphone number of the buddy you are typing to. - phoneNumber: (str) cellphone number of the buddy you are typing to.
- typing: (bool) True if you are typing, False if you are not - typing: (bool) True if you are typing, False if you are not
""" """
jid = phoneNumber + u'@s.whatsapp.net' jid = phoneNumber + '@s.whatsapp.net'
if typing: if typing:
state = OutgoingChatstateProtocolEntity( state = OutgoingChatstateProtocolEntity(
ChatstateProtocolEntity.STATE_TYPING, jid ChatstateProtocolEntity.STATE_TYPING, jid
@ -273,7 +273,7 @@ class YowsupApp(object):
self.sendEntity(state) self.sendEntity(state)
def sendSync(self, contacts, delta = False, interactive = True): def sendSync(self, contacts, delta = False, interactive = True):
u""" """
You need to sync new contacts before you interact with You need to sync new contacts before you interact with
them, failure to do so could result in a temporary ban. them, failure to do so could result in a temporary ban.
@ -293,7 +293,7 @@ class YowsupApp(object):
self.sendIq(iq) self.sendIq(iq)
def requestStatuses(self, contacts, success = None, failure = None): def requestStatuses(self, contacts, success = None, failure = None):
u""" """
Request the statuses of a number of users. Request the statuses of a number of users.
Args: Args:
@ -302,19 +302,19 @@ class YowsupApp(object):
- success: (func) called when request is successful - success: (func) called when request is successful
- failure: (func) called when request has failed - failure: (func) called when request has failed
""" """
iq = GetStatusesIqProtocolEntity([c + u'@s.whatsapp.net' for c in contacts]) iq = GetStatusesIqProtocolEntity([c + '@s.whatsapp.net' for c in contacts])
def onSuccess(response, request): def onSuccess(response, request):
self.logger.debug(u"Received Statuses %s", response) self.logger.debug("Received Statuses %s", response)
s = {} s = {}
for k, v in response.statuses.iteritems(): for k, v in response.statuses.iteritems():
s[k.split(u'@')[0]] = v s[k.split('@')[0]] = v
success(s) success(s)
self.sendIq(iq, onSuccess = onSuccess, onError = failure) self.sendIq(iq, onSuccess = onSuccess, onError = failure)
def requestLastSeen(self, phoneNumber, success = None, failure = None): def requestLastSeen(self, phoneNumber, success = None, failure = None):
u""" """
Requests when user was last seen. Requests when user was last seen.
Args: Args:
- phone_number: (str) the phone number of the user - phone_number: (str) the phone number of the user
@ -323,22 +323,22 @@ class YowsupApp(object):
since last seen. since last seen.
- failure: (func) called when request has failed - failure: (func) called when request has failed
""" """
iq = LastseenIqProtocolEntity(phoneNumber + u'@s.whatsapp.net') iq = LastseenIqProtocolEntity(phoneNumber + '@s.whatsapp.net')
self.sendIq(iq, onSuccess = partial(self._lastSeenSuccess, success), self.sendIq(iq, onSuccess = partial(self._lastSeenSuccess, success),
onError = failure) onError = failure)
def _lastSeenSuccess(self, success, response, request): def _lastSeenSuccess(self, success, response, request):
success(response._from.split(u'@')[0], response.seconds) success(response._from.split('@')[0], response.seconds)
def requestProfilePicture(self, phoneNumber, onSuccess = None, onFailure = None): def requestProfilePicture(self, phoneNumber, onSuccess = None, onFailure = None):
u""" """
Requests profile picture of whatsapp user Requests profile picture of whatsapp user
Args: Args:
- phoneNumber: (str) the phone number of the user - phoneNumber: (str) the phone number of the user
- onSuccess: (func) called when request is successfully processed. - onSuccess: (func) called when request is successfully processed.
- onFailure: (func) called when request has failed - onFailure: (func) called when request has failed
""" """
iq = GetPictureIqProtocolEntity(phoneNumber + u'@s.whatsapp.net') iq = GetPictureIqProtocolEntity(phoneNumber + '@s.whatsapp.net')
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure) self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
def requestGroupsList(self, onSuccess = None, onFailure = None): def requestGroupsList(self, onSuccess = None, onFailure = None):
@ -346,7 +346,7 @@ class YowsupApp(object):
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure) self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
def requestGroupInfo(self, group, onSuccess = None, onFailure = None): def requestGroupInfo(self, group, onSuccess = None, onFailure = None):
u""" """
Request info on a specific group (includes participants, subject, owner etc.) Request info on a specific group (includes participants, subject, owner etc.)
Args: Args:
@ -354,11 +354,11 @@ class YowsupApp(object):
- onSuccess: (func) called when request is successfully processed. - onSuccess: (func) called when request is successfully processed.
- onFailure: (func) called when request is has failed - onFailure: (func) called when request is has failed
""" """
iq = InfoGroupsIqProtocolEntity(group + u'@g.us') iq = InfoGroupsIqProtocolEntity(group + '@g.us')
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure) self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t): def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t):
u""" """
Called when login is successful. Called when login is successful.
Args: Args:
@ -373,7 +373,7 @@ class YowsupApp(object):
pass pass
def onAuthFailure(self, reason): def onAuthFailure(self, reason):
u""" """
Called when login is a failure Called when login is a failure
Args: Args:
@ -382,7 +382,7 @@ class YowsupApp(object):
pass pass
def onReceipt(self, _id, _from, timestamp, type, participant, offline, items): def onReceipt(self, _id, _from, timestamp, type, participant, offline, items):
u""" """
Called when a receipt is received (double tick or blue tick) Called when a receipt is received (double tick or blue tick)
Args Args
@ -398,7 +398,7 @@ class YowsupApp(object):
pass pass
def onAck(self, _id,_class, _from, timestamp): def onAck(self, _id,_class, _from, timestamp):
u""" """
Called when Ack is received Called when Ack is received
Args: Args:
@ -410,7 +410,7 @@ class YowsupApp(object):
pass pass
def onPresenceReceived(self, _type, name, _from, last): def onPresenceReceived(self, _type, name, _from, last):
u""" """
Called when presence (e.g. available, unavailable) is received Called when presence (e.g. available, unavailable) is received
from whatsapp from whatsapp
@ -423,12 +423,12 @@ class YowsupApp(object):
pass pass
def onDisconnect(self): def onDisconnect(self):
u""" """
Called when disconnected from whatsapp Called when disconnected from whatsapp
""" """
def onContactTyping(self, number): def onContactTyping(self, number):
u""" """
Called when contact starts to type Called when contact starts to type
Args: Args:
@ -437,7 +437,7 @@ class YowsupApp(object):
pass pass
def onContactPaused(self, number): def onContactPaused(self, number):
u""" """
Called when contact stops typing Called when contact stops typing
Args: Args:
@ -446,7 +446,7 @@ class YowsupApp(object):
pass pass
def onTextMessage(self, _id, _from, to, notify, timestamp, participant, offline, retry, body): def onTextMessage(self, _id, _from, to, notify, timestamp, participant, offline, retry, body):
u""" """
Called when text message is received Called when text message is received
Args: Args:
@ -463,7 +463,7 @@ class YowsupApp(object):
pass pass
def onImage(self, entity): def onImage(self, entity):
u""" """
Called when image message is received Called when image message is received
Args: Args:
@ -472,7 +472,7 @@ class YowsupApp(object):
pass pass
def onAudio(self, entity): def onAudio(self, entity):
u""" """
Called when audio message is received Called when audio message is received
Args: Args:
@ -482,7 +482,7 @@ class YowsupApp(object):
def onVideo(self, entity): def onVideo(self, entity):
u""" """
Called when video message is received Called when video message is received
Args: Args:
@ -491,7 +491,7 @@ class YowsupApp(object):
pass pass
def onLocation(self, entity): def onLocation(self, entity):
u""" """
Called when location message is received Called when location message is received
Args: Args:
@ -500,7 +500,7 @@ class YowsupApp(object):
pass pass
def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant): def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant):
u""" """
Called when VCard message is received Called when VCard message is received
Args: Args:
@ -516,15 +516,15 @@ class YowsupApp(object):
pass pass
def onAddedToGroup(self, entity): def onAddedToGroup(self, entity):
u"""Called when the user has been added to a new group""" """Called when the user has been added to a new group"""
pass pass
def onParticipantsAddedToGroup(self, entity): def onParticipantsAddedToGroup(self, entity):
u"""Called when participants have been added to a group""" """Called when participants have been added to a group"""
pass pass
def onParticipantsRemovedFromGroup(self, group, participants): def onParticipantsRemovedFromGroup(self, group, participants):
u"""Called when participants have been removed from a group """Called when participants have been removed from a group
Args: Args:
- group: (str) id of the group (e.g. 27831788123-144024456) - group: (str) id of the group (e.g. 27831788123-144024456)
@ -533,7 +533,7 @@ class YowsupApp(object):
pass pass
def sendEntity(self, entity): def sendEntity(self, entity):
u"""Sends an entity down the stack (as if YowsupAppLayer called toLower)""" """Sends an entity down the stack (as if YowsupAppLayer called toLower)"""
self.stack.broadcastEvent(YowLayerEvent(YowsupAppLayer.TO_LOWER_EVENT, self.stack.broadcastEvent(YowLayerEvent(YowsupAppLayer.TO_LOWER_EVENT,
entity = entity entity = entity
)) ))
@ -551,9 +551,9 @@ class YowsupApp(object):
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
class YowsupAppLayer(YowInterfaceLayer): class YowsupAppLayer(YowInterfaceLayer):
EVENT_START = u'transwhat.event.YowsupAppLayer.start' EVENT_START = 'transwhat.event.YowsupAppLayer.start'
TO_LOWER_EVENT = u'transwhat.event.YowsupAppLayer.toLower' TO_LOWER_EVENT = 'transwhat.event.YowsupAppLayer.toLower'
SEND_IQ = u'transwhat.event.YowsupAppLayer.sendIq' SEND_IQ = 'transwhat.event.YowsupAppLayer.sendIq'
def onEvent(self, layerEvent): def onEvent(self, layerEvent):
# We cannot pass instance varaibles in through init, so we use an event # We cannot pass instance varaibles in through init, so we use an event
@ -561,24 +561,24 @@ class YowsupAppLayer(YowInterfaceLayer):
# Return False if you want the event to propogate down the stack # Return False if you want the event to propogate down the stack
# return True otherwise # return True otherwise
if layerEvent.getName() == YowsupAppLayer.EVENT_START: if layerEvent.getName() == YowsupAppLayer.EVENT_START:
self.caller = layerEvent.getArg(u'caller') self.caller = layerEvent.getArg('caller')
self.logger = logging.getLogger(self.__class__.__name__) self.logger = logging.getLogger(self.__class__.__name__)
return True return True
elif layerEvent.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECTED: elif layerEvent.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECTED:
self.caller.onDisconnect() self.caller.onDisconnect()
return True return True
elif layerEvent.getName() == YowsupAppLayer.TO_LOWER_EVENT: elif layerEvent.getName() == YowsupAppLayer.TO_LOWER_EVENT:
self.toLower(layerEvent.getArg(u'entity')) self.toLower(layerEvent.getArg('entity'))
return True return True
elif layerEvent.getName() == YowsupAppLayer.SEND_IQ: elif layerEvent.getName() == YowsupAppLayer.SEND_IQ:
iq = layerEvent.getArg(u'iq') iq = layerEvent.getArg('iq')
success = layerEvent.getArg(u'success') success = layerEvent.getArg('success')
failure = layerEvent.getArg(u'failure') failure = layerEvent.getArg('failure')
self._sendIq(iq, success, failure) self._sendIq(iq, success, failure)
return True return True
return False return False
@ProtocolEntityCallback(u'success') @ProtocolEntityCallback('success')
def onAuthSuccess(self, entity): def onAuthSuccess(self, entity):
# entity is SuccessProtocolEntity # entity is SuccessProtocolEntity
status = entity.status status = entity.status
@ -587,21 +587,21 @@ class YowsupAppLayer(YowInterfaceLayer):
expiration = entity.expiration expiration = entity.expiration
props = entity.props props = entity.props
nonce = entity.nonce nonce = entity.nonce
t = entity.t # I donu't know what this is t = entity.t # I don't know what this is
self.caller.onAuthSuccess(status, kind, creation, expiration, props, nonce, t) self.caller.onAuthSuccess(status, kind, creation, expiration, props, nonce, t)
@ProtocolEntityCallback('failureu') @ProtocolEntityCallback('failure')
def onAuthFailure(self, entity): def onAuthFailure(self, entity):
# entity is FailureProtocolEntity # entity is FailureProtocolEntity
reason = entity.reason reason = entity.reason
self.caller.onAuthFailure(reason) self.caller.onAuthFailure(reason)
@ProtocolEntityCallback('receiptu') @ProtocolEntityCallback('receipt')
def onReceipt(self, entity): def onReceipt(self, entity):
"""Sends ack automatically""" """Sends ack automatically"""
# entity is IncomingReceiptProtocolEntity # entity is IncomingReceiptProtocolEntity
ack = OutgoingAckProtocolEntity(entity.getId(), ack = OutgoingAckProtocolEntity(entity.getId(),
'receiptu', entity.getType(), entity.getFrom()) 'receipt', entity.getType(), entity.getFrom())
self.toLower(ack) self.toLower(ack)
_id = entity._id _id = entity._id
_from = entity._from _from = entity._from
@ -612,7 +612,7 @@ class YowsupAppLayer(YowInterfaceLayer):
items = entity.items items = entity.items
self.caller.onReceipt(_id, _from, timestamp, type, participant, offline, items) self.caller.onReceipt(_id, _from, timestamp, type, participant, offline, items)
@ProtocolEntityCallback('acku') @ProtocolEntityCallback('ack')
def onAck(self, entity): def onAck(self, entity):
# entity is IncomingAckProtocolEntity # entity is IncomingAckProtocolEntity
self.caller.onAck( self.caller.onAck(
@ -622,7 +622,7 @@ class YowsupAppLayer(YowInterfaceLayer):
entity.timestamp entity.timestamp
) )
@ProtocolEntityCallback('notificationu') @ProtocolEntityCallback('notification')
def onNotification(self, entity): def onNotification(self, entity):
""" """
Sends ack automatically Sends ack automatically
@ -635,11 +635,11 @@ class YowsupAppLayer(YowInterfaceLayer):
self.caller.onParticipantsAddedToGroup(entity) self.caller.onParticipantsAddedToGroup(entity)
elif isinstance(entity, RemoveGroupsNotificationProtocolEntity): elif isinstance(entity, RemoveGroupsNotificationProtocolEntity):
self.caller.onParticipantsRemovedFromGroup( self.caller.onParticipantsRemovedFromGroup(
entity.getGroupId().split('@u')[0], entity.getGroupId().split('@')[0],
entity.getParticipants().keys() entity.getParticipants().keys()
) )
@ProtocolEntityCallback('messageu') @ProtocolEntityCallback('message')
def onMessageReceived(self, entity): def onMessageReceived(self, entity):
self.logger.debug("Received Message: %s", entity) self.logger.debug("Received Message: %s", entity)
if entity.getType() == MessageProtocolEntity.MESSAGE_TYPE_TEXT: if entity.getType() == MessageProtocolEntity.MESSAGE_TYPE_TEXT:
@ -677,7 +677,7 @@ class YowsupAppLayer(YowInterfaceLayer):
elif isinstance(entity, LocationMediaMessageProtocolEntity): elif isinstance(entity, LocationMediaMessageProtocolEntity):
self.caller.onLocation(entity) self.caller.onLocation(entity)
@ProtocolEntityCallback('presenceu') @ProtocolEntityCallback('presence')
def onPresenceReceived(self, presence): def onPresenceReceived(self, presence):
_type = presence.getType() _type = presence.getType()
name = presence.getName() name = presence.getName()
@ -685,7 +685,7 @@ class YowsupAppLayer(YowInterfaceLayer):
last = presence.getLast() last = presence.getLast()
self.caller.onPresenceReceived(_type, name, _from, last) self.caller.onPresenceReceived(_type, name, _from, last)
@ProtocolEntityCallback('chatstateu') @ProtocolEntityCallback('chatstate')
def onChatstate(self, chatstate): def onChatstate(self, chatstate):
number = chatstate._from.split('@')[0] number = chatstate._from.split('@')[0]
if chatstate.getState() == ChatstateProtocolEntity.STATE_TYPING: if chatstate.getState() == ChatstateProtocolEntity.STATE_TYPING: