lots of whitespace cleanups

This commit is contained in:
Steffen Vogel 2016-04-06 22:02:40 +02:00
parent c005c31afa
commit 22725c042f
5 changed files with 113 additions and 136 deletions

View file

@ -277,13 +277,11 @@ class SpectrumBackend:
self.handleMessageSendRequest(payload.userName, payload.buddyName, payload.message, payload.xhtml, payload.id) self.handleMessageSendRequest(payload.userName, payload.buddyName, payload.message, payload.xhtml, payload.id)
def handleConvMessageAckPayload(self, data): def handleConvMessageAckPayload(self, data):
payload = protocol_pb2.ConversationMessage() payload = protocol_pb2.ConversationMessage()
if (payload.ParseFromString(data) == False): if (payload.ParseFromString(data) == False):
#TODO: ERROR #TODO: ERROR
return return
self.handleMessageAckRequest(payload.userName, payload.buddyName, payload.id) self.handleMessageAckRequest(payload.userName, payload.buddyName, payload.id)
def handleAttentionPayload(self, data): def handleAttentionPayload(self, data):
payload = protocol_pb2.ConversationMessage() payload = protocol_pb2.ConversationMessage()
@ -452,7 +450,7 @@ class SpectrumBackend:
elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_EXIT: elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_EXIT:
self.handleExitRequest() self.handleExitRequest()
elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_CONV_MESSAGE_ACK: elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_CONV_MESSAGE_ACK:
self.handleConvMessageAckPayload(wrapper.payload) self.handleConvMessageAckPayload(wrapper.payload)
elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_RAW_XML: elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_RAW_XML:
self.handleRawXmlRequest(wrapper.payload) self.handleRawXmlRequest(wrapper.payload)
elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_BUDDIES: elif wrapper.type == protocol_pb2.WrapperMessage.TYPE_BUDDIES:
@ -543,14 +541,14 @@ class SpectrumBackend:
raise NotImplementedError, "Implement me" raise NotImplementedError, "Implement me"
def handleMessageAckRequest(self, user, legacyName, ID = 0): def handleMessageAckRequest(self, user, legacyName, ID = 0):
""" """
Called when XMPP user sends message to legacy network. Called when XMPP user sends message to legacy network.
@param user: XMPP JID of user for which this event occurs. @param user: XMPP JID of user for which this event occurs.
@param legacyName: Legacy network name of buddy or room. @param legacyName: Legacy network name of buddy or room.
@param ID: message ID @param ID: message ID
""" """
# raise NotImplementedError, "Implement me" # raise NotImplementedError, "Implement me"
pass pass

2
bot.py
View file

@ -37,7 +37,7 @@ class Bot():
self.commands = { self.commands = {
"help": self._help, "help": self._help,
"prune": self._prune, "prune": self._prune,
"groups": self._groups, "groups": self._groups,
"getgroups": self._getgroups "getgroups": self._getgroups
} }

View file

