Use unicode string literals

This commit is contained in:
moyamo 2015-12-29 21:03:14 +02:00
parent 4093568234
commit fae4c648ee
10 changed files with 400 additions and 401 deletions

View file

@ -262,7 +262,6 @@ 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

40
bot.py
View file

@ -1,10 +1,10 @@
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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 = "Bot"): def __init__(self, session, name = u"Bot"):
self.session = session self.session = session
self.name = name self.name = name
self.commands = { self.commands = {
"help": self._help, u"help": self._help,
"prune": self._prune, u"prune": self._prune,
"groups": self._groups, u"groups": self._groups,
"getgroups": self._getgroups u"getgroups": self._getgroups
} }
def parse(self, message): def parse(self, message):
args = message.split(" ") args = message.split(u" ")
cmd = args.pop(0) cmd = args.pop(0)
if cmd[0] == '\\': if cmd[0] == u'\\':
try: try:
self.call(cmd[1:], args) self.call(cmd[1:], args)
except KeyError: except KeyError:
self.send("invalid command") self.send(u"invalid command")
except TypeError: except TypeError:
self.send("invalid syntax") self.send(u"invalid syntax")
else: else:
self.send("a valid command starts with a backslash") self.send(u"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("""following bot commands are available: self.send(u"""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("buddy list cleared") self.send(u"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 + "@" + self.session.backend.spectrum_jid + " " + self.session.groups[group].subject + " Owner: " + nick ) self.send(self.session.groups[group].id + u"@" + self.session.backend.spectrum_jid + u" " + self.session.groups[group].subject + u" Owner: " + nick )
def _getgroups(self): def _getgroups(self):
#self.session.call("group_getGroups", ("participating",)) #self.session.call(u"group_getGroups", (u"participating",))
self.session.requestGroupsList(self.session._updateGroups) self.session.requestGroupsList(self.session._updateGroups)

View file

@ -1,10 +1,10 @@
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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
@ -33,7 +33,7 @@ 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 "" self.image_hash = image_hash if image_hash is not None else u""
self.statusMsg = u"" self.statusMsg = u""
self.lastseen = 0 self.lastseen = 0
self.presence = 0 self.presence = 0
@ -46,7 +46,7 @@ class Buddy():
self.image_hash = image_hash self.image_hash = image_hash
def __str__(self): def __str__(self):
return "%s (nick=%s)" % (self.number, self.nick) return u"%s (nick=%s)" % (self.number, self.nick)
class BuddyList(dict): class BuddyList(dict):
@ -62,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('utf-8') statusMsg = buddy.statusMessage.decode(u'utf-8')
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("Update roster") self.logger.debug(u"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('bot') contacts.remove(u'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)
@ -84,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("Roster remove: %s", str(list(remove))) # self.logger.debug(u"Roster remove: %s", str(list(remove)))
self.logger.debug("Roster add: %s", str(list(contacts))) self.logger.debug(u"Roster add: %s", str(list(contacts)))
# for number in remove: # for number in remove:
# self.backend.handleBuddyChanged(self.user, number, "", [], # self.backend.handleBuddyChanged(self.user, number, u"", [],
# 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)
@ -97,16 +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 "") iconHash = buddy.image_hash if buddy.image_hash is not None else u"")
self.session.subscribePresence(number) self.session.subscribePresence(number)
self.logger.debug("%s is requesting statuses of: %s", self.user, contacts) self.logger.debug(u"%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("%s received statuses of: %s", self.user, contacts) self.logger.debug(u"%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]
buddy.statusMsg = status.decode('utf-8') buddy.statusMsg = status.decode(u'utf-8')
self.updateSpectrum(buddy) self.updateSpectrum(buddy)
@ -124,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, "", groups, image_hash) buddy = Buddy(self.owner, number, nick, u"", groups, image_hash)
self[number] = buddy self[number] = buddy
self.logger.debug("Roster add: %s", buddy) self.logger.debug(u"Roster add: %s", buddy)
self.updateSpectrum(buddy) self.updateSpectrum(buddy)
return buddy return buddy
@ -134,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 == 'unavailable': elif buddy.presence == u'unavailable':
status = protocol_pb2.STATUS_AWAY status = protocol_pb2.STATUS_AWAY
else: else:
status = protocol_pb2.STATUS_ONLINE status = protocol_pb2.STATUS_ONLINE
@ -142,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("\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp) statusmsg += time.strftime(u"\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 "") iconHash = buddy.image_hash if buddy.image_hash is not None else u"")
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, "", [], self.backend.handleBuddyChanged(self.user, number, u"", [],
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__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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
@ -34,12 +34,12 @@ class Group():
self.backend = backend self.backend = backend
self.user = user self.user = user
self.nick = "me" self.nick = u"me"
# Participants is a number -> nickname dict # Participants is a number -> nickname dict
self.participants = {} self.participants = {}
def addParticipants(self, participants, buddies, yourNumber): def addParticipants(self, participants, buddies, yourNumber):
""" u"""
Adds participants to the group. Adds participants to the group.
Args: Args:
@ -48,14 +48,14 @@ class Group():
- yourNumber: The number you are using - yourNumber: The number you are using
""" """
for jid in participants: for jid in participants:
number = jid.split('@')[0] number = jid.split(u'@')[0]
try: try:
nick = buddies[number].nick nick = buddies[number].nick
except KeyError: except KeyError:
nick = number nick = number
if number == yourNumber: if number == yourNumber:
nick = self.nick nick = self.nick
if nick == "": if nick == u"":
nick = number nick = number
self.participants[number] = nick self.participants[number] = nick
@ -72,7 +72,7 @@ class Group():
def removeParticipants(self, participants): def removeParticipants(self, participants):
for jid in participants: for jid in participants:
number = jid.split('@')[0] number = jid.split(u'@')[0]
nick = self.participants[number] nick = self.participants[number]
flags = protocol_pb2.PARTICIPANT_FLAG_NONE flags = protocol_pb2.PARTICIPANT_FLAG_NONE
self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE) self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE)
@ -88,7 +88,7 @@ class Group():
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, new_nick) self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, new_nick)
self.participants[number] = new_nick self.participants[number] = new_nick
def _updateParticipant(self, number, flags, status, newNick = ""): def _updateParticipant(self, number, flags, status, newNick = u""):
nick = self.participants[number] nick = self.participants[number]
# Notice the status message is the buddy's number # Notice the status message is the buddy's number
if self.joined: if self.joined:

View file

@ -1,10 +1,10 @@
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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 @@ __email__ = "post@steffenvogel.de"
import time import time
def get_token(number, timeout = 30): def get_token(number, timeout = 30):
file = open('tokens') file = open(u'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 ["", "\n"]: if line in [u"", u"\n"]:
time.sleep(1) time.sleep(1)
count += 1 count += 1
continue continue
else: else:
t, n, tk = line[:-1].split("\t") t, n, tk = line[:-1].split(u"\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("4917696978528") print get_token(u"4917696978528")

View file

@ -1,10 +1,10 @@
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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
@ -56,14 +56,14 @@ class Session(YowsupApp):
def __init__(self, backend, user, legacyName, extra): def __init__(self, backend, user, legacyName, extra):
super(Session, self).__init__() super(Session, self).__init__()
self.logger = logging.getLogger(self.__class__.__name__) self.logger = logging.getLogger(self.__class__.__name__)
self.logger.info("Created: %s", legacyName) self.logger.info(u"Created: %s", legacyName)
self.backend = backend self.backend = backend
self.user = user self.user = user
self.legacyName = legacyName self.legacyName = legacyName
self.status = protocol_pb2.STATUS_NONE self.status = protocol_pb2.STATUS_NONE
self.statusMessage = '' self.statusMessage = u''
self.groups = {} self.groups = {}
self.gotGroupList = False self.gotGroupList = False
@ -86,21 +86,21 @@ class Session(YowsupApp):
self.bot = Bot(self) self.bot = Bot(self)
self.imgMsgId = None self.imgMsgId = None
self.imgPath = "" self.imgPath = u""
self.imgBuddy = None self.imgBuddy = None
self.imgType = "" self.imgType = u""
def __del__(self): # handleLogoutRequest def __del__(self): # handleLogoutRequest
self.logout() self.logout()
def logout(self): def logout(self):
self.logger.info("%s logged out", self.user) self.logger.info(u"%s logged out", self.user)
super(Session, self).logout() super(Session, self).logout()
self.loggedIn = False self.loggedIn = False
def login(self, password): def login(self, password):
self.logger.info("%s attempting login", self.user) self.logger.info(u"%s attempting login", self.user)
self.password = password self.password = password
self.shouldBeConncted = True self.shouldBeConncted = True
super(Session, self).login(self.legacyName, self.password) super(Session, self).login(self.legacyName, self.password)
@ -108,33 +108,33 @@ class Session(YowsupApp):
def _shortenGroupId(self, gid): def _shortenGroupId(self, gid):
# FIXME: might have problems if number begins with 0 # FIXME: might have problems if number begins with 0
return gid return gid
# return '-'.join(hex(int(s))[2:] for s in gid.split('-')) # return u'-'.join(hex(int(s))[2:] for s in gid.split(u'-'))
def _lengthenGroupId(self, gid): def _lengthenGroupId(self, gid):
return gid return gid
# FIXME: might have problems if number begins with 0 # FIXME: might have problems if number begins with 0
# return '-'.join(str(int(s, 16)) for s in gid.split('-')) # return u'-'.join(str(int(s, 16)) for s in gid.split(u'-'))
def updateRoomList(self): def updateRoomList(self):
rooms = [] rooms = []
text = [] text = []
for room, group in self.groups.iteritems(): for room, group in self.groups.iteritems():
rooms.append([self._shortenGroupId(room), group.subject]) rooms.append([self._shortenGroupId(room), group.subject])
text.append(self._shortenGroupId(room) + '@' + self.backend.spectrum_jid + ' :' + group.subject) text.append(self._shortenGroupId(room) + u'@' + self.backend.spectrum_jid + u' :' + group.subject)
self.logger.debug("Got rooms: %s", rooms) self.logger.debug(u"Got rooms: %s", rooms)
self.backend.handleRoomList(rooms) self.backend.handleRoomList(rooms)
message = "Note, you are a participant of the following groups:\n" +\ message = u"Note, you are a participant of the following groups:\n" +\
'\n'.join(text) + '\nIf you do not join them you will lose messages' u'\n'.join(text) + u'\nIf you do not join them you will lose messages'
#self.bot.send(message) #self.bot.send(message)
def _updateGroups(self, response, request): def _updateGroups(self, response, request):
self.logger.debug('Received groups list %s', response) self.logger.debug(u'Received groups list %s', response)
groups = response.getGroups() groups = response.getGroups()
for group in groups: for group in groups:
room = group.getId() room = group.getId()
owner = group.getOwner().split('@')[0] owner = group.getOwner().split(u'@')[0]
subjectOwner = group.getSubjectOwner().split('@')[0] subjectOwner = group.getSubjectOwner().split(u'@')[0]
subject = utils.softToUni(group.getSubject()) subject = utils.softToUni(group.getSubject())
if room in self.groups: if room in self.groups:
@ -144,7 +144,7 @@ class Session(YowsupApp):
oroom.subject = subject oroom.subject = subject
else: else:
self.groups[room] = Group(room, owner, subject, subjectOwner, self.backend, self.user) self.groups[room] = Group(room, owner, subject, subjectOwner, self.backend, self.user)
# self.joinRoom(self._shortenGroupId(room), self.user.split("@")[0]) # self.joinRoom(self._shortenGroupId(room), self.user.split(u"@")[0])
self.groups[room].addParticipants(group.getParticipants().keys(), self.groups[room].addParticipants(group.getParticipants().keys(),
self.buddies, self.legacyName) self.buddies, self.legacyName)
@ -154,8 +154,8 @@ class Session(YowsupApp):
while self.groupOfflineQueue[room]: while self.groupOfflineQueue[room]:
msg = self.groupOfflineQueue[room].pop(0) msg = self.groupOfflineQueue[room].pop(0)
self.backend.handleMessage(self.user, room, msg[1], self.backend.handleMessage(self.user, room, msg[1],
msg[0], "", msg[2]) msg[0], u"", msg[2])
self.logger.debug("Send queued group message to: %s %s %s", self.logger.debug(u"Send queued group message to: %s %s %s",
msg[0],msg[1], msg[2]) msg[0],msg[1], msg[2])
self.gotGroupList = True self.gotGroupList = True
for room, nick in self.joinRoomQueue: for room, nick in self.joinRoomQueue:
@ -169,7 +169,7 @@ class Session(YowsupApp):
return return
room = self._lengthenGroupId(room) room = self._lengthenGroupId(room)
if room in self.groups: if room in self.groups:
self.logger.info("Joining room: %s room=%s, nick=%s", self.logger.info(u"Joining room: %s room=%s, nick=%s",
self.legacyName, room, nick) self.legacyName, room, nick)
group = self.groups[room] group = self.groups[room]
@ -184,24 +184,24 @@ class Session(YowsupApp):
group.sendParticipantsToSpectrum(self.legacyName) group.sendParticipantsToSpectrum(self.legacyName)
self.backend.handleSubject(self.user, self._shortenGroupId(room), self.backend.handleSubject(self.user, self._shortenGroupId(room),
group.subject, ownerNick) group.subject, ownerNick)
self.logger.debug("Room subject: room=%s, subject=%s", self.logger.debug(u"Room subject: room=%s, subject=%s",
room, group.subject) room, group.subject)
self.backend.handleRoomNicknameChanged( self.backend.handleRoomNicknameChanged(
self.user, self._shortenGroupId(room), group.subject self.user, self._shortenGroupId(room), group.subject
) )
else: else:
self.logger.warn("Room doesn't exist: %s", room) self.logger.warn(u"Room doesn't exist: %s", room)
def leaveRoom(self, room): def leaveRoom(self, room):
if room in self.groups: if room in self.groups:
self.logger.info("Leaving room: %s room=%s", self.legacyName, room) self.logger.info(u"Leaving room: %s room=%s", self.legacyName, room)
group = self.groups[room] group = self.groups[room]
group.joined = False group.joined = False
else: else:
self.logger.warn("Room doesn't exist: %s. Unable to leave.", room) self.logger.warn(u"Room doesn't exist: %s. Unable to leave.", room)
def _lastSeen(self, number, seconds): def _lastSeen(self, number, seconds):
self.logger.debug("Last seen %s at %s seconds" % (number, str(seconds))) self.logger.debug(u"Last seen %s at %s seconds" % (number, str(seconds)))
if seconds < 60: if seconds < 60:
self.onPresenceAvailable(number) self.onPresenceAvailable(number)
else: else:
@ -210,43 +210,43 @@ class Session(YowsupApp):
# Called by superclass # Called by superclass
def onAuthSuccess(self, status, kind, creation, def onAuthSuccess(self, status, kind, creation,
expiration, props, nonce, t): expiration, props, nonce, t):
self.logger.info("Auth success: %s", self.user) self.logger.info(u"Auth success: %s", self.user)
self.backend.handleConnected(self.user) self.backend.handleConnected(self.user)
self.backend.handleBuddyChanged(self.user, "bot", self.bot.name, self.backend.handleBuddyChanged(self.user, u"bot", self.bot.name,
["Admin"], protocol_pb2.STATUS_ONLINE) [u"Admin"], protocol_pb2.STATUS_ONLINE)
if self.initialized == False: if self.initialized == False:
self.sendOfflineMessages() self.sendOfflineMessages()
#self.bot.call("welcome") #self.bot.call(u"welcome")
self.initialized = True self.initialized = True
self.sendPresence(True) self.sendPresence(True)
for func in self.loginQueue: for func in self.loginQueue:
func() func()
self.logger.debug('Requesting groups list') self.logger.debug(u'Requesting groups list')
self.requestGroupsList(self._updateGroups) self.requestGroupsList(self._updateGroups)
self.loggedIn = True self.loggedIn = True
# Called by superclass # Called by superclass
def onAuthFailed(self, reason): def onAuthFailed(self, reason):
self.logger.info("Auth failed: %s (%s)", self.user, reason) self.logger.info(u"Auth failed: %s (%s)", self.user, reason)
self.backend.handleDisconnected(self.user, 0, reason) self.backend.handleDisconnected(self.user, 0, reason)
self.password = None self.password = None
self.loggedIn = False self.loggedIn = False
# Called by superclass # Called by superclass
def onDisconnect(self): def onDisconnect(self):
self.logger.debug('Disconnected') self.logger.debug(u'Disconnected')
self.backend.handleDisconnected(self.user, 0, 'Disconnected for unknown reasons') self.backend.handleDisconnected(self.user, 0, u'Disconnected for unknown reasons')
# Called by superclass # Called by superclass
def onReceipt(self, _id, _from, timestamp, type, participant, offline, items): def onReceipt(self, _id, _from, timestamp, type, participant, offline, items):
self.logger.debug("received receipt, sending ack: " + self.logger.debug(u"received receipt, sending ack: " +
' '.join(map(str, [_id, _from, timestamp, u' '.join(map(str, [_id, _from, timestamp,
type, participant, offline, items])) type, participant, offline, items]))
) )
try: try:
buddy = self.buddies[_from.split('@')[0]] buddy = self.buddies[_from.split(u'@')[0]]
#self.backend.handleBuddyChanged(self.user, buddy.number.number, #self.backend.handleBuddyChanged(self.user, buddy.number.number,
# buddy.nick, buddy.groups, protocol_pb2.STATUS_ONLINE) # buddy.nick, buddy.groups, protocol_pb2.STATUS_ONLINE)
self.backend.handleMessageAck(self.user, buddy.number, self.msgIDs[_id].xmppId) self.backend.handleMessageAck(self.user, buddy.number, self.msgIDs[_id].xmppId)
@ -259,47 +259,47 @@ class Session(YowsupApp):
# Called by superclass # Called by superclass
def onAck(self, _id, _class, _from, timestamp): def onAck(self, _id, _class, _from, timestamp):
self.logger.debug('received ack ' + self.logger.debug(u'received ack ' +
' '.join(map(str, [_id, _class, _from,timestamp,])) u' '.join(map(str, [_id, _class, _from,timestamp,]))
) )
# Called by superclass # Called by superclass
def onTextMessage(self, _id, _from, to, notify, timestamp, participant, def onTextMessage(self, _id, _from, to, notify, timestamp, participant,
offline, retry, body): offline, retry, body):
self.logger.debug('received TextMessage' + self.logger.debug(u'received TextMessage' +
' '.join(map(str, [ u' '.join(map(str, [
_id, _from, to, notify, timestamp, _id, _from, to, notify, timestamp,
participant, offline, retry, body participant, offline, retry, body
])) ]))
) )
buddy = _from.split('@')[0] buddy = _from.split(u'@')[0]
messageContent = utils.softToUni(body) messageContent = utils.softToUni(body)
self.sendReceipt(_id, _from, None, participant) self.sendReceipt(_id, _from, None, participant)
self.logger.info("Message received from %s to %s: %s (at ts=%s)", self.logger.info(u"Message received from %s to %s: %s (at ts=%s)",
buddy, self.legacyName, messageContent, timestamp) buddy, self.legacyName, messageContent, timestamp)
if participant is not None: # Group message if participant is not None: # Group message
partname = participant.split('@')[0] partname = participant.split(u'@')[0]
self.sendGroupMessageToXMPP(buddy, partname, messageContent, self.sendGroupMessageToXMPP(buddy, partname, messageContent,
timestamp) timestamp)
else: else:
self.sendMessageToXMPP(buddy, messageContent, timestamp) self.sendMessageToXMPP(buddy, messageContent, timestamp)
# isBroadcast always returns false, I'm not sure how to get a broadcast # isBroadcast always returns false, Iu'm not sure how to get a broadcast
# message. # message.
#if messageEntity.isBroadcast(): #if messageEntity.isBroadcast():
# self.logger.info("Broadcast received from %s to %s: %s (at ts=%s)",\ # self.logger.info(u"Broadcast received from %s to %s: %s (at ts=%s)",\
# buddy, self.legacyName, messageContent, timestamp) # buddy, self.legacyName, messageContent, timestamp)
# messageContent = "[Broadcast] " + messageContent # messageContent = u"[Broadcast] " + messageContent
# Called by superclass # Called by superclass
def onImage(self, image): def onImage(self, image):
self.logger.debug('Received image message %s', str(image)) self.logger.debug('Received image message %su', str(image))
buddy = image._from.split('@')[0] buddy = image._from.split('@u')[0]
participant = image.participant participant = image.participant
if image.caption is None: if image.caption is None:
image.caption = '' image.caption = 'u'
message = image.url + ' ' + image.caption message = image.url + ' u' + image.caption
if participant is not None: # Group message if participant is not None: # Group message
partname = participant.split('@')[0] partname = participant.split('@u')[0]
self.sendGroupMessageToXMPP(buddy, partname, message, image.timestamp) self.sendGroupMessageToXMPP(buddy, partname, message, image.timestamp)
else: else:
@ -308,12 +308,12 @@ class Session(YowsupApp):
# Called by superclass # Called by superclass
def onAudio(self, audio): def onAudio(self, audio):
self.logger.debug('Received audio message %s', str(audio)) self.logger.debug('Received audio message %su', str(audio))
buddy = audio._from.split('@')[0] buddy = audio._from.split('@u')[0]
participant = audio.participant participant = audio.participant
message = audio.url message = audio.url
if participant is not None: # Group message if participant is not None: # Group message
partname = participant.split('@')[0] partname = participant.split('@u')[0]
self.sendGroupMessageToXMPP(buddy, partname, message, audio.timestamp) self.sendGroupMessageToXMPP(buddy, partname, message, audio.timestamp)
else: else:
@ -322,13 +322,13 @@ class Session(YowsupApp):
# Called by superclass # Called by superclass
def onVideo(self, video): def onVideo(self, video):
self.logger.debug('Received video message %s', str(video)) self.logger.debug('Received video message %su', str(video))
buddy = video._from.split('@')[0] buddy = video._from.split('@u')[0]
participant = video.participant participant = video.participant
message = video.url message = video.url
if participant is not None: # Group message if participant is not None: # Group message
partname = participant.split('@')[0] partname = participant.split('@u')[0]
self.sendGroupMessageToXMPP(buddy, partname, message, video.timestamp) self.sendGroupMessageToXMPP(buddy, partname, message, video.timestamp)
else: else:
@ -336,57 +336,57 @@ class Session(YowsupApp):
self.sendReceipt(video._id, video._from, None, video.participant) self.sendReceipt(video._id, video._from, None, video.participant)
def onLocation(self, location): def onLocation(self, location):
buddy = location._from.split('@')[0] buddy = location._from.split('@u')[0]
latitude = location.getLatitude() latitude = location.getLatitude()
longitude = location.getLongitude() longitude = location.getLongitude()
url = location.getLocationUrl() url = location.getLocationUrl()
participant = location.participant participant = location.participant
self.logger.debug("Location received from %s: %s, %s", self.logger.debug(u"Location received from %s: %s, %s",
buddy, latitude, longitude) buddy, latitude, longitude)
if participant is not None: # Group message if participant is not None: # Group message
partname = participant.split('@')[0] partname = participant.split('@u')[0]
self.sendGroupMessageToXMPP(buddy, partname, url, location.timestamp) self.sendGroupMessageToXMPP(buddy, partname, url, location.timestamp)
self.sendGroupMessageToXMPP(buddy, partname, 'geo:' + latitude + ',' + longitude, self.sendGroupMessageToXMPP(buddy, partname, 'geo:u' + latitude + ',u' + longitude,
location.timestamp) location.timestamp)
else: else:
self.sendMessageToXMPP(buddy, url, location.timestamp) self.sendMessageToXMPP(buddy, url, location.timestamp)
self.sendMessageToXMPP(buddy, 'geo:' + latitude + ',' + longitude, self.sendMessageToXMPP(buddy, 'geo:u' + latitude + ',u' + longitude,
location.timestamp) location.timestamp)
self.sendReceipt(location._id, location._from, None, location.participant, location.timestamp) self.sendReceipt(location._id, location._from, None, location.participant, location.timestamp)
# Called by superclass # Called by superclass
def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant): def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant):
self.logger.debug('received VCard' + self.logger.debug('received VCardu' +
' '.join(map(str, [ ' u'.join(map(str, [
_id, _from, name, card_data, to, notify, timestamp, participant _id, _from, name, card_data, to, notify, timestamp, participant
])) ]))
) )
buddy = _from.split("@")[0] buddy = _from.split(u"@")[0]
if participant is not None: # Group message if participant is not None: # Group message
partname = participant.split('@')[0] partname = participant.split('@u')[0]
self.sendGroupMessageToXMPP(buddy, partname, "Received VCard (not implemented yet)", timestamp) self.sendGroupMessageToXMPP(buddy, partname, u"Received VCard (not implemented yet)", timestamp)
else: else:
self.sendMessageToXMPP(buddy, "Received VCard (not implemented yet)") self.sendMessageToXMPP(buddy, u"Received VCard (not implemented yet)")
# self.sendMessageToXMPP(buddy, card_data) # self.sendMessageToXMPP(buddy, card_data)
#self.transferFile(buddy, str(name), card_data) #self.transferFile(buddy, str(name), card_data)
self.sendReceipt(_id, _from, None, participant) self.sendReceipt(_id, _from, None, participant)
def transferFile(self, buddy, name, data): def transferFile(self, buddy, name, data):
# Not working # Not working
self.logger.debug('transfering file %s', name) self.logger.debug('transfering file %su', name)
self.backend.handleFTStart(self.user, buddy, name, len(data)) self.backend.handleFTStart(self.user, buddy, name, len(data))
self.backend.handleFTData(0, data) self.backend.handleFTData(0, data)
self.backend.handleFTFinish(self.user, buddy, name, len(data), 0) self.backend.handleFTFinish(self.user, buddy, name, len(data), 0)
# Called by superclass # Called by superclass
def onContactTyping(self, buddy): def onContactTyping(self, buddy):
self.logger.info("Started typing: %s", buddy) self.logger.info(u"Started typing: %s", buddy)
if buddy != 'bot': if buddy != 'botu':
self.sendPresence(True) self.sendPresence(True)
self.backend.handleBuddyTyping(self.user, buddy) self.backend.handleBuddyTyping(self.user, buddy)
@ -395,15 +395,15 @@ class Session(YowsupApp):
# Called by superclass # Called by superclass
def onContactPaused(self, buddy): def onContactPaused(self, buddy):
self.logger.info("Paused typing: %s", buddy) self.logger.info(u"Paused typing: %s", buddy)
if buddy != 'bot': if buddy != 'botu':
self.backend.handleBuddyTyped(self.user, buddy) self.backend.handleBuddyTyped(self.user, buddy)
self.timer = Timer(3, self.backend.handleBuddyStoppedTyping, self.timer = Timer(3, self.backend.handleBuddyStoppedTyping,
(self.user, buddy)).start() (self.user, buddy)).start()
# Called by superclass # Called by superclass
def onAddedToGroup(self, group): def onAddedToGroup(self, group):
self.logger.debug("Added to group: %s", group) self.logger.debug(u"Added to group: %s", group)
room = group.getGroupId() room = group.getGroupId()
owner = group.getCreatorJid(full = False) owner = group.getCreatorJid(full = False)
subjectOwner = group.getSubjectOwnerJid(full = False) subjectOwner = group.getSubjectOwnerJid(full = False)
@ -411,42 +411,42 @@ class Session(YowsupApp):
self.groups[room] = Group(room, owner, subject, subjectOwner, self.backend, self.user) self.groups[room] = Group(room, owner, subject, subjectOwner, self.backend, self.user)
self.groups[room].addParticipants(group.getParticipants, self.buddies, self.legacyName) self.groups[room].addParticipants(group.getParticipants, self.buddies, self.legacyName)
self.bot.send("You have been added to group: %s@%s (%s)" self.bot.send(u"You have been added to group: %s@%s (%s)"
% (self._shortenGroupId(room), subject, self.backend.spectrum_jid)) % (self._shortenGroupId(room), subject, self.backend.spectrum_jid))
# Called by superclass # Called by superclass
def onParticipantsAddedToGroup(self, group): def onParticipantsAddedToGroup(self, group):
self.logger.debug("Participants added to group: %s", group) self.logger.debug(u"Participants added to group: %s", group)
room = group.getGroupId().split('@')[0] room = group.getGroupId().split('@u')[0]
self.groups[room].addParticipants(group.getParticipants(), self.buddies, self.legacyName) self.groups[room].addParticipants(group.getParticipants(), self.buddies, self.legacyName)
self.groups[room].sendParticipantsToSpectrum(self.legacyName) self.groups[room].sendParticipantsToSpectrum(self.legacyName)
# Called by superclass # Called by superclass
def onParticipantsRemovedFromGroup(self, room, participants): def onParticipantsRemovedFromGroup(self, room, participants):
self.logger.debug("Participants removed from group: %s, %s", self.logger.debug(u"Participants removed from group: %s, %s",
room, participants) room, participants)
self.groups[room].removeParticipants(participants) self.groups[room].removeParticipants(participants)
def onPresenceReceived(self, _type, name, jid, lastseen): def onPresenceReceived(self, _type, name, jid, lastseen):
self.logger.info("Presence received: %s %s %s %s", _type, name, jid, lastseen) self.logger.info(u"Presence received: %s %s %s %s", _type, name, jid, lastseen)
buddy = jid.split("@")[0] buddy = jid.split(u"@")[0]
try: try:
buddy = self.buddies[buddy] buddy = self.buddies[buddy]
except KeyError: except KeyError:
self.logger.error("Buddy not found: %s", buddy) self.logger.error(u"Buddy not found: %s", buddy)
return return
if (lastseen == str(buddy.lastseen)) and (_type == buddy.presence): if (lastseen == str(buddy.lastseen)) and (_type == buddy.presence):
return return
if ((lastseen != "deny") and (lastseen != None) and (lastseen != "none")): if ((lastseen != u"deny") and (lastseen != None) and (lastseen != u"none")):
buddy.lastseen = int(lastseen) buddy.lastseen = int(lastseen)
if (_type == None): if (_type == None):
buddy.lastseen = time.time() buddy.lastseen = time.time()
buddy.presence = _type buddy.presence = _type
if _type == "unavailable": if _type == u"unavailable":
self.onPresenceUnavailable(buddy) self.onPresenceUnavailable(buddy)
else: else:
self.onPresenceAvailable(buddy) self.onPresenceAvailable(buddy)
@ -454,17 +454,17 @@ class Session(YowsupApp):
def onPresenceAvailable(self, buddy): def onPresenceAvailable(self, buddy):
self.logger.info("Is available: %s", buddy) self.logger.info(u"Is available: %s", buddy)
self.buddies.updateSpectrum(buddy) self.buddies.updateSpectrum(buddy)
def onPresenceUnavailable(self, buddy): def onPresenceUnavailable(self, buddy):
self.logger.info("Is unavailable: %s", buddy) self.logger.info(u"Is unavailable: %s", buddy)
self.buddies.updateSpectrum(buddy) self.buddies.updateSpectrum(buddy)
# spectrum RequestMethods # spectrum RequestMethods
def sendTypingStarted(self, buddy): def sendTypingStarted(self, buddy):
if buddy != "bot": if buddy != u"bot":
self.logger.info("Started typing: %s to %s", self.legacyName, buddy) self.logger.info(u"Started typing: %s to %s", self.legacyName, buddy)
self.sendTyping(buddy, True) self.sendTyping(buddy, True)
# If he is typing he is present # If he is typing he is present
# I really don't know where else to put this. # I really don't know where else to put this.
@ -472,26 +472,26 @@ class Session(YowsupApp):
self.sendPresence(True) self.sendPresence(True)
def sendTypingStopped(self, buddy): def sendTypingStopped(self, buddy):
if buddy != "bot": if buddy != u"bot":
self.logger.info("Stopped typing: %s to %s", self.legacyName, buddy) self.logger.info(u"Stopped typing: %s to %s", self.legacyName, buddy)
self.sendTyping(buddy, False) self.sendTyping(buddy, False)
def sendMessageToWA(self, sender, message, ID): def sendMessageToWA(self, sender, message, ID):
self.logger.info("Message sent from %s to %s: %s", self.logger.info(u"Message sent from %s to %s: %s",
self.legacyName, sender, message) self.legacyName, sender, message)
message = message.encode("utf-8") message = message.encode(u"utf-8")
# FIXME: Fragile, should pass this in to onDlerror # FIXME: Fragile, should pass this in to onDlerror
self.dlerror_message = message self.dlerror_message = message
self.dlerror_sender = sender self.dlerror_sender = sender
self.dlerror_ID = ID self.dlerror_ID = ID
# End Fragile # End Fragile
if sender == "bot": if sender == u"bot":
self.bot.parse(message) self.bot.parse(message)
elif "-" in sender: # group msg elif u"-" in sender: # group msg
if "/" in sender: # directed at single user if u"/" in sender: # directed at single user
room, nick = sender.split("/") room, nick = sender.split(u"/")
group = self.groups[room] group = self.groups[room]
number = None number = None
for othernumber, othernick in group.participants.iteritems(): for othernumber, othernick in group.participants.iteritems():
@ -499,99 +499,99 @@ class Session(YowsupApp):
number = othernumber number = othernumber
break break
if number is not None: if number is not None:
self.logger.debug("Private message sent from %s to %s", self.legacyName, number) self.logger.debug(u"Private message sent from %s to %s", self.legacyName, number)
waId = self.sendTextMessage(number + '@s.whatsapp.net', message) waId = self.sendTextMessage(number + u'@s.whatsapp.net', message)
self.msgIDs[waId] = MsgIDs( ID, waId) self.msgIDs[waId] = MsgIDs( ID, waId)
else: else:
self.logger.error("Attempted to send private message to non-existent user") self.logger.error(u"Attempted to send private message to non-existent user")
self.logger.debug("%s to %s in %s", self.legacyName, nick, room) self.logger.debug(u"%s to %s in %s", self.legacyName, nick, room)
else: else:
room = sender room = sender
if message[0] == '\\' and message[:1] != '\\\\': if message[0] == u'\\' and message[:1] != u'\\\\':
self.logger.debug("Executing command %s in %s", message, room) self.logger.debug(u"Executing command %s in %s", message, room)
self.executeCommand(message, room) self.executeCommand(message, room)
else: else:
try: try:
group = self.groups[self._lengthenGroupId(room)] group = self.groups[self._lengthenGroupId(room)]
self.logger.debug("Group Message from %s to %s Groups: %s", self.logger.debug(u"Group Message from %s to %s Groups: %s",
group.nick , group , self.groups) group.nick , group , self.groups)
self.backend.handleMessage( self.backend.handleMessage(
self.user, room, message.decode('utf-8'), group.nick self.user, room, message.decode(u'utf-8'), group.nick
) )
except KeyError: except KeyError:
self.logger.error('Group not found: %s', room) self.logger.error(u'Group not found: %s', room)
if (".jpg" in message.lower()) or (".webp" in message.lower()): if (u".jpg" in message.lower()) or (u".webp" in message.lower()):
if (".jpg" in message.lower()): if (u".jpg" in message.lower()):
self.imgType = "jpg" self.imgType = u"jpg"
if (".webp" in message.lower()): if (u".webp" in message.lower()):
self.imgType = "webp" self.imgType = u"webp"
self.imgMsgId = ID self.imgMsgId = ID
self.imgBuddy = room + "@g.us" self.imgBuddy = room + u"@g.us"
downloader = MediaDownloader(self.onDlsuccess, self.onDlerror) downloader = MediaDownloader(self.onDlsuccess, self.onDlerror)
downloader.download(message) downloader.download(message)
#self.imgMsgId = ID #self.imgMsgId = ID
#self.imgBuddy = room + "@g.us" #self.imgBuddy = room + u"@g.us"
elif "geo:" in message.lower(): elif u"geo:" in message.lower():
self._sendLocation(room + "@g.us", message, ID) self._sendLocation(room + u"@g.us", message, ID)
else: else:
self.sendTextMessage(self._lengthenGroupId(room) + '@g.us', message) self.sendTextMessage(self._lengthenGroupId(room) + u'@g.us', message)
else: # private msg else: # private msg
buddy = sender buddy = sender
# if message == "\\lastseen": # if message == u"\\lastseen":
# self.call("presence_request", buddy = (buddy + "@s.whatsapp.net",)) # self.call(u"presence_request", buddy = (buddy + u"@s.whatsapp.net",))
# else: # else:
if message.split(" ").pop(0) == "\\lastseen": if message.split(u" ").pop(0) == u"\\lastseen":
self.presenceRequested.append(buddy) self.presenceRequested.append(buddy)
#self.call("presence_request", (buddy + "@s.whatsapp.net",)) #self.call(u"presence_request", (buddy + u"@s.whatsapp.net",))
self._requestLastSeen(buddy) self._requestLastSeen(buddy)
elif message.split(" ").pop(0) == "\\gpp": elif message.split(u" ").pop(0) == u"\\gpp":
self.logger.info("Get Profile Picture! ") self.logger.info(u"Get Profile Picture! ")
self.sendMessageToXMPP(buddy, "Fetching Profile Picture") self.sendMessageToXMPP(buddy, u"Fetching Profile Picture")
#self.call("contact_getProfilePicture", (buddy + "@s.whatsapp.net",)) #self.call(u"contact_getProfilePicture", (buddy + u"@s.whatsapp.net",))
self.requestVCard(buddy) self.requestVCard(buddy)
else: else:
if (".jpg" in message.lower()) or (".webp" in message.lower()): if (u".jpg" in message.lower()) or (u".webp" in message.lower()):
#waId = self.call("message_imageSend", (buddy + "@s.whatsapp.net", message, None, 0, None)) #waId = self.call(u"message_imageSend", (buddy + u"@s.whatsapp.net", message, None, 0, None))
#waId = self.call("message_send", (buddy + "@s.whatsapp.net", message)) #waId = self.call(u"message_send", (buddy + u"@s.whatsapp.net", message))
if (".jpg" in message.lower()): if (u".jpg" in message.lower()):
self.imgType = "jpg" self.imgType = u"jpg"
if (".webp" in message.lower()): if (u".webp" in message.lower()):
self.imgType = "webp" self.imgType = u"webp"
self.imgMsgId = ID self.imgMsgId = ID
self.imgBuddy = buddy + "@s.whatsapp.net" self.imgBuddy = buddy + u"@s.whatsapp.net"
downloader = MediaDownloader(self.onDlsuccess, self.onDlerror) downloader = MediaDownloader(self.onDlsuccess, self.onDlerror)
downloader.download(message) downloader.download(message)
#self.imgMsgId = ID #self.imgMsgId = ID
#self.imgBuddy = buddy + "@s.whatsapp.net" #self.imgBuddy = buddy + u"@s.whatsapp.net"
elif "geo:" in message.lower(): elif u"geo:" in message.lower():
self._sendLocation(buddy + "@s.whatsapp.net", message, ID) self._sendLocation(buddy + u"@s.whatsapp.net", message, ID)
else: else:
waId = self.sendTextMessage(sender + '@s.whatsapp.net', message) waId = self.sendTextMessage(sender + u'@s.whatsapp.net', message)
self.msgIDs[waId] = MsgIDs( ID, waId) self.msgIDs[waId] = MsgIDs( ID, waId)
self.logger.info("WA Message send to %s with ID %s", buddy, waId) self.logger.info(u"WA Message send to %s with ID %s", buddy, waId)
#self.sendTextMessage(sender + '@s.whatsapp.net', message) #self.sendTextMessage(sender + u'@s.whatsapp.net', message)
def executeCommand(self, command, room): def executeCommand(self, command, room):
if command == '\\leave': if command == u'\\leave':
self.logger.debug("Leaving room %s", room) self.logger.debug(u"Leaving room %s", room)
# Leave group on whatsapp side # Leave group on whatsapp side
self.leaveGroup(room) self.leaveGroup(room)
# Delete Room on spectrum side # Delete Room on spectrum side
group = self.groups[room] group = self.groups[room]
for jid in group.participants: for jid in group.participants:
buddy = jid.split("@")[0] buddy = jid.split(u"@")[0]
try: try:
nick = self.buddies[buddy].nick nick = self.buddies[buddy].nick
except KeyError: except KeyError:
nick = buddy nick = buddy
if nick == "": if nick == u"":
nick = buddy nick = buddy
if buddy == self.legacyName: if buddy == self.legacyName:
nick = group.nick nick = group.nick
@ -605,43 +605,43 @@ class Session(YowsupApp):
def onSuccess(buddy, lastseen): def onSuccess(buddy, lastseen):
timestamp = time.localtime(time.localtime()-lastseen) timestamp = time.localtime(time.localtime()-lastseen)
timestring = time.strftime("%a, %d %b %Y %H:%M:%S", timestamp) timestring = time.strftime(u"%a, %d %b %Y %H:%M:%S", timestamp)
self.sendMessageToXMPP(buddy, "%s (%s) %s" % (timestring, utils.ago(lastseen),str(lastseen))) self.sendMessageToXMPP(buddy, u"%s (%s) %s" % (timestring, utils.ago(lastseen),str(lastseen)))
def onError(errorIqEntity, originalIqEntity): def onError(errorIqEntity, originalIqEntity):
self.sendMessageToXMPP(errorIqEntity.getFrom(), "LastSeen Error") self.sendMessageToXMPP(errorIqEntity.getFrom(), u"LastSeen Error")
self.requestLastSeen(buddy, onSuccess, onError) self.requestLastSeen(buddy, onSuccess, onError)
def _sendLocation(self, buddy, message, ID): def _sendLocation(self, buddy, message, ID):
#with open('/opt/transwhat/map.jpg', 'rb') as imageFile: #with open(u'/opt/transwhat/map.jpg', u'rb') as imageFile:
# raw = base64.b64encode(imageFile.read()) # raw = base64.b64encode(imageFile.read())
latitude,longitude = message.split(':')[1].split(',') latitude,longitude = message.split(u':')[1].split(u',')
waId = self.sendLocation(buddy, float(latitude), float(longitude)) waId = self.sendLocation(buddy, float(latitude), float(longitude))
self.msgIDs[waId] = MsgIDs( ID, waId) self.msgIDs[waId] = MsgIDs( ID, waId)
self.logger.info("WA Location Message send to %s with ID %s", buddy, waId) self.logger.info(u"WA Location Message send to %s with ID %s", buddy, waId)
def sendMessageToXMPP(self, buddy, messageContent, timestamp = "", nickname = ""): def sendMessageToXMPP(self, buddy, messageContent, timestamp = u"", nickname = u""):
if timestamp: if timestamp:
timestamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime(timestamp)) timestamp = time.strftime(u"%Y%m%dT%H%M%S", time.gmtime(timestamp))
if self.initialized == False: if self.initialized == False:
self.logger.debug("Message queued from %s to %s: %s", self.logger.debug(u"Message queued from %s to %s: %s",
buddy, self.legacyName, messageContent) buddy, self.legacyName, messageContent)
self.offlineQueue.append((buddy, messageContent, timestamp)) self.offlineQueue.append((buddy, messageContent, timestamp))
else: else:
self.logger.debug("Message sent from %s to %s: %s", buddy, self.logger.debug(u"Message sent from %s to %s: %s", buddy,
self.legacyName, messageContent) self.legacyName, messageContent)
self.backend.handleMessage(self.user, buddy, messageContent, "", self.backend.handleMessage(self.user, buddy, messageContent, u"",
"", timestamp) u"", timestamp)
def sendGroupMessageToXMPP(self, room, number, messageContent, timestamp = ""): def sendGroupMessageToXMPP(self, room, number, messageContent, timestamp = u""):
if timestamp: if timestamp:
timestamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime(timestamp)) timestamp = time.strftime(u"%Y%m%dT%H%M%S", time.gmtime(timestamp))
if self.initialized == False: if self.initialized == False:
self.logger.debug("Group message queued from %s to %s: %s", self.logger.debug(u"Group message queued from %s to %s: %s",
number, room, messageContent) number, room, messageContent)
if room not in self.groupOfflineQueue: if room not in self.groupOfflineQueue:
@ -651,34 +651,34 @@ class Session(YowsupApp):
(number, messageContent, timestamp) (number, messageContent, timestamp)
) )
else: else:
self.logger.debug("Group message sent from %s to %s: %s", self.logger.debug(u"Group message sent from %s to %s: %s",
number, room, messageContent) number, room, messageContent)
try: try:
group = self.groups[room] group = self.groups[room]
# Update nickname # Update nickname
try: try:
if self.buddies[number].nick != "": if self.buddies[number].nick != u"":
group.changeNick(number, self.buddies[number].nick) group.changeNick(number, self.buddies[number].nick)
except KeyError: except KeyError:
pass pass
nick = group.participants[number] nick = group.participants[number]
if group.joined: if group.joined:
self.backend.handleMessage(self.user, room, messageContent, self.backend.handleMessage(self.user, room, messageContent,
nick, "", timestamp) nick, u"", timestamp)
else: else:
self.bot.send("You have received a message in group: %s@%s" self.bot.send(u"You have received a message in group: %s@%s"
% (room, self.backend.spectrum_jid)) % (room, self.backend.spectrum_jid))
self.bot.send("Join the group in order to reply") self.bot.send(u"Join the group in order to reply")
self.bot.send("%s: %s" % (nick, messageContent)) self.bot.send(u"%s: %s" % (nick, messageContent))
except KeyError: except KeyError:
self.logger.warn("Group is not in group list") self.logger.warn(u"Group is not in group list")
self.backend.handleMessage(self.user, self._shortenGroupId(room), self.backend.handleMessage(self.user, self._shortenGroupId(room),
messageContent, number, "", timestamp) messageContent, number, u"", timestamp)
def changeStatus(self, status): def changeStatus(self, status):
if status != self.status: if status != self.status:
self.logger.info("Status changed: %s", status) self.logger.info(u"Status changed: %s", status)
self.status = status self.status = status
if status == protocol_pb2.STATUS_ONLINE \ if status == protocol_pb2.STATUS_ONLINE \
@ -690,19 +690,19 @@ class Session(YowsupApp):
def changeStatusMessage(self, statusMessage): def changeStatusMessage(self, statusMessage):
if (statusMessage != self.statusMessage) or (self.initialized == False): if (statusMessage != self.statusMessage) or (self.initialized == False):
self.statusMessage = statusMessage self.statusMessage = statusMessage
self.setStatus(statusMessage.encode('utf-8')) self.setStatus(statusMessage.encode(u'utf-8'))
self.logger.info("Status message changed: %s", statusMessage) self.logger.info(u"Status message changed: %s", statusMessage)
#if self.initialized == False: #if self.initialized == False:
# self.sendOfflineMessages() # self.sendOfflineMessages()
# self.bot.call("welcome") # self.bot.call(u"welcome")
# self.initialized = True # self.initialized = True
def sendOfflineMessages(self): def sendOfflineMessages(self):
# Flush Queues # Flush Queues
while self.offlineQueue: while self.offlineQueue:
msg = self.offlineQueue.pop(0) msg = self.offlineQueue.pop(0)
self.backend.handleMessage(self.user, msg[0], msg[1], "", "", msg[2]) self.backend.handleMessage(self.user, msg[0], msg[1], u"", u"", msg[2])
# Called when user logs in to initialize the roster # Called when user logs in to initialize the roster
def loadBuddies(self, buddies): def loadBuddies(self, buddies):
@ -710,56 +710,56 @@ class Session(YowsupApp):
# also for adding a new buddy # also for adding a new buddy
def updateBuddy(self, buddy, nick, groups, image_hash = None): def updateBuddy(self, buddy, nick, groups, image_hash = None):
if buddy != "bot": if buddy != u"bot":
self.buddies.update(buddy, nick, groups, image_hash) self.buddies.update(buddy, nick, groups, image_hash)
def removeBuddy(self, buddy): def removeBuddy(self, buddy):
if buddy != "bot": if buddy != u"bot":
self.logger.info("Buddy removed: %s", buddy) self.logger.info(u"Buddy removed: %s", buddy)
self.buddies.remove(buddy) self.buddies.remove(buddy)
def requestVCard(self, buddy, ID=None): def requestVCard(self, buddy, ID=None):
def onSuccess(response, request): def onSuccess(response, request):
self.logger.debug('Sending VCard (%s) with image id %s', self.logger.debug(u'Sending VCard (%s) with image id %s',
ID, response.pictureId) ID, response.pictureId)
image_hash = utils.sha1hash(response.pictureData) image_hash = utils.sha1hash(response.pictureData)
self.logger.debug('Image hash is %s', image_hash) self.logger.debug(u'Image hash is %s', image_hash)
if ID != None: if ID != None:
self.backend.handleVCard(self.user, ID, buddy, "", "", response.pictureData) self.backend.handleVCard(self.user, ID, buddy, u"", u"", response.pictureData)
obuddy = self.buddies[buddy] obuddy = self.buddies[buddy]
self.updateBuddy(buddy, obuddy.nick, obuddy.groups, image_hash) self.updateBuddy(buddy, obuddy.nick, obuddy.groups, image_hash)
self.logger.debug('Requesting profile picture of %s', buddy) self.logger.debug(u'Requesting profile picture of %s', buddy)
self.requestProfilePicture(buddy, onSuccess = onSuccess) self.requestProfilePicture(buddy, onSuccess = onSuccess)
def onDlsuccess(self, path): def onDlsuccess(self, path):
self.logger.info("Success: Image downloaded to %s", path) self.logger.info(u"Success: Image downloaded to %s", path)
os.rename(path, path+"."+self.imgType) os.rename(path, path+u"."+self.imgType)
if self.imgType != "jpg": if self.imgType != u"jpg":
im = Image.open(path+"."+self.imgType) im = Image.open(path+u"."+self.imgType)
im.save(path+".jpg") im.save(path+u".jpg")
self.imgPath = path+".jpg" self.imgPath = path+u".jpg"
statinfo = os.stat(self.imgPath) statinfo = os.stat(self.imgPath)
name=os.path.basename(self.imgPath) name=os.path.basename(self.imgPath)
self.logger.info("Buddy %s",self.imgBuddy) self.logger.info(u"Buddy %s",self.imgBuddy)
self.image_send(self.imgBuddy, self.imgPath) self.image_send(self.imgBuddy, self.imgPath)
#self.logger.info("Sending picture %s of size %s with name %s",self.imgPath, statinfo.st_size, name) #self.logger.info(u"Sending picture %s of size %s with name %s",self.imgPath, statinfo.st_size, name)
#mtype = "image" #mtype = u"image"
#sha1 = hashlib.sha256() #sha1 = hashlib.sha256()
#fp = open(self.imgPath, 'rb') #fp = open(self.imgPath, u'rb')
#try: #try:
# sha1.update(fp.read()) # sha1.update(fp.read())
# hsh = base64.b64encode(sha1.digest()) # hsh = base64.b64encode(sha1.digest())
# self.call("media_requestUpload", (hsh, mtype, os.path.getsize(self.imgPath))) # self.call(u"media_requestUpload", (hsh, mtype, os.path.getsize(self.imgPath)))
#finally: #finally:
# fp.close() # fp.close()
def onDlerror(self): def onDlerror(self):
self.logger.info("Download Error. Sending message as is.") self.logger.info(u"Download Error. Sending message as is.")
waId = self.sendTextMessage(self.dlerror_sender + '@s.whatsapp.net', self.dlerror_message) waId = self.sendTextMessage(self.dlerror_sender + u'@s.whatsapp.net', self.dlerror_message)
self.msgIDs[waId] = MsgIDs(self.dlerror_ID, waId) self.msgIDs[waId] = MsgIDs(self.dlerror_ID, waId)
@ -777,7 +777,7 @@ class Session(YowsupApp):
def createThumb(self, size=100, raw=False): def createThumb(self, size=100, raw=False):
img = Image.open(self.imgPath) img = Image.open(self.imgPath)
width, height = img.size width, height = img.size
img_thumbnail = self.imgPath + '_thumbnail' img_thumbnail = self.imgPath + u'_thumbnail'
if width > height: if width > height:
nheight = float(height) / width * size nheight = float(height) / width * size
@ -787,47 +787,47 @@ class Session(YowsupApp):
nheight = size nheight = size
img.thumbnail((nwidth, nheight), Image.ANTIALIAS) img.thumbnail((nwidth, nheight), Image.ANTIALIAS)
img.save(img_thumbnail, 'JPEG') img.save(img_thumbnail, u'JPEG')
with open(img_thumbnail, 'rb') as imageFile: with open(img_thumbnail, u'rb') as imageFile:
raw = base64.b64encode(imageFile.read()) raw = base64.b64encode(imageFile.read())
return raw return raw
# Not used # Not used
def onLocationReceived(self, messageId, jid, name, preview, latitude, longitude, receiptRequested, isBroadcast): def onLocationReceived(self, messageId, jid, name, preview, latitude, longitude, receiptRequested, isBroadcast):
buddy = jid.split("@")[0] buddy = jid.split(u"@")[0]
self.logger.info("Location received from %s: %s, %s", buddy, latitude, longitude) self.logger.info(u"Location received from %s: %s, %s", buddy, latitude, longitude)
url = "http://maps.google.de?%s" % urllib.urlencode({ "q": "%s %s" % (latitude, longitude) }) url = u"http://maps.google.de?%s" % urllib.urlencode({ u"q": u"%s %s" % (latitude, longitude) })
self.sendMessageToXMPP(buddy, utils.shorten(url)) self.sendMessageToXMPP(buddy, utils.shorten(url))
if receiptRequested: self.call("message_ack", (jid, messageId)) if receiptRequested: self.call(u"message_ack", (jid, messageId))
def onGroupSubjectReceived(self, messageId, gjid, jid, subject, timestamp, receiptRequested): def onGroupSubjectReceived(self, messageId, gjid, jid, subject, timestamp, receiptRequested):
room = gjid.split("@")[0] room = gjid.split(u"@")[0]
buddy = jid.split("@")[0] buddy = jid.split(u"@")[0]
self.backend.handleSubject(self.user, room, subject, buddy) self.backend.handleSubject(self.user, room, subject, buddy)
if receiptRequested: self.call("subject_ack", (gjid, messageId)) if receiptRequested: self.call(u"subject_ack", (gjid, messageId))
# Yowsup Notifications # Yowsup Notifications
def onGroupParticipantRemoved(self, gjid, jid, author, timestamp, messageId, receiptRequested): def onGroupParticipantRemoved(self, gjid, jid, author, timestamp, messageId, receiptRequested):
room = gjid.split("@")[0] room = gjid.split(u"@")[0]
buddy = jid.split("@")[0] buddy = jid.split(u"@")[0]
self.logger.info("Removed %s from room %s", buddy, room) self.logger.info(u"Removed %s from room %s", buddy, room)
self.backend.handleParticipantChanged(self.user, buddy, room, protocol_pb2.PARTICIPANT_FLAG_NONE, protocol_pb2.STATUS_NONE) # TODO self.backend.handleParticipantChanged(self.user, buddy, room, protocol_pb2.PARTICIPANT_FLAG_NONE, protocol_pb2.STATUS_NONE) # TODO
if receiptRequested: self.call("notification_ack", (gjid, messageId)) if receiptRequested: self.call(u"notification_ack", (gjid, messageId))
def onContactProfilePictureUpdated(self, jid, timestamp, messageId, pictureId, receiptRequested): def onContactProfilePictureUpdated(self, jid, timestamp, messageId, pictureId, receiptRequested):
# TODO # TODO
if receiptRequested: self.call("notification_ack", (jid, messageId)) if receiptRequested: self.call(u"notification_ack", (jid, messageId))
def onGroupPictureUpdated(self, jid, author, timestamp, messageId, pictureId, receiptRequested): def onGroupPictureUpdated(self, jid, author, timestamp, messageId, pictureId, receiptRequested):
# TODO # TODO
if receiptRequested: self.call("notification_ack", (jid, messageId)) if receiptRequested: self.call(u"notification_ack", (jid, messageId))

View file

@ -1,12 +1,12 @@
#!/usr/bin/python #!/usr/bin/python
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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('--debug', action='store_true') parser.add_argument(u'--debug', action=u'store_true')
parser.add_argument('--host', type=str, required=True) parser.add_argument(u'--host', type=str, required=True)
parser.add_argument('--port', type=int, required=True) parser.add_argument(u'--port', type=int, required=True)
parser.add_argument('--service.backend_id', metavar="ID", type=int, required=True) parser.add_argument(u'--service.backend_id', metavar=u"ID", type=int, required=True)
parser.add_argument('config', type=str) parser.add_argument(u'config', type=str)
parser.add_argument('-j', type=str, required=True) parser.add_argument(u'-j', type=str, required=True)
args, unknown = parser.parse_known_args() args, unknown = parser.parse_known_args()
YowConstants.PATH_STORAGE='/var/lib/spectrum2/' + args.j YowConstants.PATH_STORAGE=u'/var/lib/spectrum2/' + args.j
loggingfile = '/var/log/spectrum2/' + args.j + '/backends/backend.log' loggingfile = u'/var/log/spectrum2/' + args.j + u'/backends/backend.log'
# Logging # Logging
logging.basicConfig( \ logging.basicConfig( \
filename=loggingfile,\ filename=loggingfile,\
format = "%(asctime)-15s %(levelname)s %(name)s: %(message)s", \ format = u"%(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({
'features': [ u'features': [
('send_buddies_on_login', 1), (u'send_buddies_on_login', 1),
('muc', 'true'), (u'muc', u'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) #doesn't block callback = YowStack._YowStack__detachedQueue.get(False) #doesnu't block
callback() callback()
except Queue.Empty: except Queue.Empty:
pass pass

View file

@ -1,10 +1,10 @@
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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
@ -26,7 +26,7 @@ import base64
import hashlib import hashlib
def ago(secs): def ago(secs):
periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"] periods = [u"second", u"minute", u"hour", u"day", u"week", u"month", u"year", u"decade"]
lengths = [60, 60, 24, 7,4.35, 12, 10] lengths = [60, 60, 24, 7,4.35, 12, 10]
j = 0 j = 0
@ -38,16 +38,16 @@ def ago(secs):
j += 1 j += 1
period = periods[j] period = periods[j]
if diff > 1: period += "s" if diff > 1: period += u"s"
return "%d %s ago" % (diff, period) return u"%d %s ago" % (diff, period)
def softToUni(message): def softToUni(message):
message = message.decode("utf-8") message = message.decode(u"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("utf-8"))) return base64.b64decode(bytes(password.encode(u"utf-8")))
def sha1hash(data): def sha1hash(data):
return hashlib.sha1(data).hexdigest() return hashlib.sha1(data).hexdigest()

View file

@ -1,10 +1,10 @@
__author__ = "Steffen Vogel" __author__ = u"Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel" __copyright__ = u"Copyright 2015, Steffen Vogel"
__license__ = "GPLv3" __license__ = u"GPLv3"
__maintainer__ = "Steffen Vogel" __maintainer__ = u"Steffen Vogel"
__email__ = "post@steffenvogel.de" __email__ = u"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("Backend started") self.logger.debug(u"Backend started")
# RequestsHandlers # RequestsHandlers
def handleLoginRequest(self, user, legacyName, password, extra): def handleLoginRequest(self, user, legacyName, password, extra):
self.logger.debug("handleLoginRequest(user=%s, legacyName=%s)", user, legacyName) self.logger.debug(u"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("handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName) self.logger.debug(u"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 = "", ID = 0): def handleMessageSendRequest(self, user, buddy, message, xhtml = u"", ID = 0):
self.logger.debug("handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml) self.logger.debug(u"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("handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname) self.logger.debug(u"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("handleLeaveRoomRequest(user=%s, room=%s)", user, room) self.logger.debug(u"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("handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage) self.logger.debug(u"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):
"""Called when user logs in. Used to initialize roster.""" u"""Called when user logs in. Used to initialize roster."""
self.logger.debug("handleBuddies(buddies=%s)", buddies) self.logger.debug(u"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("handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups)) self.logger.debug(u"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("handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups)) self.logger.debug(u"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("handleTypingRequest(user=%s, buddy=%s)", user, buddy) self.logger.debug(u"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("handleTypedRequest(user=%s, buddy=%s)", user, buddy) self.logger.debug(u"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("handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy) self.logger.debug(u"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("handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID) self.logger.debug(u"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('File send request %s, for user %s, from %s, size: %s', self.logger.debug(u'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("Meassage ACK request for %s !!",legacyName) self.logger.info(u"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):
"""Login to yowsup u"""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('password not base64 encoded') self.onAuthFailure(u'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("%s" % e) # self.onAuthFailure(u"%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, "raw", to = to) messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, u"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("Request upload for file %s for %s failed" % (path, jid)) self.logger.error(u"Request upload for file %s for %s failed" % (path, jid))
def onUploadError(self, filePath, jid, url): def onUploadError(self, filePath, jid, url):
#logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid)) #logger.error(u"Upload file %s to %s for %s failed!" % (filePath, url, jid))
self.logger.error("Upload Error!") self.logger.error(u"Upload Error!")
def onUploadProgress(self, filePath, jid, url, progress): def onUploadProgress(self, filePath, jid, url, progress):
#sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress)) #sys.stdout.write(u"%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("Subscribing to Presence updates from %s", (phone_number)) self.logger.debug(u"Subscribing to Presence updates from %s", (phone_number))
jid = phone_number + '@s.whatsapp.net' jid = phone_number + u'@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 + '@s.whatsapp.net' jid = phone_number + u'@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 + '@g.us']) entity = LeaveGroupsIqProtocolEntity([group + u'@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 + '@s.whatsapp.net' jid = phoneNumber + u'@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 + '@s.whatsapp.net' for c in contacts]) iq = GetStatusesIqProtocolEntity([c + u'@s.whatsapp.net' for c in contacts])
def onSuccess(response, request): def onSuccess(response, request):
self.logger.debug("Received Statuses %s", response) self.logger.debug(u"Received Statuses %s", response)
s = {} s = {}
for k, v in response.statuses.iteritems(): for k, v in response.statuses.iteritems():
s[k.split('@')[0]] = v s[k.split(u'@')[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 + '@s.whatsapp.net') iq = LastseenIqProtocolEntity(phoneNumber + u'@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('@')[0], response.seconds) success(response._from.split(u'@')[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 + '@s.whatsapp.net') iq = GetPictureIqProtocolEntity(phoneNumber + u'@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 + '@g.us') iq = InfoGroupsIqProtocolEntity(group + u'@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):
"""Called when the user has been added to a new group""" u"""Called when the user has been added to a new group"""
pass pass
def onParticipantsAddedToGroup(self, entity): def onParticipantsAddedToGroup(self, entity):
"""Called when participants have been added to a group""" u"""Called when participants have been added to a group"""
pass pass
def onParticipantsRemovedFromGroup(self, group, participants): def onParticipantsRemovedFromGroup(self, group, participants):
"""Called when participants have been removed from a group u"""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):
"""Sends an entity down the stack (as if YowsupAppLayer called toLower)""" u"""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 = 'transwhat.event.YowsupAppLayer.start' EVENT_START = u'transwhat.event.YowsupAppLayer.start'
TO_LOWER_EVENT = 'transwhat.event.YowsupAppLayer.toLower' TO_LOWER_EVENT = u'transwhat.event.YowsupAppLayer.toLower'
SEND_IQ = 'transwhat.event.YowsupAppLayer.sendIq' SEND_IQ = u'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('caller') self.caller = layerEvent.getArg(u'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('entity')) self.toLower(layerEvent.getArg(u'entity'))
return True return True
elif layerEvent.getName() == YowsupAppLayer.SEND_IQ: elif layerEvent.getName() == YowsupAppLayer.SEND_IQ:
iq = layerEvent.getArg('iq') iq = layerEvent.getArg(u'iq')
success = layerEvent.getArg('success') success = layerEvent.getArg(u'success')
failure = layerEvent.getArg('failure') failure = layerEvent.getArg(u'failure')
self._sendIq(iq, success, failure) self._sendIq(iq, success, failure)
return True return True
return False return False
@ProtocolEntityCallback('success') @ProtocolEntityCallback(u'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 don't know what this is t = entity.t # I donu'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('failure') @ProtocolEntityCallback('failureu')
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('receipt') @ProtocolEntityCallback('receiptu')
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(),
'receipt', entity.getType(), entity.getFrom()) 'receiptu', 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('ack') @ProtocolEntityCallback('acku')
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('notification') @ProtocolEntityCallback('notificationu')
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('@')[0], entity.getGroupId().split('@u')[0],
entity.getParticipants().keys() entity.getParticipants().keys()
) )
@ProtocolEntityCallback('message') @ProtocolEntityCallback('messageu')
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('presence') @ProtocolEntityCallback('presenceu')
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('chatstate') @ProtocolEntityCallback('chatstateu')
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: