fixes for Python 3

This commit is contained in:
Steffen Vogel 2019-04-25 22:41:45 +02:00
parent c79de527ff
commit 2ec730020f
8 changed files with 59 additions and 67 deletions

View file

@ -1,15 +1,10 @@
from Spectrum2 import protocol_pb2
import logging import logging
import time import time
import base64 import base64
import hashlib import hashlib
import Spectrum2
import deferred from . import deferred
from deferred import call
def sha1hash(data):
hashlib.sha1(data).hexdigest()
class Buddy(): class Buddy():
def __init__(self, owner, number, nick, statusMsg, groups, image_hash): def __init__(self, owner, number, nick, statusMsg, groups, image_hash):
@ -120,11 +115,11 @@ 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 = Spectrum2.protocol_pb2.STATUS_NONE
elif buddy.presence == 'unavailable': elif buddy.presence == 'unavailable':
status = protocol_pb2.STATUS_AWAY status = Spectrum2.protocol_pb2.STATUS_AWAY
else: else:
status = protocol_pb2.STATUS_ONLINE status = Spectrum2.protocol_pb2.STATUS_ONLINE
statusmsg = buddy.statusMsg statusmsg = buddy.statusMsg
if buddy.lastseen != 0: if buddy.lastseen != 0:
@ -144,7 +139,7 @@ class BuddyList(dict):
buddy = self[number] buddy = self[number]
del self[number] del self[number]
self.backend.handleBuddyChanged(self.user, number, "", [], self.backend.handleBuddyChanged(self.user, number, "", [],
protocol_pb2.STATUS_NONE) Spectrum2.protocol_pb2.STATUS_NONE)
self.backend.handleBuddyRemoved(self.user, number) self.backend.handleBuddyRemoved(self.user, number)
self.session.unsubscribePresence(number) self.session.unsubscribePresence(number)
# TODO Sync remove # TODO Sync remove
@ -182,9 +177,9 @@ class BuddyList(dict):
pictureData = response.pictureData() pictureData = response.pictureData()
# Send VCard # Send VCard
if ID != None: if ID != None:
call(self.logger.debug, 'Sending VCard (%s) with image id %s: %s' % deferred.call(self.logger.debug, 'Sending VCard (%s) with image id %s: %s' %
(ID, response.pictureId(), pictureData.then(base64.b64encode))) (ID, response.pictureId(), pictureData.then(base64.b64encode)))
call(self.backend.handleVCard, self.user, ID, buddy, "", "", deferred.call(self.backend.handleVCard, self.user, ID, buddy, "", "",
pictureData) pictureData)
# If error # If error
error.when(self.logger.debug, 'Sending VCard (%s) without image' % ID) error.when(self.logger.debug, 'Sending VCard (%s) without image' % ID)
@ -199,9 +194,14 @@ class BuddyList(dict):
except KeyError: except KeyError:
nick = "" nick = ""
groups = [] groups = []
def sha1hash(data):
hashlib.sha1(data).hexdigest()
image_hash = pictureData.then(sha1hash) image_hash = pictureData.then(sha1hash)
call(self.logger.debug, 'Image hash is %s' % image_hash)
call(self.update, buddynr, nick, groups, image_hash) deferred.call(self.logger.debug, 'Image hash is %s' % image_hash)
deferred.call(self.update, buddynr, nick, groups, image_hash)
# No image # No image
error.when(self.logger.debug, 'No image') error.when(self.logger.debug, 'No image')
error.when(self.update, buddynr, nick, groups, '') error.when(self.update, buddynr, nick, groups, '')

View file

