#!/usr/bin/python
# -*- coding: utf-8 -*-
__doc__ = """
Hylapex command line program.
Useful program for send file(s) to an hylafax server.
As far as I can, I emulate the sendfax client.
Usage: hylapex_cp.[py|exe] -h
Thanks to: Steven Bethard and his argparse module
Simple example:
- Create two pdf files
- Send them to two destinations:
michele:~$ man -t cp | ps2pdf - /tmp/cp.pdf
michele:~$ man -t mv | ps2pdf - /tmp/mv.pdf
michele:~$ python hylapex_cl.py -d 0432931511 -d 0432931378 -f /tmp/cp.pdf -f /tmp/mv.pdf -H localhost
"""
import sys, os, optparse
from library import argparse
from twisted.internet import reactor,defer
from library.ftp.hylaproto_t import HylafaxProto,SendFax
NOTIFY_STRINGS = ("done+requeue", "requeue", "done", "none")
class HylapexCL(object):
""" Hylapex command line class
"""
def __init__(self):
"""
"""
self._call_send = 0
#Before all, control the args
self._ctrl_args()
#And after, if all are ok, start twisted
d = defer.Deferred()
d.addCallback(self._log_in_hylafax)
d.addErrback(self._error)
d.callback(None)
def _log_in_hylafax(self, *args):
self._h = HylafaxProto(self._args.host, self._args.user,
self._args.passwd,
callBackOnStatus=self._after_log_in,
callBackOnError=self._error,
passive=1,
dateTimeRcvUse=False)
#Set the debug value
if not self._args.quiet:
self._h.debug = self._args.verbose
reactor.run()
def _after_log_in(self):
""" We end the login, so send the send fax command
"""
fax = SendFax()
fax.sendtime = self._args.atime
fax.dialstring = self._args.dialstring
fax.notifyaddr = self._args.email
fax.file_list = self._args.filein
fax.notify = self._args.notify
fax.fromuser = self._args.user
fax.maxdials = str(self._args.maxdials)
fax.priority = self._args.priority
fax.convert = self._args.convert
fax.gspath = self._args.gspath
fax.tocompany = self._args.tocompany
d = {"callback": self._fax_done, }
self._h.SendFax(fax, **d)
#Done send the fax. Not need more updated
self._h.callBackOnStatus = None
def _fax_done(self, *args):
""" Called at the end of the process
"""
self._h.Close()
#Other method to print a msg?
import pprint
reactor.callLater(0.2, pprint.pprint, "End send")
reactor.callLater(0.5, reactor.stop)
def _ctrl_args(self):
""" Control the argouments
"""
def create_user():
if sys.platform.startswith('win'):
if sys.getwindowsversion()[3] < 2:
usr = ""
else:
usr = os.environ["USERNAME"]
else:
usr = os.environ["USER"]
return usr
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--atime", default="now",
help="Send the fax at the indicated time. See sendfax for more info")
parser.add_argument("-c", "--tocompany", default="", dest="tocompany",
help="Company destionation string")
parser.add_argument("-d", "--dialstring", required=True, action='append',
help="Dialstring. You can add more that one by adding more -d switch" )
parser.add_argument("-e", "--email", help="Address where send the email", )
parser.add_argument("-f", "--filein", required=True, action='append',
help="Input filename path(s). You can add more that one by adding more -f switch")
parser.add_argument("-g", "--gspath",
help="Ghostscript .exe path. Please use the 'c' exe file (gswin32c.exe). Need on win if you don't use the -N")
parser.add_argument("-H", "--host", required=True, help="Host where the server are")
parser.add_argument("-n", "--notify", default="none", choices=NOTIFY_STRINGS,
help="When notify. Can be one of: %s. Default done+requeue" % ",".join(NOTIFY_STRINGS),)
parser.add_argument("-N", "--noconvert", nargs="?", dest="convert", default=True,
help="Not convert the file before send into a single tiff image. Allowed only one file!")
parser.add_argument("-m", "--maxdials", default=10, type=int, help="Max dials")
parser.add_argument("-p", "--pass", help="Pass for connect to the server", dest="passwd")
parser.add_argument("-P", "--priority", help="scheduling priority", default=127, type=int)
parser.add_argument("-q", "--quiet", help="Be quiet (like -v 0)", default=False)
parser.add_argument("-u", "--user",
help="User for connect to the server. If not set, I'll use the user that invoke me.")
parser.add_argument("-v", "--verbose", default=0,
help="Be verbose")
#Force the user value to sys.argv, so it'll go throw the user control
if not ('-u' in sys.argv or '--user' in sys.argv):
sys.argv += ['-u', create_user()]
args = parser.parse_args()
#Control the convert and the file list
if not args.convert and len(args.filein) > 1:
msg = "I cannot send more than one file while not converted them. See -h for more"
print msg
raise ValueError(msg)
#Convert and gs path, only on win
if sys.platform.startswith("win"):
if args.convert and not args.gspath:
msg = "You are on Win Platform. Specify the gs path via -g or use the not convert parameter via -N. See -h for more"
print msg
raise EnvironmentError(msg)
self._args = args
def _error(self, *args, **kw):
"""
"""
msg = ""
for m in args: msg += repr(m)
for m in kw.values(): msg += repr(m)
print "There is an error:\n", m
try:
reactor.stop()
except RuntimeError:
pass
if __name__ == "__main__":
HylapexCL()
|