@ -45,13 +45,10 @@ from yowsupwrapper import YowsupApp
class MsgIDs: class MsgIDs:
def __init__(self, xmppId, waId): def __init__(self, xmppId, waId):
self.xmppId = xmppId self.xmppId = xmppId
self.waId = waId self.waId = waId
self.cnt = 0 self.cnt = 0
class Session(YowsupApp): class Session(YowsupApp):
broadcast_prefix = u'\U0001F4E2 ' broadcast_prefix = u'\U0001F4E2 '
@ -335,7 +332,7 @@ class Session(YowsupApp):
def onAudio(self, audio): def onAudio(self, audio):
self.logger.debug('Received audio message %s', str(audio)) self.logger.debug('Received audio message %s', str(audio))
buddy = audio._from.split('@')[0] buddy = audio._from.split('@')[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('@')[0]
@ -354,7 +351,7 @@ class Session(YowsupApp):
def onVideo(self, video): def onVideo(self, video):
self.logger.debug('Received video message %s', str(video)) self.logger.debug('Received video message %s', str(video))
buddy = video._from.split('@')[0] buddy = video._from.split('@')[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
@ -375,12 +372,10 @@ class Session(YowsupApp):
latitude = location.getLatitude() latitude = location.getLatitude()
longitude = location.getLongitude() longitude = location.getLongitude()
url = location.getLocationURL() url = location.getLocationURL()
participant = location.participant participant = location.participant
latlong = 'geo:' + latitude + ',' + longitude latlong = 'geo:' + latitude + ',' + longitude
self.logger.debug("Location received from %s: %s, %s", self.logger.debug("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('@')[0]
@ -563,8 +558,6 @@ class Session(YowsupApp):
else: else:
self.onPresenceAvailable(buddy) self.onPresenceAvailable(buddy)
def onPresenceAvailable(self, buddy): def onPresenceAvailable(self, buddy):
self.logger.info("Is available: %s", buddy) self.logger.info("Is available: %s", buddy)
self.buddies.updateSpectrum(buddy) self.buddies.updateSpectrum(buddy)
@ -674,60 +667,46 @@ class Session(YowsupApp):
self.sendTextMessage(room + '@g.us', message) self.sendTextMessage(room + '@g.us', message)
else: # private msg else: # private msg
buddy = sender buddy = sender
# if message == "\\lastseen":
# self.call("presence_request", buddy = (buddy + "@s.whatsapp.net",))
# else:
if message.split(" ").pop(0) == "\\lastseen": if message.split(" ").pop(0) == "\\lastseen":
self.presenceRequested.append(buddy) self.presenceRequested.append(buddy)
#self.call("presence_request", (buddy + "@s.whatsapp.net",)) self._requestLastSeen(buddy)
self._requestLastSeen(buddy) elif message.split(" ").pop(0) == "\\gpp":
elif message.split(" ").pop(0) == "\\gpp": self.sendMessageToXMPP(buddy, "Fetching Profile Picture")
self.logger.info("Get Profile Picture! ") self.requestVCard(buddy)
self.sendMessageToXMPP(buddy, "Fetching Profile Picture") elif (".jpg" in message.lower()) or (".webp" in message.lower()):
#self.call("contact_getProfilePicture", (buddy + "@s.whatsapp.net",)) self.sendImage(message, ID, buddy + "@s.whatsapp.net")
self.requestVCard(buddy) elif "geo:" in message.lower():
else: self._sendLocation(buddy + "@s.whatsapp.net", message, ID)
if (".jpg" in message.lower()) or (".webp" in message.lower()): else:
self.sendImage(message, ID, buddy + "@s.whatsapp.net") waId = self.sendTextMessage(sender + '@s.whatsapp.net', message)
elif "geo:" in message.lower(): self.msgIDs[waId] = MsgIDs(ID, waId)
self._sendLocation(buddy + "@s.whatsapp.net", message, ID)
else:
waId = self.sendTextMessage(sender + '@s.whatsapp.net', message)
self.msgIDs[waId] = MsgIDs( ID, waId)
self.logger.info("WA Message send to %s with ID %s", buddy, waId) self.logger.info("WA Message send to %s with ID %s", buddy, waId)
#self.sendTextMessage(sender + '@s.whatsapp.net', message)
def executeCommand(self, command, room): def executeCommand(self, command, room):
if command == '\\leave': if command == '\\leave':
self.logger.debug("Leaving room %s", room) self.logger.debug("Leaving room %s", room)
# Leave group on whatsapp side self.leaveGroup(room) # Leave group on whatsapp side
self.leaveGroup(room)
# Delete Room on spectrum side
group = self.groups[room] group = self.groups[room]
group.leaveRoom() group.leaveRoom() # Delete Room on spectrum side
del self.groups[room] del self.groups[room]
def _requestLastSeen(self, buddy): def _requestLastSeen(self, buddy):
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("%a, %d %b %Y %H:%M:%S", timestamp)
self.sendMessageToXMPP(buddy, "%s (%s) %s" % (timestring, utils.ago(lastseen),str(lastseen))) self.sendMessageToXMPP(buddy, "%s (%s) %s" % (timestring, utils.ago(lastseen),str(lastseen)))
def onError(errorIqEntity, originalIqEntity):
self.sendMessageToXMPP(errorIqEntity.getFrom(), "LastSeen Error") def onError(errorIqEntity, originalIqEntity):
self.sendMessageToXMPP(errorIqEntity.getFrom(), "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: latitude,longitude = message.split(':')[1].split(',')
# raw = base64.b64encode(imageFile.read()) waId = self.sendLocation(buddy, float(latitude), float(longitude))
latitude,longitude = message.split(':')[1].split(',') self.msgIDs[waId] = MsgIDs( ID, waId)
waId = self.sendLocation(buddy, float(latitude), float(longitude)) self.logger.info("WA Location Message send to %s with ID %s", buddy, waId)
self.msgIDs[waId] = MsgIDs( ID, waId)
self.logger.info("WA Location Message send to %s with ID %s", buddy, waId)
def sendMessageToXMPP(self, buddy, messageContent, timestamp = "", nickname = ""): def sendMessageToXMPP(self, buddy, messageContent, timestamp = "", nickname = ""):
if timestamp: if timestamp:
@ -831,24 +810,24 @@ class Session(YowsupApp):
self.buddies.requestVCard(buddy, ID) self.buddies.requestVCard(buddy, ID)
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 + '_thumbnail'
if width > height: if width > height:
nheight = float(height) / width * size nheight = float(height) / width * size
nwidth = size nwidth = size
else: else:
nwidth = float(width) / height * size nwidth = float(width) / height * size
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, 'JPEG')
with open(img_thumbnail, 'rb') as imageFile: with open(img_thumbnail, '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):
@ -857,15 +836,16 @@ class Session(YowsupApp):
url = "http://maps.google.de?%s" % urllib.urlencode({ "q": "%s %s" % (latitude, longitude) }) url = "http://maps.google.de?%s" % urllib.urlencode({ "q": "%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("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("@")[0]
buddy = jid.split("@")[0] buddy = jid.split("@")[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("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):
@ -875,15 +855,15 @@ class Session(YowsupApp):
self.logger.info("Removed %s from room %s", buddy, room) self.logger.info("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("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("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("notification_ack", (jid, messageId))

View file

@ -160,7 +160,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("Meassage ACK request for %s !!",legacyName)
def sendData(self, data): def sendData(self, data):
self.io.sendData(data) self.io.sendData(data)

View file

@ -185,64 +185,63 @@ class YowsupApp(object):
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, "raw", to = to)
self.sendEntity(messageEntity) self.sendEntity(messageEntity)
return messageEntity.getId()
return messageEntity.getId()
def sendImage(self, jid, path, caption = None, onSuccess = None, onFailure = None): def sendImage(self, jid, path, caption = None, onSuccess = None, onFailure = None):
entity = RequestUploadIqProtocolEntity(RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, filePath=path) entity = RequestUploadIqProtocolEntity(RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, filePath=path)
successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, path, successEntity, originalEntity, caption, onSuccess, onFailure) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, path, successEntity, originalEntity, caption, onSuccess, onFailure)
errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity)
self.sendIq(entity, successFn, errorFn) self.sendIq(entity, successFn, errorFn)
def onRequestUploadResult(self, jid, filePath, resultRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity, caption = None, onSuccess=None, onFailure=None): def onRequestUploadResult(self, jid, filePath, resultRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity, caption = None, onSuccess=None, onFailure=None):
if requestUploadIqProtocolEntity.mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO:
doSendFn = self.doSendAudio
else:
doSendFn = self.doSendImage
if requestUploadIqProtocolEntity.mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO: if resultRequestUploadIqProtocolEntity.isDuplicate():
doSendFn = self.doSendAudio doSendFn(filePath, resultRequestUploadIqProtocolEntity.getUrl(), jid,
else: resultRequestUploadIqProtocolEntity.getIp(), caption)
doSendFn = self.doSendImage else:
successFn = lambda filePath, jid, url: doSendFn(filePath, url, jid, resultRequestUploadIqProtocolEntity.getIp(), caption, onSuccess, onFailure)
if resultRequestUploadIqProtocolEntity.isDuplicate(): ownNumber = self.stack.getLayerInterface(YowAuthenticationProtocolLayer).getUsername(full=False)
doSendFn(filePath, resultRequestUploadIqProtocolEntity.getUrl(), jid,
resultRequestUploadIqProtocolEntity.getIp(), caption)
else:
successFn = lambda filePath, jid, url: doSendFn(filePath, url, jid, resultRequestUploadIqProtocolEntity.getIp(), caption, onSuccess, onFailure)
ownNumber = self.stack.getLayerInterface(YowAuthenticationProtocolLayer).getUsername(full=False)
mediaUploader = MediaUploader(jid, ownNumber, filePath,
resultRequestUploadIqProtocolEntity.getUrl(),
resultRequestUploadIqProtocolEntity.getResumeOffset(),
successFn, self.onUploadError, self.onUploadProgress, async=False)
mediaUploader.start()
def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity): mediaUploader = MediaUploader(jid, ownNumber, filePath,
self.logger.error("Request upload for file %s for %s failed" % (path, jid)) resultRequestUploadIqProtocolEntity.getUrl(),
resultRequestUploadIqProtocolEntity.getResumeOffset(),
successFn, self.onUploadError, self.onUploadProgress, async=False)
def onUploadError(self, filePath, jid, url): mediaUploader.start()
#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): def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity):
#sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress)) self.logger.error("Request upload for file %s for %s failed" % (path, jid))
#sys.stdout.flush()
pass
def doSendImage(self, filePath, url, to, ip = None, caption = None, onSuccess = None, onFailure = None): def onUploadError(self, filePath, jid, url):
entity = ImageDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to, caption = caption) self.logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid))
self.sendEntity(entity)
def onUploadProgress(self, filePath, jid, url, progress):
#sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
#sys.stdout.flush()
pass
def doSendImage(self, filePath, url, to, ip = None, caption = None, onSuccess = None, onFailure = None):
entity = ImageDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to, caption = caption)
self.sendEntity(entity)
#self.msgIDs[entity.getId()] = MsgIDs(self.imgMsgId, entity.getId()) #self.msgIDs[entity.getId()] = MsgIDs(self.imgMsgId, entity.getId())
if onSuccess is not None: if onSuccess is not None:
onSuccess(entity.getId()) onSuccess(entity.getId())
return entity.getId() return entity.getId()
def doSendAudio(self, filePath, url, to, ip = None, caption = None, onSuccess = None, onFailure = None):
entity = AudioDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to)
self.sendEntity(entity)
#self.msgIDs[entity.getId()] = MsgIDs(self.imgMsgId, entity.getId())
if onSuccess is not None:
onSuccess(entity.getId())
return entity.getId()
def doSendAudio(self, filePath, url, to, ip = None, caption = None, onSuccess = None, onFailure = None):
entity = AudioDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to)
self.sendEntity(entity)
#self.msgIDs[entity.getId()] = MsgIDs(self.imgMsgId, entity.getId())
if onSuccess is not None:
onSuccess(entity.getId())
return entity.getId()
def sendPresence(self, available): def sendPresence(self, available):
""" """