@ -1,4 +1,4 @@
from Spectrum2 import protocol_pb2 import Spectrum2
class Group(): class Group():
@ -39,40 +39,40 @@ class Group():
def sendParticipantsToSpectrum(self, yourNumber): def sendParticipantsToSpectrum(self, yourNumber):
for number, nick in self.participants.iteritems(): for number, nick in self.participants.iteritems():
if number == self.owner: if number == self.owner:
flags = protocol_pb2.PARTICIPANT_FLAG_MODERATOR flags = Spectrum2.protocol_pb2.PARTICIPANT_FLAG_MODERATOR
else: else:
flags = protocol_pb2.PARTICIPANT_FLAG_NONE flags = Spectrum2.protocol_pb2.PARTICIPANT_FLAG_NONE
if number == yourNumber: if number == yourNumber:
flags = flags | protocol_pb2.PARTICIPANT_FLAG_ME flags = flags | Spectrum2.protocol_pb2.PARTICIPANT_FLAG_ME
try: try:
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, self._updateParticipant(number, flags, Spectrum2.protocol_pb2.STATUS_ONLINE,
self.backend.sessions[self.user].buddies[number].image_hash) self.backend.sessions[self.user].buddies[number].image_hash)
except KeyError: except KeyError:
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE) self._updateParticipant(number, flags, Spectrum2.protocol_pb2.STATUS_ONLINE)
def removeParticipants(self, participants): def removeParticipants(self, participants):
for jid in participants: for jid in participants:
number = jid.split('@')[0] number = jid.split('@')[0]
nick = self.participants[number] nick = self.participants[number]
flags = protocol_pb2.PARTICIPANT_FLAG_NONE flags = Spectrum2.protocol_pb2.PARTICIPANT_FLAG_NONE
self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE) self._updateParticipant(number, flags, Spectrum2.protocol_pb2.STATUS_NONE)
del self.participants[number] del self.participants[number]
def leaveRoom(self): def leaveRoom(self):
for number in self.participants: for number in self.participants:
nick = self.participants[number] nick = self.participants[number]
flags = protocol_pb2.PARTICIPANT_FLAG_ROOM_NOT_FOUND flags = Spectrum2.protocol_pb2.PARTICIPANT_FLAG_ROOM_NOT_FOUND
self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE) self._updateParticipant(number, flags, Spectrum2.protocol_pb2.STATUS_NONE)
def changeNick(self, number, new_nick): def changeNick(self, number, new_nick):
if self.participants[number] == new_nick: if self.participants[number] == new_nick:
return return
if number == self.owner: if number == self.owner:
flags = protocol_pb2.PARTICIPANT_FLAG_MODERATOR flags = Spectrum2.protocol_pb2.PARTICIPANT_FLAG_MODERATOR
else: else:
flags = protocol_pb2.PARTICIPANT_FLAG_NONE flags = Spectrum2.protocol_pb2.PARTICIPANT_FLAG_NONE
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, new_nick) self._updateParticipant(number, flags, Spectrum2.protocol_pb2.STATUS_ONLINE, new_nick)
self.participants[number] = new_nick self.participants[number] = new_nick
def _updateParticipant(self, number, flags, status, imageHash = "", newNick = ""): def _updateParticipant(self, number, flags, status, imageHash = "", newNick = ""):

View file

@ -1,9 +1,11 @@
from Spectrum2 import protocol_pb2
from yowsupwrapper import YowsupApp
import logging
import threadutils
import sys import sys
import logging
import Spectrum2
from .yowsupwrapper import YowsupApp
from . import threadutils
class RegisterSession(YowsupApp): class RegisterSession(YowsupApp):
""" """
@ -22,7 +24,7 @@ class RegisterSession(YowsupApp):
def login(self, password=""): def login(self, password=""):
self.backend.handleConnected(self.user) self.backend.handleConnected(self.user)
self.backend.handleBuddyChanged(self.user, 'bot', 'bot', self.backend.handleBuddyChanged(self.user, 'bot', 'bot',
['Admin'], protocol_pb2.STATUS_ONLINE) ['Admin'], Spectrum2.protocol_pb2.STATUS_ONLINE)
self.backend.handleMessage(self.user, 'bot', self.backend.handleMessage(self.user, 'bot',
'Please enter your country code') 'Please enter your country code')

View file

