Revert upto c40d477667
Hard to find connection bugs are occuring. Reverting changes for now
This commit is contained in:
parent
bed8214a11
commit
22cebef457
|
@ -262,6 +262,7 @@ class SpectrumBackend:
|
|||
|
||||
def handleConvMessagePayload(self, data):
|
||||
payload = protocol_pb2.ConversationMessage()
|
||||
self.logger.error("handleConvMessagePayload")
|
||||
if (payload.ParseFromString(data) == False):
|
||||
#TODO: ERROR
|
||||
return
|
||||
|
|
1
USAGE.md
1
USAGE.md
|
@ -28,6 +28,7 @@ The bot is one of the contacts every user has in its contact list. It offers you
|
|||
| ------------ | --------------- |
|
||||
| `\help` | show this message |
|
||||
| `\prune` | clear your buddylist |
|
||||
| `\sync` | sync your imported contacts with WhatsApp |
|
||||
| `\lastseen` | request last online timestamp from buddy |
|
||||
| `\leave` | permanently leave group chat |
|
||||
| `\groups` | print all attended groups |
|
||||
|
|
40
bot.py
40
bot.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -30,30 +30,30 @@ import os
|
|||
import utils
|
||||
|
||||
class Bot():
|
||||
def __init__(self, session, name = u"Bot"):
|
||||
def __init__(self, session, name = "Bot"):
|
||||
self.session = session
|
||||
self.name = name
|
||||
|
||||
self.commands = {
|
||||
u"help": self._help,
|
||||
u"prune": self._prune,
|
||||
u"groups": self._groups,
|
||||
u"getgroups": self._getgroups
|
||||
"help": self._help,
|
||||
"prune": self._prune,
|
||||
"groups": self._groups,
|
||||
"getgroups": self._getgroups
|
||||
}
|
||||
|
||||
def parse(self, message):
|
||||
args = message.split(u" ")
|
||||
args = message.split(" ")
|
||||
cmd = args.pop(0)
|
||||
|
||||
if cmd[0] == u'\\':
|
||||
if cmd[0] == '\\':
|
||||
try:
|
||||
self.call(cmd[1:], args)
|
||||
except KeyError:
|
||||
self.send(u"invalid command")
|
||||
self.send("invalid command")
|
||||
except TypeError:
|
||||
self.send(u"invalid syntax")
|
||||
self.send("invalid syntax")
|
||||
else:
|
||||
self.send(u"a valid command starts with a backslash")
|
||||
self.send("a valid command starts with a backslash")
|
||||
|
||||
def call(self, cmd, args = []):
|
||||
func = self.commands[cmd]
|
||||
|
@ -71,7 +71,7 @@ class Bot():
|
|||
|
||||
# commands
|
||||
def _help(self):
|
||||
self.send(u"""following bot commands are available:
|
||||
self.send("""following bot commands are available:
|
||||
\\help show this message
|
||||
\\prune clear your buddylist
|
||||
|
||||
|
@ -86,7 +86,7 @@ following group commands are available
|
|||
def _prune(self):
|
||||
self.session.buddies.prune()
|
||||
self.session.updateRoster()
|
||||
self.send(u"buddy list cleared")
|
||||
self.send("buddy list cleared")
|
||||
|
||||
def _groups(self):
|
||||
for group in self.session.groups:
|
||||
|
@ -96,9 +96,9 @@ following group commands are available
|
|||
except KeyError:
|
||||
nick = buddy
|
||||
|
||||
self.send(self.session.groups[group].id + u"@" + self.session.backend.spectrum_jid + u" " + self.session.groups[group].subject + u" Owner: " + nick )
|
||||
self.send(self.session.groups[group].id + "@" + self.session.backend.spectrum_jid + " " + self.session.groups[group].subject + " Owner: " + nick )
|
||||
|
||||
def _getgroups(self):
|
||||
#self.session.call(u"group_getGroups", (u"participating",))
|
||||
#self.session.call("group_getGroups", ("participating",))
|
||||
self.session.requestGroupsList(self.session._updateGroups)
|
||||
|
||||
|
|
54
buddy.py
54
buddy.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -25,7 +25,6 @@ from Spectrum2 import protocol_pb2
|
|||
|
||||
import logging
|
||||
import time
|
||||
import utils
|
||||
|
||||
|
||||
class Buddy():
|
||||
|
@ -34,8 +33,8 @@ class Buddy():
|
|||
self.owner = owner
|
||||
self.number = number
|
||||
self.groups = groups
|
||||
self.image_hash = image_hash if image_hash is not None else u""
|
||||
self.statusMsg = u""
|
||||
self.image_hash = image_hash if image_hash is not None else ""
|
||||
self.statusMsg = ""
|
||||
self.lastseen = 0
|
||||
self.presence = 0
|
||||
|
||||
|
@ -47,7 +46,7 @@ class Buddy():
|
|||
self.image_hash = image_hash
|
||||
|
||||
def __str__(self):
|
||||
return u"%s (nick=%s)" % (self.number, self.nick)
|
||||
return "%s (nick=%s)" % (self.number, self.nick)
|
||||
|
||||
class BuddyList(dict):
|
||||
|
||||
|
@ -63,20 +62,20 @@ class BuddyList(dict):
|
|||
for buddy in buddies:
|
||||
number = buddy.buddyName
|
||||
nick = buddy.alias
|
||||
statusMsg = buddy.statusMessage.decode(u'utf-8')
|
||||
statusMsg = buddy.statusMessage
|
||||
groups = [g for g in buddy.group]
|
||||
image_hash = buddy.iconHash
|
||||
self[number] = Buddy(self.owner, number, nick, statusMsg,
|
||||
groups, image_hash)
|
||||
|
||||
self.logger.debug(u"Update roster")
|
||||
self.logger.debug("Update roster")
|
||||
|
||||
# old = self.buddies.keys()
|
||||
# self.buddies.load()
|
||||
# new = self.buddies.keys()
|
||||
# contacts = new
|
||||
contacts = self.keys()
|
||||
contacts.remove(u'bot')
|
||||
contacts.remove('bot')
|
||||
|
||||
if self.synced == False:
|
||||
self.session.sendSync(contacts, delta = False, interactive = True)
|
||||
|
@ -85,11 +84,11 @@ class BuddyList(dict):
|
|||
# add = set(new) - set(old)
|
||||
# remove = set(old) - set(new)
|
||||
|
||||
# self.logger.debug(u"Roster remove: %s", str(list(remove)))
|
||||
self.logger.debug(u"Roster add: %s", str(list(contacts)))
|
||||
# self.logger.debug("Roster remove: %s", str(list(remove)))
|
||||
self.logger.debug("Roster add: %s", str(list(contacts)))
|
||||
|
||||
# for number in remove:
|
||||
# self.backend.handleBuddyChanged(self.user, number, u"", [],
|
||||
# self.backend.handleBuddyChanged(self.user, number, "", [],
|
||||
# protocol_pb2.STATUS_NONE)
|
||||
# self.backend.handleBuddyRemoved(self.user, number)
|
||||
# self.unsubscribePresence(number)
|
||||
|
@ -98,19 +97,16 @@ class BuddyList(dict):
|
|||
buddy = self[number]
|
||||
self.backend.handleBuddyChanged(self.user, number, buddy.nick,
|
||||
buddy.groups, protocol_pb2.STATUS_NONE,
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else u"")
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else "")
|
||||
self.session.subscribePresence(number)
|
||||
self.logger.debug(u"%s is requesting statuses of: %s", self.user, contacts)
|
||||
self.logger.debug("%s is requesting statuses of: %s", self.user, contacts)
|
||||
self.session.requestStatuses(contacts, success = self.onStatus)
|
||||
|
||||
def onStatus(self, contacts):
|
||||
self.logger.debug(u"%s received statuses of: %s", self.user, contacts)
|
||||
self.logger.debug("%s received statuses of: %s", self.user, contacts)
|
||||
for number, (status, time) in contacts.iteritems():
|
||||
buddy = self[number]
|
||||
if status is None:
|
||||
buddy.statusMsg = ""
|
||||
else:
|
||||
buddy.statusMsg = utils.softToUni(status)
|
||||
buddy.statusMsg = status
|
||||
self.updateSpectrum(buddy)
|
||||
|
||||
|
||||
|
@ -128,9 +124,9 @@ class BuddyList(dict):
|
|||
self.session.sendSync([number], delta = True, interactive = True)
|
||||
self.session.subscribePresence(number)
|
||||
self.session.requestStatuses([number], success = self.onStatus)
|
||||
buddy = Buddy(self.owner, number, nick, u"", groups, image_hash)
|
||||
buddy = Buddy(self.owner, number, nick, "", groups, image_hash)
|
||||
self[number] = buddy
|
||||
self.logger.debug(u"Roster add: %s", buddy)
|
||||
self.logger.debug("Roster add: %s", buddy)
|
||||
|
||||
self.updateSpectrum(buddy)
|
||||
return buddy
|
||||
|
@ -138,7 +134,7 @@ class BuddyList(dict):
|
|||
def updateSpectrum(self, buddy):
|
||||
if buddy.presence == 0:
|
||||
status = protocol_pb2.STATUS_NONE
|
||||
elif buddy.presence == u'unavailable':
|
||||
elif buddy.presence == 'unavailable':
|
||||
status = protocol_pb2.STATUS_AWAY
|
||||
else:
|
||||
status = protocol_pb2.STATUS_ONLINE
|
||||
|
@ -146,18 +142,18 @@ class BuddyList(dict):
|
|||
statusmsg = buddy.statusMsg
|
||||
if buddy.lastseen != 0:
|
||||
timestamp = time.localtime(buddy.lastseen)
|
||||
statusmsg += time.strftime(u"\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp)
|
||||
statusmsg += time.strftime("\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp)
|
||||
|
||||
self.backend.handleBuddyChanged(self.user, buddy.number, buddy.nick,
|
||||
buddy.groups, status, statusMessage = statusmsg,
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else u"")
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else "")
|
||||
|
||||
|
||||
def remove(self, number):
|
||||
try:
|
||||
buddy = self[number]
|
||||
del self[number]
|
||||
self.backend.handleBuddyChanged(self.user, number, u"", [],
|
||||
self.backend.handleBuddyChanged(self.user, number, "", [],
|
||||
protocol_pb2.STATUS_NONE)
|
||||
self.backend.handleBuddyRemoved(self.user, number)
|
||||
self.session.unsubscribePresence(number)
|
||||
|
|
81
group.py
81
group.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -21,77 +21,14 @@ u"""
|
|||
along with transWhat. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from Spectrum2 import protocol_pb2
|
||||
|
||||
class Group():
|
||||
|
||||
def __init__(self, id, owner, subject, subjectOwner, backend, user):
|
||||
def __init__(self, id, owner, subject, subjectOwner):
|
||||
self.id = id
|
||||
self.subject = subject
|
||||
self.subjectOwner = subjectOwner
|
||||
self.owner = owner
|
||||
self.joined = False
|
||||
self.backend = backend
|
||||
self.user = user
|
||||
|
||||
self.nick = u"me"
|
||||
# Participants is a number -> nickname dict
|
||||
self.participants = {}
|
||||
|
||||
def addParticipants(self, participants, buddies, yourNumber):
|
||||
u"""
|
||||
Adds participants to the group.
|
||||
|
||||
Args:
|
||||
- participants: (Iterable) phone numbers of participants
|
||||
- buddies: (dict) Used to get the nicknames of the participants
|
||||
- yourNumber: The number you are using
|
||||
"""
|
||||
for jid in participants:
|
||||
number = jid.split(u'@')[0]
|
||||
try:
|
||||
nick = buddies[number].nick
|
||||
except KeyError:
|
||||
nick = number
|
||||
if number == yourNumber:
|
||||
nick = self.nick
|
||||
if nick == u"":
|
||||
nick = number
|
||||
self.participants[number] = nick
|
||||
|
||||
def sendParticipantsToSpectrum(self, yourNumber):
|
||||
for number, nick in self.participants.iteritems():
|
||||
if number == self.owner:
|
||||
flags = protocol_pb2.PARTICIPANT_FLAG_MODERATOR
|
||||
else:
|
||||
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
|
||||
if number == yourNumber:
|
||||
flags = flags | protocol_pb2.PARTICIPANT_FLAG_ME
|
||||
|
||||
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE)
|
||||
|
||||
def removeParticipants(self, participants):
|
||||
for jid in participants:
|
||||
number = jid.split(u'@')[0]
|
||||
nick = self.participants[number]
|
||||
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
|
||||
self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE)
|
||||
del self.participants[number]
|
||||
|
||||
def changeNick(self, number, new_nick):
|
||||
if self.participants[number] == new_nick:
|
||||
return
|
||||
if number == self.owner:
|
||||
flags = protocol_pb2.PARTICIPANT_FLAG_MODERATOR
|
||||
else:
|
||||
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
|
||||
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, new_nick)
|
||||
self.participants[number] = new_nick
|
||||
|
||||
def _updateParticipant(self, number, flags, status, newNick = u""):
|
||||
nick = self.participants[number]
|
||||
# Notice the status message is the buddy's number
|
||||
if self.joined:
|
||||
self.backend.handleParticipantChanged(
|
||||
self.user, nick, self.id, flags,
|
||||
status, number, newname = newNick)
|
||||
self.nick = "me"
|
||||
self.participants = []
|
||||
|
|
20
reader.py
20
reader.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -24,19 +24,19 @@ u"""
|
|||
import time
|
||||
|
||||
def get_token(number, timeout = 30):
|
||||
file = open(u'tokens')
|
||||
file = open('tokens')
|
||||
file.seek(-1, 2)
|
||||
|
||||
count = 0
|
||||
while count < timeout:
|
||||
line = file.readline()
|
||||
|
||||
if line in [u"", u"\n"]:
|
||||
if line in ["", "\n"]:
|
||||
time.sleep(1)
|
||||
count += 1
|
||||
continue
|
||||
else:
|
||||
t, n, tk = line[:-1].split(u"\t")
|
||||
t, n, tk = line[:-1].split("\t")
|
||||
|
||||
if (n == number):
|
||||
file.close()
|
||||
|
@ -45,4 +45,4 @@ def get_token(number, timeout = 30):
|
|||
file.close()
|
||||
|
||||
|
||||
print get_token(u"4917696978528")
|
||||
print get_token("4917696978528")
|
||||
|
|
525
session.py
525
session.py
File diff suppressed because it is too large
Load diff
38
transwhat.py
38
transwhat.py
|
@ -1,12 +1,12 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -42,21 +42,21 @@ from yowsup.stacks import YowStack
|
|||
|
||||
# Arguments
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(u'--debug', action=u'store_true')
|
||||
parser.add_argument(u'--host', type=str, required=True)
|
||||
parser.add_argument(u'--port', type=int, required=True)
|
||||
parser.add_argument(u'--service.backend_id', metavar=u"ID", type=int, required=True)
|
||||
parser.add_argument(u'config', type=str)
|
||||
parser.add_argument(u'-j', type=str, required=True)
|
||||
parser.add_argument('--debug', action='store_true')
|
||||
parser.add_argument('--host', type=str, required=True)
|
||||
parser.add_argument('--port', type=int, required=True)
|
||||
parser.add_argument('--service.backend_id', metavar="ID", type=int, required=True)
|
||||
parser.add_argument('config', type=str)
|
||||
parser.add_argument('-j', type=str, required=True)
|
||||
|
||||
args, unknown = parser.parse_known_args()
|
||||
|
||||
YowConstants.PATH_STORAGE=u'/var/lib/spectrum2/' + args.j
|
||||
loggingfile = u'/var/log/spectrum2/' + args.j + u'/backends/backend.log'
|
||||
YowConstants.PATH_STORAGE='/var/lib/spectrum2/' + args.j
|
||||
loggingfile = '/var/log/spectrum2/' + args.j + '/backends/backend.log'
|
||||
# Logging
|
||||
logging.basicConfig( \
|
||||
filename=loggingfile,\
|
||||
format = u"%(asctime)-15s %(levelname)s %(name)s: %(message)s", \
|
||||
format = "%(asctime)-15s %(levelname)s %(name)s: %(message)s", \
|
||||
level = logging.DEBUG if args.debug else logging.INFO \
|
||||
)
|
||||
|
||||
|
@ -77,9 +77,9 @@ io = IOChannel(args.host, args.port, handleTransportData, connectionClosed)
|
|||
plugin = WhatsAppBackend(io, args.j)
|
||||
|
||||
plugin.handleBackendConfig({
|
||||
u'features': [
|
||||
(u'send_buddies_on_login', 1),
|
||||
(u'muc', u'true'),
|
||||
'features': [
|
||||
('send_buddies_on_login', 1),
|
||||
('muc', 'true'),
|
||||
],
|
||||
})
|
||||
|
||||
|
@ -87,7 +87,7 @@ while True:
|
|||
try:
|
||||
asyncore.loop(timeout=1.0, count=10, use_poll = True)
|
||||
try:
|
||||
callback = YowStack._YowStack__detachedQueue.get(False) #doesnu't block
|
||||
callback = YowStack._YowStack__detachedQueue.get(False) #doesn't block
|
||||
callback()
|
||||
except Queue.Empty:
|
||||
pass
|
||||
|
|
25
utils.py
25
utils.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -24,10 +24,9 @@ u"""
|
|||
import e4u
|
||||
import base64
|
||||
import hashlib
|
||||
import base64
|
||||
|
||||
def ago(secs):
|
||||
periods = [u"second", u"minute", u"hour", u"day", u"week", u"month", u"year", u"decade"]
|
||||
periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"]
|
||||
lengths = [60, 60, 24, 7,4.35, 12, 10]
|
||||
|
||||
j = 0
|
||||
|
@ -39,16 +38,16 @@ def ago(secs):
|
|||
j += 1
|
||||
|
||||
period = periods[j]
|
||||
if diff > 1: period += u"s"
|
||||
if diff > 1: period += "s"
|
||||
|
||||
return u"%d %s ago" % (diff, period)
|
||||
return "%d %s ago" % (diff, period)
|
||||
|
||||
def softToUni(message):
|
||||
message = message.decode(u"utf-8")
|
||||
message = message.decode("utf-8")
|
||||
return e4u.translate(message, reverse=False, **e4u.SOFTBANK_TRANSLATE_PROFILE)
|
||||
|
||||
def decodePassword(password):
|
||||
return base64.b64decode(bytes(password.encode(u"utf-8")))
|
||||
return base64.b64decode(bytes(password.encode("utf-8")))
|
||||
|
||||
def sha1hash(data):
|
||||
return base64.b64encode(hashlib.sha1(data).digest())
|
||||
return hashlib.sha1(data).hexdigest()
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
|
||||
u"""
|
||||
"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -38,11 +38,11 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
# Used to prevent duplicate messages
|
||||
self.lastMessage = {}
|
||||
|
||||
self.logger.debug(u"Backend started")
|
||||
self.logger.debug("Backend started")
|
||||
|
||||
# RequestsHandlers
|
||||
def handleLoginRequest(self, user, legacyName, password, extra):
|
||||
self.logger.debug(u"handleLoginRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
self.logger.debug("handleLoginRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
if user not in self.sessions:
|
||||
self.sessions[user] = Session(self, user, legacyName, extra)
|
||||
|
||||
|
@ -52,13 +52,13 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
self.sessions[user].login(password)
|
||||
|
||||
def handleLogoutRequest(self, user, legacyName):
|
||||
self.logger.debug(u"handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
self.logger.debug("handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
if user in self.sessions:
|
||||
self.sessions[user].logout()
|
||||
del self.sessions[user]
|
||||
|
||||
def handleMessageSendRequest(self, user, buddy, message, xhtml = u"", ID = 0):
|
||||
self.logger.debug(u"handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml)
|
||||
def handleMessageSendRequest(self, user, buddy, message, xhtml = "", ID = 0):
|
||||
self.logger.debug("handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml)
|
||||
# For some reason spectrum occasionally sends to identical messages to
|
||||
# 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
|
||||
|
@ -73,48 +73,48 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
usersMessage[buddy] = message
|
||||
|
||||
def handleJoinRoomRequest(self, user, room, nickname, pasword):
|
||||
self.logger.debug(u"handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname)
|
||||
self.logger.debug("handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname)
|
||||
self.sessions[user].joinRoom(room, nickname)
|
||||
|
||||
def handleLeaveRoomRequest(self, user, room):
|
||||
self.logger.debug(u"handleLeaveRoomRequest(user=%s, room=%s)", user, room)
|
||||
self.logger.debug("handleLeaveRoomRequest(user=%s, room=%s)", user, room)
|
||||
self.sessions[user].leaveRoom(room)
|
||||
|
||||
def handleStatusChangeRequest(self, user, status, statusMessage):
|
||||
self.logger.debug(u"handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage)
|
||||
self.logger.debug("handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage)
|
||||
self.sessions[user].changeStatusMessage(statusMessage)
|
||||
self.sessions[user].changeStatus(status)
|
||||
|
||||
def handleBuddies(self, buddies):
|
||||
u"""Called when user logs in. Used to initialize roster."""
|
||||
self.logger.debug(u"handleBuddies(buddies=%s)", buddies)
|
||||
"""Called when user logs in. Used to initialize roster."""
|
||||
self.logger.debug("handleBuddies(buddies=%s)", buddies)
|
||||
buddies = [b for b in buddies.buddy]
|
||||
if len(buddies) > 0:
|
||||
user = buddies[0].userName
|
||||
self.sessions[user].loadBuddies(buddies)
|
||||
|
||||
def handleBuddyUpdatedRequest(self, user, buddy, nick, groups):
|
||||
self.logger.debug(u"handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups))
|
||||
self.logger.debug("handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups))
|
||||
self.sessions[user].updateBuddy(buddy, nick, groups)
|
||||
|
||||
def handleBuddyRemovedRequest(self, user, buddy, groups):
|
||||
self.logger.debug(u"handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups))
|
||||
self.logger.debug("handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups))
|
||||
self.sessions[user].removeBuddy(buddy)
|
||||
|
||||
def handleTypingRequest(self, user, buddy):
|
||||
self.logger.debug(u"handleTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.logger.debug("handleTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.sessions[user].sendTypingStarted(buddy)
|
||||
|
||||
def handleTypedRequest(self, user, buddy):
|
||||
self.logger.debug(u"handleTypedRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.logger.debug("handleTypedRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.sessions[user].sendTypingStopped(buddy)
|
||||
|
||||
def handleStoppedTypingRequest(self, user, buddy):
|
||||
self.logger.debug(u"handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.logger.debug("handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.sessions[user].sendTypingStopped(buddy)
|
||||
|
||||
def handleVCardRequest(self, user, buddy, ID):
|
||||
self.logger.debug(u"handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID)
|
||||
self.logger.debug("handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID)
|
||||
self.sessions[user].requestVCard(buddy, ID)
|
||||
|
||||
|
||||
|
@ -129,7 +129,7 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
pass
|
||||
|
||||
def handleFTStartRequest(self, user, buddy, fileName, size, ftID):
|
||||
self.logger.debug(u'File send request %s, for user %s, from %s, size: %s',
|
||||
self.logger.debug('File send request %s, for user %s, from %s, size: %s',
|
||||
fileName, user, buddy, size)
|
||||
|
||||
def handleFTFinishRequest(self, user, buddy, fileName, size, ftID):
|
||||
|
@ -145,7 +145,7 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
pass
|
||||
|
||||
def handleMessageAckRequest(self, user, legacyName, ID = 0):
|
||||
self.logger.info(u"Meassage ACK request for %s !!",legacyName)
|
||||
self.logger.info("Meassage ACK request for %s !!",legacyName)
|
||||
|
||||
def sendData(self, data):
|
||||
self.io.sendData(data)
|
||||
|
|
142
yowsupwrapper.py
142
yowsupwrapper.py
|
@ -78,7 +78,7 @@ class YowsupApp(object):
|
|||
)
|
||||
|
||||
def login(self, username, password):
|
||||
u"""Login to yowsup
|
||||
"""Login to yowsup
|
||||
|
||||
Should result in onAuthSuccess or onAuthFailure to be called.
|
||||
|
||||
|
@ -102,20 +102,20 @@ class YowsupApp(object):
|
|||
self.stack.broadcastEvent(
|
||||
YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
|
||||
except TypeError as e: # Occurs when password is not correctly formated
|
||||
self.onAuthFailure(u'password not base64 encoded')
|
||||
self.onAuthFailure('password not base64 encoded')
|
||||
# try:
|
||||
# self.stack.loop(timeout=0.5, discrete=0.5)
|
||||
# except AuthError as e: # For some reason Yowsup throws an exception
|
||||
# self.onAuthFailure(u"%s" % e)
|
||||
# self.onAuthFailure("%s" % e)
|
||||
|
||||
def logout(self):
|
||||
u"""
|
||||
"""
|
||||
Logout from whatsapp
|
||||
"""
|
||||
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
|
||||
|
||||
def sendReceipt(self, _id, _from, read, participant):
|
||||
u"""
|
||||
"""
|
||||
Send a receipt (delivered: double-tick, read: blue-ticks)
|
||||
|
||||
Args:
|
||||
|
@ -128,7 +128,7 @@ class YowsupApp(object):
|
|||
self.sendEntity(receipt)
|
||||
|
||||
def sendTextMessage(self, to, message):
|
||||
u"""
|
||||
"""
|
||||
Sends a text message
|
||||
|
||||
Args:
|
||||
|
@ -140,7 +140,7 @@ class YowsupApp(object):
|
|||
return messageEntity.getId()
|
||||
|
||||
def sendLocation(self, to, latitude, longitude):
|
||||
messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, u"raw", to = to)
|
||||
messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, "raw", to = to)
|
||||
self.sendEntity(messageEntity)
|
||||
return messageEntity.getId()
|
||||
|
||||
|
@ -170,14 +170,14 @@ class YowsupApp(object):
|
|||
mediaUploader.start()
|
||||
|
||||
def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity):
|
||||
self.logger.error(u"Request upload for file %s for %s failed" % (path, jid))
|
||||
self.logger.error("Request upload for file %s for %s failed" % (path, jid))
|
||||
|
||||
def onUploadError(self, filePath, jid, url):
|
||||
#logger.error(u"Upload file %s to %s for %s failed!" % (filePath, url, jid))
|
||||
self.logger.error(u"Upload Error!")
|
||||
#logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid))
|
||||
self.logger.error("Upload Error!")
|
||||
|
||||
def onUploadProgress(self, filePath, jid, url, progress):
|
||||
#sys.stdout.write(u"%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
|
||||
#sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
|
||||
#sys.stdout.flush()
|
||||
pass
|
||||
|
||||
|
@ -197,7 +197,7 @@ class YowsupApp(object):
|
|||
|
||||
|
||||
def sendPresence(self, available):
|
||||
u"""
|
||||
"""
|
||||
Send presence to whatsapp
|
||||
|
||||
Args:
|
||||
|
@ -209,42 +209,42 @@ class YowsupApp(object):
|
|||
self.sendEntity(UnavailablePresenceProtocolEntity())
|
||||
|
||||
def subscribePresence(self, phone_number):
|
||||
u"""
|
||||
"""
|
||||
Subscribe to presence updates from phone_number
|
||||
|
||||
Args:
|
||||
- phone_number: (str) The cellphone number of the person to
|
||||
subscribe to
|
||||
"""
|
||||
self.logger.debug(u"Subscribing to Presence updates from %s", (phone_number))
|
||||
jid = phone_number + u'@s.whatsapp.net'
|
||||
self.logger.debug("Subscribing to Presence updates from %s", (phone_number))
|
||||
jid = phone_number + '@s.whatsapp.net'
|
||||
entity = SubscribePresenceProtocolEntity(jid)
|
||||
self.sendEntity(entity)
|
||||
|
||||
def unsubscribePresence(self, phone_number):
|
||||
u"""
|
||||
"""
|
||||
Unsubscribe to presence updates from phone_number
|
||||
|
||||
Args:
|
||||
- phone_number: (str) The cellphone number of the person to
|
||||
unsubscribe from
|
||||
"""
|
||||
jid = phone_number + u'@s.whatsapp.net'
|
||||
jid = phone_number + '@s.whatsapp.net'
|
||||
entity = UnsubscribePresenceProtocolEntity(jid)
|
||||
self.sendEntity(entity)
|
||||
|
||||
def leaveGroup(self, group):
|
||||
u"""
|
||||
"""
|
||||
Permanently leave a WhatsApp group
|
||||
|
||||
Args:
|
||||
- group: (str) the group id (e.g. 27831788123-144024456)
|
||||
"""
|
||||
entity = LeaveGroupsIqProtocolEntity([group + u'@g.us'])
|
||||
entity = LeaveGroupsIqProtocolEntity([group + '@g.us'])
|
||||
self.sendEntity(entity)
|
||||
|
||||
def setStatus(self, statusText):
|
||||
u"""
|
||||
"""
|
||||
Send status to whatsapp
|
||||
|
||||
Args:
|
||||
|
@ -254,14 +254,14 @@ class YowsupApp(object):
|
|||
self.sendIq(iq)
|
||||
|
||||
def sendTyping(self, phoneNumber, typing):
|
||||
u"""
|
||||
"""
|
||||
Notify buddy using phoneNumber that you are typing to him
|
||||
|
||||
Args:
|
||||
- phoneNumber: (str) cellphone number of the buddy you are typing to.
|
||||
- typing: (bool) True if you are typing, False if you are not
|
||||
"""
|
||||
jid = phoneNumber + u'@s.whatsapp.net'
|
||||
jid = phoneNumber + '@s.whatsapp.net'
|
||||
if typing:
|
||||
state = OutgoingChatstateProtocolEntity(
|
||||
ChatstateProtocolEntity.STATE_TYPING, jid
|
||||
|
@ -273,7 +273,7 @@ class YowsupApp(object):
|
|||
self.sendEntity(state)
|
||||
|
||||
def sendSync(self, contacts, delta = False, interactive = True):
|
||||
u"""
|
||||
"""
|
||||
You need to sync new contacts before you interact with
|
||||
them, failure to do so could result in a temporary ban.
|
||||
|
||||
|
@ -293,7 +293,7 @@ class YowsupApp(object):
|
|||
self.sendIq(iq)
|
||||
|
||||
def requestStatuses(self, contacts, success = None, failure = None):
|
||||
u"""
|
||||
"""
|
||||
Request the statuses of a number of users.
|
||||
|
||||
Args:
|
||||
|
@ -302,19 +302,19 @@ class YowsupApp(object):
|
|||
- success: (func) called when request is successful
|
||||
- failure: (func) called when request has failed
|
||||
"""
|
||||
iq = GetStatusesIqProtocolEntity([c + u'@s.whatsapp.net' for c in contacts])
|
||||
iq = GetStatusesIqProtocolEntity([c + '@s.whatsapp.net' for c in contacts])
|
||||
def onSuccess(response, request):
|
||||
self.logger.debug(u"Received Statuses %s", response)
|
||||
self.logger.debug("Received Statuses %s", response)
|
||||
s = {}
|
||||
for k, v in response.statuses.iteritems():
|
||||
s[k.split(u'@')[0]] = v
|
||||
s[k.split('@')[0]] = v
|
||||
success(s)
|
||||
|
||||
self.sendIq(iq, onSuccess = onSuccess, onError = failure)
|
||||
|
||||
|
||||
def requestLastSeen(self, phoneNumber, success = None, failure = None):
|
||||
u"""
|
||||
"""
|
||||
Requests when user was last seen.
|
||||
Args:
|
||||
- phone_number: (str) the phone number of the user
|
||||
|
@ -323,22 +323,22 @@ class YowsupApp(object):
|
|||
since last seen.
|
||||
- failure: (func) called when request has failed
|
||||
"""
|
||||
iq = LastseenIqProtocolEntity(phoneNumber + u'@s.whatsapp.net')
|
||||
iq = LastseenIqProtocolEntity(phoneNumber + '@s.whatsapp.net')
|
||||
self.sendIq(iq, onSuccess = partial(self._lastSeenSuccess, success),
|
||||
onError = failure)
|
||||
|
||||
def _lastSeenSuccess(self, success, response, request):
|
||||
success(response._from.split(u'@')[0], response.seconds)
|
||||
success(response._from.split('@')[0], response.seconds)
|
||||
|
||||
def requestProfilePicture(self, phoneNumber, onSuccess = None, onFailure = None):
|
||||
u"""
|
||||
"""
|
||||
Requests profile picture of whatsapp user
|
||||
Args:
|
||||
- phoneNumber: (str) the phone number of the user
|
||||
- onSuccess: (func) called when request is successfully processed.
|
||||
- onFailure: (func) called when request has failed
|
||||
"""
|
||||
iq = GetPictureIqProtocolEntity(phoneNumber + u'@s.whatsapp.net')
|
||||
iq = GetPictureIqProtocolEntity(phoneNumber + '@s.whatsapp.net')
|
||||
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
|
||||
|
||||
def requestGroupsList(self, onSuccess = None, onFailure = None):
|
||||
|
@ -346,7 +346,7 @@ class YowsupApp(object):
|
|||
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
|
||||
|
||||
def requestGroupInfo(self, group, onSuccess = None, onFailure = None):
|
||||
u"""
|
||||
"""
|
||||
Request info on a specific group (includes participants, subject, owner etc.)
|
||||
|
||||
Args:
|
||||
|
@ -354,11 +354,11 @@ class YowsupApp(object):
|
|||
- onSuccess: (func) called when request is successfully processed.
|
||||
- onFailure: (func) called when request is has failed
|
||||
"""
|
||||
iq = InfoGroupsIqProtocolEntity(group + u'@g.us')
|
||||
iq = InfoGroupsIqProtocolEntity(group + '@g.us')
|
||||
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
|
||||
|
||||
def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t):
|
||||
u"""
|
||||
"""
|
||||
Called when login is successful.
|
||||
|
||||
Args:
|
||||
|
@ -373,7 +373,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAuthFailure(self, reason):
|
||||
u"""
|
||||
"""
|
||||
Called when login is a failure
|
||||
|
||||
Args:
|
||||
|
@ -382,7 +382,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onReceipt(self, _id, _from, timestamp, type, participant, offline, items):
|
||||
u"""
|
||||
"""
|
||||
Called when a receipt is received (double tick or blue tick)
|
||||
|
||||
Args
|
||||
|
@ -398,7 +398,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAck(self, _id,_class, _from, timestamp):
|
||||
u"""
|
||||
"""
|
||||
Called when Ack is received
|
||||
|
||||
Args:
|
||||
|
@ -410,7 +410,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onPresenceReceived(self, _type, name, _from, last):
|
||||
u"""
|
||||
"""
|
||||
Called when presence (e.g. available, unavailable) is received
|
||||
from whatsapp
|
||||
|
||||
|
@ -423,12 +423,12 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onDisconnect(self):
|
||||
u"""
|
||||
"""
|
||||
Called when disconnected from whatsapp
|
||||
"""
|
||||
|
||||
def onContactTyping(self, number):
|
||||
u"""
|
||||
"""
|
||||
Called when contact starts to type
|
||||
|
||||
Args:
|
||||
|
@ -437,7 +437,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onContactPaused(self, number):
|
||||
u"""
|
||||
"""
|
||||
Called when contact stops typing
|
||||
|
||||
Args:
|
||||
|
@ -446,7 +446,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onTextMessage(self, _id, _from, to, notify, timestamp, participant, offline, retry, body):
|
||||
u"""
|
||||
"""
|
||||
Called when text message is received
|
||||
|
||||
Args:
|
||||
|
@ -463,7 +463,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onImage(self, entity):
|
||||
u"""
|
||||
"""
|
||||
Called when image message is received
|
||||
|
||||
Args:
|
||||
|
@ -472,7 +472,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAudio(self, entity):
|
||||
u"""
|
||||
"""
|
||||
Called when audio message is received
|
||||
|
||||
Args:
|
||||
|
@ -482,7 +482,7 @@ class YowsupApp(object):
|
|||
|
||||
|
||||
def onVideo(self, entity):
|
||||
u"""
|
||||
"""
|
||||
Called when video message is received
|
||||
|
||||
Args:
|
||||
|
@ -491,7 +491,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onLocation(self, entity):
|
||||
u"""
|
||||
"""
|
||||
Called when location message is received
|
||||
|
||||
Args:
|
||||
|
@ -500,7 +500,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant):
|
||||
u"""
|
||||
"""
|
||||
Called when VCard message is received
|
||||
|
||||
Args:
|
||||
|
@ -516,15 +516,15 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAddedToGroup(self, entity):
|
||||
u"""Called when the user has been added to a new group"""
|
||||
"""Called when the user has been added to a new group"""
|
||||
pass
|
||||
|
||||
def onParticipantsAddedToGroup(self, entity):
|
||||
u"""Called when participants have been added to a group"""
|
||||
"""Called when participants have been added to a group"""
|
||||
pass
|
||||
|
||||
def onParticipantsRemovedFromGroup(self, group, participants):
|
||||
u"""Called when participants have been removed from a group
|
||||
"""Called when participants have been removed from a group
|
||||
|
||||
Args:
|
||||
- group: (str) id of the group (e.g. 27831788123-144024456)
|
||||
|
@ -533,7 +533,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def sendEntity(self, entity):
|
||||
u"""Sends an entity down the stack (as if YowsupAppLayer called toLower)"""
|
||||
"""Sends an entity down the stack (as if YowsupAppLayer called toLower)"""
|
||||
self.stack.broadcastEvent(YowLayerEvent(YowsupAppLayer.TO_LOWER_EVENT,
|
||||
entity = entity
|
||||
))
|
||||
|
@ -551,9 +551,9 @@ class YowsupApp(object):
|
|||
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
|
||||
|
||||
class YowsupAppLayer(YowInterfaceLayer):
|
||||
EVENT_START = u'transwhat.event.YowsupAppLayer.start'
|
||||
TO_LOWER_EVENT = u'transwhat.event.YowsupAppLayer.toLower'
|
||||
SEND_IQ = u'transwhat.event.YowsupAppLayer.sendIq'
|
||||
EVENT_START = 'transwhat.event.YowsupAppLayer.start'
|
||||
TO_LOWER_EVENT = 'transwhat.event.YowsupAppLayer.toLower'
|
||||
SEND_IQ = 'transwhat.event.YowsupAppLayer.sendIq'
|
||||
|
||||
def onEvent(self, layerEvent):
|
||||
# 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 True otherwise
|
||||
if layerEvent.getName() == YowsupAppLayer.EVENT_START:
|
||||
self.caller = layerEvent.getArg(u'caller')
|
||||
self.caller = layerEvent.getArg('caller')
|
||||
self.logger = logging.getLogger(self.__class__.__name__)
|
||||
return True
|
||||
elif layerEvent.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECTED:
|
||||
self.caller.onDisconnect()
|
||||
return True
|
||||
elif layerEvent.getName() == YowsupAppLayer.TO_LOWER_EVENT:
|
||||
self.toLower(layerEvent.getArg(u'entity'))
|
||||
self.toLower(layerEvent.getArg('entity'))
|
||||
return True
|
||||
elif layerEvent.getName() == YowsupAppLayer.SEND_IQ:
|
||||
iq = layerEvent.getArg(u'iq')
|
||||
success = layerEvent.getArg(u'success')
|
||||
failure = layerEvent.getArg(u'failure')
|
||||
iq = layerEvent.getArg('iq')
|
||||
success = layerEvent.getArg('success')
|
||||
failure = layerEvent.getArg('failure')
|
||||
self._sendIq(iq, success, failure)
|
||||
return True
|
||||
return False
|
||||
|
||||
@ProtocolEntityCallback(u'success')
|
||||
@ProtocolEntityCallback('success')
|
||||
def onAuthSuccess(self, entity):
|
||||
# entity is SuccessProtocolEntity
|
||||
status = entity.status
|
||||
|
@ -587,21 +587,21 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
expiration = entity.expiration
|
||||
props = entity.props
|
||||
nonce = entity.nonce
|
||||
t = entity.t # I donu't know what this is
|
||||
t = entity.t # I don't know what this is
|
||||
self.caller.onAuthSuccess(status, kind, creation, expiration, props, nonce, t)
|
||||
|
||||
@ProtocolEntityCallback('failureu')
|
||||
@ProtocolEntityCallback('failure')
|
||||
def onAuthFailure(self, entity):
|
||||
# entity is FailureProtocolEntity
|
||||
reason = entity.reason
|
||||
self.caller.onAuthFailure(reason)
|
||||
|
||||
@ProtocolEntityCallback('receiptu')
|
||||
@ProtocolEntityCallback('receipt')
|
||||
def onReceipt(self, entity):
|
||||
"""Sends ack automatically"""
|
||||
# entity is IncomingReceiptProtocolEntity
|
||||
ack = OutgoingAckProtocolEntity(entity.getId(),
|
||||
'receiptu', entity.getType(), entity.getFrom())
|
||||
'receipt', entity.getType(), entity.getFrom())
|
||||
self.toLower(ack)
|
||||
_id = entity._id
|
||||
_from = entity._from
|
||||
|
@ -612,7 +612,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
items = entity.items
|
||||
self.caller.onReceipt(_id, _from, timestamp, type, participant, offline, items)
|
||||
|
||||
@ProtocolEntityCallback('acku')
|
||||
@ProtocolEntityCallback('ack')
|
||||
def onAck(self, entity):
|
||||
# entity is IncomingAckProtocolEntity
|
||||
self.caller.onAck(
|
||||
|
@ -622,7 +622,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
entity.timestamp
|
||||
)
|
||||
|
||||
@ProtocolEntityCallback('notificationu')
|
||||
@ProtocolEntityCallback('notification')
|
||||
def onNotification(self, entity):
|
||||
"""
|
||||
Sends ack automatically
|
||||
|
@ -635,11 +635,11 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
self.caller.onParticipantsAddedToGroup(entity)
|
||||
elif isinstance(entity, RemoveGroupsNotificationProtocolEntity):
|
||||
self.caller.onParticipantsRemovedFromGroup(
|
||||
entity.getGroupId().split('@u')[0],
|
||||
entity.getGroupId().split('@')[0],
|
||||
entity.getParticipants().keys()
|
||||
)
|
||||
|
||||
@ProtocolEntityCallback('messageu')
|
||||
@ProtocolEntityCallback('message')
|
||||
def onMessageReceived(self, entity):
|
||||
self.logger.debug("Received Message: %s", entity)
|
||||
if entity.getType() == MessageProtocolEntity.MESSAGE_TYPE_TEXT:
|
||||
|
@ -677,7 +677,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
elif isinstance(entity, LocationMediaMessageProtocolEntity):
|
||||
self.caller.onLocation(entity)
|
||||
|
||||
@ProtocolEntityCallback('presenceu')
|
||||
@ProtocolEntityCallback('presence')
|
||||
def onPresenceReceived(self, presence):
|
||||
_type = presence.getType()
|
||||
name = presence.getName()
|
||||
|
@ -685,7 +685,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
last = presence.getLast()
|
||||
self.caller.onPresenceReceived(_type, name, _from, last)
|
||||
|
||||
@ProtocolEntityCallback('chatstateu')
|
||||
@ProtocolEntityCallback('chatstate')
|
||||
def onChatstate(self, chatstate):
|
||||
number = chatstate._from.split('@')[0]
|
||||
if chatstate.getState() == ChatstateProtocolEntity.STATE_TYPING:
|
||||
|
|
Loading…
Reference in a new issue