Permalink
Browse files

Added File Persistor Demo

  • Loading branch information...
s2team committed Jan 10, 2015
1 parent f63c6e8 commit 2b24d3fa4ea1b7f821924a48b7ef60084519553e
Showing with 161 additions and 2 deletions.
  1. +1 −1 setup.py
  2. +18 −1 yowsup-cli
  3. +1 −0 yowsup/demos/filerclient/__init__.py
  4. +84 −0 yowsup/demos/filerclient/layer.py
  5. +57 −0 yowsup/demos/filerclient/stack.py
@@ -3,7 +3,7 @@
import yowsup
import platform
deps = ['python-dateutil', 'argparse', 'python-axolotl>=0.1.1']
deps = ['python-dateutil', 'argparse', 'python-axolotl>=0.1.1', 'jsonpickle']
if platform.system().lower() == "windows":
deps.append('pyreadline')
19 yowsup-cli 100644 → 100755
@@ -3,7 +3,7 @@ __version__ = "2.0.2"
__author__ = "Tarek Galal"
import sys, argparse, yowsup, logging
from yowsup.demos import cli, echoclient, sendclient
from yowsup.demos import cli, echoclient, sendclient, filerclient
from yowsup.registration import WACodeRequest, WARegRequest
HELP_CONFIG = """
@@ -217,6 +217,10 @@ class DemosArgParser(YowArgParser):
"wait for server receipt and exit",
metavar=("phone", "message"), nargs = 2)
persistorOpts = self.add_argument_group("Filer client demo")
persistorOpts.add_argument('-f', '--filer', action = "store", help = "Start the Yowsup Filer client.",
metavar=("inboxpath", "outboxpath", "sentpath"), nargs = 3)
def process(self):
super(DemosArgParser, self).process()
if self.args["yowsup"]:
@@ -225,6 +229,8 @@ class DemosArgParser(YowArgParser):
self.startEcho()
elif self.args["send"]:
self.startSendClient()
elif self.args["filer"]:
self.startFilerClient()
else:
return False
return True
@@ -273,6 +279,17 @@ class DemosArgParser(YowArgParser):
print("\nYowsdown")
sys.exit(0)
def startFilerClient(self):
credentials = self._getCredentials()
if not credentials:
print("Error: You must specify a configuration method")
sys.exit(1)
try:
stack = fileclient.YowsupFilerStack(credentials, self.args["filer"][0], self.args["filer"][1], self.args["filer"][2], self.args["moxie"])
stack.start()
except KeyboardInterrupt:
print("\nYowsdown")
sys.exit(0)
if __name__ == "__main__":
args = sys.argv
@@ -0,0 +1 @@
from .stack import YowsupFilerStack
@@ -0,0 +1,84 @@
import jsonpickle, json, os, errno, time, datetime
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity
import threading
class FilerLayer(YowInterfaceLayer):
PROP_INBOXPATH = "org.openwhatsapp.yowsup.prop.filerclient.inboxpath"
PROP_OUTBOXPATH = "org.openwhatsapp.yowsup.prop.filerclient.outboxpath"
PROP_SENTPATH = "org.openwhatsapp.yowsup.prop.filerclient.sentpath"
EVENT_START = "org.openwhatsapp.yowsup.event.filer.start"
def __init__(self):
super().__init__()
self.inputThread = threading.Thread(target=self.startOutboxObserverThread)
self.inputThread.daemon = True
@ProtocolEntityCallback("message")
def onMessage(self, messageProtocolEntity):
# TODO: That should be done in the constructor.
inboxPath = self.getProp(self.__class__.PROP_INBOXPATH)
self.mkdir_recursive(inboxPath)
filename = "%s/%s.jsonpickle" % (inboxPath, messageProtocolEntity.getId())
print("Received: %s from %s. Writing to file %s" % (
messageProtocolEntity.getBody(), messageProtocolEntity.getFrom(False), filename))
with open(filename, "w") as output:
output.write(jsonpickle.encode(messageProtocolEntity))
receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom())
self.toLower(receipt)
@ProtocolEntityCallback("receipt")
def onReceipt(self, entity):
ack = OutgoingAckProtocolEntity(entity.getId(), "receipt", "delivery")
self.toLower(ack)
def sendMessage(self, to, text):
outgoingMessageProtocolEntity = TextMessageProtocolEntity(text, to=to)
self.toLower(outgoingMessageProtocolEntity)
def onEvent(self, layerEvent):
if layerEvent.getName() == self.__class__.EVENT_START:
self.inputThread.start()
return True
# TODO: Is there a better way of doing this with python?
def mkdir_recursive(self, path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def startOutboxObserverThread(self):
# TODO: That should be done in the constructor.
outboxPath = self.getProp(self.__class__.PROP_OUTBOXPATH)
self.mkdir_recursive(outboxPath)
sentPath = self.getProp(self.__class__.PROP_SENTPATH)
self.mkdir_recursive(sentPath)
before = []
while 1:
time.sleep(5)
after = dict([(f, None) for f in os.listdir(outboxPath)])
added = [f for f in after if not f in before]
for addedFile in added:
addedFilePath="%s/%s" % (outboxPath, addedFile)
with open(addedFilePath, "r") as fileToRead:
fileContent = fileToRead.read()
print("Going to send: %s with content: %s" % (addedFile, fileContent))
toAndText = json.loads(fileContent)
self.sendMessage(toAndText["to"], toAndText["text"])
os.rename(addedFilePath, "%s/%s-%s" % (sentPath, datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S"), addedFile))
@@ -0,0 +1,57 @@
from yowsup.stacks import YowStack
from .layer import FilerLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowCryptLayer, YowAuthenticationProtocolLayer, AuthError
from yowsup.layers.coder import YowCoderLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers.protocol_media import YowMediaProtocolLayer
from yowsup.layers.stanzaregulator import YowStanzaRegulator
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.logger import YowLoggerLayer
from yowsup.layers.axolotl import YowAxolotlLayer
from yowsup.common import YowConstants
from yowsup import env
class YowsupFilerStack(object):
def __init__(self, credentials, inboxpath, outboxpath, sentpath, encryptionEnabled = False):
if encryptionEnabled:
env.CURRENT_ENV = env.S40YowsupEnv()
layers = (
FilerLayer,
(YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer, YowMediaProtocolLayer),
YowAxolotlLayer,
YowLoggerLayer,
YowCoderLayer,
YowCryptLayer,
YowStanzaRegulator,
YowNetworkLayer
)
else:
layers = (
FilerLayer,
(YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer, YowMediaProtocolLayer),
YowLoggerLayer,
YowCoderLayer,
YowCryptLayer,
YowStanzaRegulator,
YowNetworkLayer
)
self.stack = YowStack(layers)
self.stack.setProp(FilerLayer.PROP_INBOXPATH, inboxpath)
self.stack.setProp(FilerLayer.PROP_OUTBOXPATH, outboxpath)
self.stack.setProp(FilerLayer.PROP_SENTPATH, sentpath)
self.stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, credentials)
self.stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
self.stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
self.stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
def start(self):
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
self.stack.broadcastEvent(YowLayerEvent(FilerLayer.EVENT_START))
try:
self.stack.loop()
except AuthError as e:
print("Authentication Error: %s" % e.message)

0 comments on commit 2b24d3f

Please sign in to comment.