@ -1,24 +1,18 @@
import logging import logging
import urllib import urllib
import time import time
import sys
import os import os
reload(sys)
sys.setdefaultencoding("utf-8")
from yowsup.layers.protocol_media.mediauploader import MediaUploader from yowsup.layers.protocol_media.mediauploader import MediaUploader
from yowsup.layers.protocol_media.mediadownloader import MediaDownloader from yowsup.layers.protocol_media.mediadownloader import MediaDownloader
from Spectrum2 import protocol_pb2 import Spectrum2
from buddy import BuddyList from . import deferred
from threading import Timer from .buddy import BuddyList
from group import Group from .group import Group
from bot import Bot from .bot import Bot
import deferred from .yowsupwrapper import YowsupApp
from deferred import call
from yowsupwrapper import YowsupApp
def ago(secs): def ago(secs):
periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"] periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"]
@ -56,7 +50,7 @@ class Session(YowsupApp):
self.user = user self.user = user
self.legacyName = legacyName self.legacyName = legacyName
self.status = protocol_pb2.STATUS_NONE self.status = Spectrum2.protocol_pb2.STATUS_NONE
self.statusMessage = '' self.statusMessage = ''
self.groups = {} self.groups = {}
@ -210,7 +204,7 @@ class Session(YowsupApp):
self.backend.handleConnected(self.user) self.backend.handleConnected(self.user)
self.backend.handleBuddyChanged(self.user, "bot", self.bot.name, self.backend.handleBuddyChanged(self.user, "bot", self.bot.name,
["Admin"], protocol_pb2.STATUS_ONLINE) ["Admin"], Spectrum2.protocol_pb2.STATUS_ONLINE)
# Initialisation? # Initialisation?
self.requestPrivacyList() self.requestPrivacyList()
self.requestClientConfig() self.requestClientConfig()
@ -418,7 +412,7 @@ class Session(YowsupApp):
self.logger.info("Paused typing: %s" % buddy) self.logger.info("Paused typing: %s" % buddy)
if buddy != 'bot': if buddy != 'bot':
self.backend.handleBuddyTyped(self.user, buddy) self.backend.handleBuddyTyped(self.user, buddy)
self.timer = Timer(3, self.backend.handleBuddyStoppedTyping, self.timer = threading.Timer(3, self.backend.handleBuddyStoppedTyping,
(self.user, buddy)).start() (self.user, buddy)).start()
# Called by superclass # Called by superclass
@ -744,8 +738,8 @@ class Session(YowsupApp):
self.logger.info("Status changed: %s" % status) self.logger.info("Status changed: %s" % status)
self.status = status self.status = status
if status == protocol_pb2.STATUS_ONLINE \ if status == Spectrum2.protocol_pb2.STATUS_ONLINE \
or status == protocol_pb2.STATUS_FFC: or status == Spectrum2.protocol_pb2.STATUS_FFC:
self.sendPresence(True) self.sendPresence(True)
else: else:
self.sendPresence(False) self.sendPresence(False)
@ -829,7 +823,7 @@ 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, Spectrum2.protocol_pb2.PARTICIPANT_FLAG_NONE, Spectrum2.protocol_pb2.STATUS_NONE) # TODO
if receiptRequested: self.call("notification_ack", (gjid, messageId)) if receiptRequested: self.call("notification_ack", (gjid, messageId))

View file

@ -1,8 +1,8 @@
import Queue import queue
import threading import threading
# This queue is for other threads that want to execute code in the main thread # This queue is for other threads that want to execute code in the main thread
eventQueue = Queue.Queue() eventQueue = queue.Queue()
def runInThread(threadFunc, callback): def runInThread(threadFunc, callback):
""" """
@ -15,5 +15,6 @@ def runInThread(threadFunc, callback):
result = threadFunc() result = threadFunc()
# Queue callback to be call in main thread # Queue callback to be call in main thread
eventQueue.put(lambda: callback(result)) eventQueue.put(lambda: callback(result))
thread = threading.Thread(target=helper) thread = threading.Thread(target=helper)
thread.start() thread.start()

View file

@ -4,18 +4,16 @@ import argparse
import traceback import traceback
import logging import logging
import asyncore import asyncore
import sys, os import sys
import Queue
import transWhat.threadutils
sys.path.insert(0, os.getcwd())
from Spectrum2.iochannel import IOChannel from Spectrum2.iochannel import IOChannel
from Spectrum2.config import SpectrumConfig from Spectrum2.config import SpectrumConfig
from transWhat.whatsappbackend import WhatsAppBackend
from yowsup.common import YowConstants from yowsup.common import YowConstants
from yowsup.stacks import YowStack from yowsup.stacks import YowStack
from .whatsappbackend import WhatsAppBackend
from . import threadutils
# Arguments # Arguments
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true') parser.add_argument('--debug', action='store_true')

View file

@ -1,11 +1,8 @@
from Spectrum2.backend import SpectrumBackend
from Spectrum2 import protocol_pb2
from session import Session
from registersession import RegisterSession
import logging import logging
from Spectrum2.backend import SpectrumBackend
from .session import Session
from .registersession import RegisterSession
class WhatsAppBackend(SpectrumBackend): class WhatsAppBackend(SpectrumBackend):
def __init__(self, io, spectrum_jid, specConf): def __init__(self, io, spectrum_jid, specConf):

View file

@ -178,7 +178,7 @@ class YowsupApp(object):
mediaUploader = MediaUploader(jid, ownNumber, filePath, mediaUploader = MediaUploader(jid, ownNumber, filePath,
resultRequestUploadIqProtocolEntity.getUrl(), resultRequestUploadIqProtocolEntity.getUrl(),
resultRequestUploadIqProtocolEntity.getResumeOffset(), resultRequestUploadIqProtocolEntity.getResumeOffset(),
successFn, self.onUploadError, self.onUploadProgress, async=False) successFn, self.onUploadError, self.onUploadProgress, asynchronous=False)
mediaUploader.start() mediaUploader.start()
def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity): def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity):