#!/usr/bin/python2
#
"""webClient for  Python

author: michael branton

usage: webClient.py wireTAPhost port wireTAPchannel url  wraplength sleeptime {debug}

this connects you to / website specified by a url, from
which data may be downloaded. specifying any value at all 
for the debug parameter causes the data to also be dumped 
to the screen. wraplength will wrap the text to that length

This script is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this script; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


uses danny holth/clinton mcchesney OSC.py module to convert data into 
OSC format and the wireTAP API. see http://wireTAP.stetson.edu
"""

from wtMessenger import wtMessenger
import sys
import os
from time import sleep
from wrap import wrap

# check arg count
if len(sys.argv) < 7:
	print 'usage:  webClient.py wireTAPhost port wireTAPchannel url wraplength sleeptime {debug}'
	sys.exit(1)

# parse args
host	= sys.argv[1]
port	= int(sys.argv[2])
channel = sys.argv[3]
url     = sys.argv[4]

# wrap input lines to this length
wraplen = int(sys.argv[5])

# sleep time in seconds
sleeplen= float(sys.argv[6])

if len(sys.argv) > 7:
	DEBUG='true'
else:
	DEBUG=''

# create connection to wireTAP server
mess=wtMessenger()
mess.setServerPort(int(port))
mess.serverConnect(host,channel)

# run wget to connect to website
webdumpcmd = 'wget -O - '+url

print "executing "+webdumpcmd+"\n"

while 1:

	a = os.popen(webdumpcmd)

	# read web page data and send it to the server
	q = a.readline()
	while q!='':
        	try:
			if DEBUG:
                		print 'webdump:', q

			mess.add(q)

                	# ship it off
			mess.send()

			sleep(sleeplen)

			# read web data
			q = a.readline()
                        if wraplen != 0 :
                                q = wrap(q,wraplen)

        	except KeyboardInterrupt:
			mess.serverDisconnect()
                	print ' '
                	print 'your webdump session is now complete'
                	print ' '
                	sys.exit(0)

mess.serverDisconnect()
