hylaprint.py :  » Business-Application » hylaPEx » hylapex » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Business Application » hylaPEx 
hylaPEx » hylapex » hylaprint.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# hylaPEx, an hylafax client written in python
#
# www.unipex.it/hylapex/
#
# License:
#         GNU General Public License (GPL)
#         For more info see LICENSE.txt and LICENSE-GPL.txt
#
# Copyright (C) 2004-2006  Unipex s.r.l.,  All Rights Reserved.
# Via Vittorio Veneto 83/A
# 33050 Gonars (UD) - Italy
# phone 0039 0432 931511 - fax 0039 0432 931378
# www.unipex.it - michele.petrazzo@unipex.it

import sys, os, getopt, tempfile, time, traceback

from twisted.internet import reactor,protocol

from library.ftp import read_conf

HYLAPRINT_PREFIX = "hylaprint_tmp"

if 'REDMON_USER' in os.environ:
    conf = read_conf.pref('hylapex', env_user = 'REDMON_USER')
else:
    conf = read_conf.pref('hylapex')
my_path = conf.get_my_path()
tmp_dir = conf.get_local_temp()


if sys.platform.startswith("win"):
    exc = WindowsError, OSError
else:
    exc = OSError

try:
    lst_f_del = []
    now = time.time()
    for _ in os.listdir(tmp_dir):
        date_ = os.stat(_)[-1]
        if (date_ > (now - 60*60*24) ) or _ in lst_f_del:
            continue
        
        if _.startswith("hylapex"):
            lst_f_del.append(_)
        
        #control if there is only one file that start with 
        #HYLAPRINT_PREFIX, see the its stat
        if _.startswith(HYLAPRINT_PREFIX) and not _ in lst_f_del:
            lst_f_del.append(_)

except exc:
    lst_f_del = []

for file_ in lst_f_del:
    try:
        path_compl = os.path.join(tmp_dir, file_)
        os.remove(path_compl)
    except (WindowsError, OSError):
        pass

if not os.path.exists(tmp_dir):
  os.mkdir(tmp_dir)

class my_var:
  pass

class ConnFrameExist(protocol.Protocol):
  #The server is listening
  def connectionMade(self):
    self.transport.write( str(my_var.file_name_path) )
    out()

class snd(protocol.ClientFactory):
  protocol = ConnFrameExist
  def clientConnectionFailed(self, connector, reason):
    #The server isn't listening
    hyPathExe = 'hylapex.exe'
    hyPathSrc ='hylapex.py'
    try:
      if sys.platform == 'win32':
        args = ['-r ', '"%s"' % my_var.file_name_path]
        os.spawnv(os.P_NOWAIT, os.path.join(my_path, hyPathExe), args)
      else:
        args = [hyPathSrc, '-r', my_var.file_name_path]
        os.spawnv(os.P_NOWAIT, os.path.join(my_path, hyPathSrc), args)
      out()
    except Exception, Ex:
      Ex = traceback.format_exc()
      fd, path = tempfile.mkstemp(prefix="hylaprint_log_error_", dir=tmp_dir, suffix='.log')
      f = os.fdopen(fd, "a")
      msg = [Ex, my_path, hyPathExe, hyPathSrc]
      f.write( '\n'.join(msg) )
      f.close()
      print '\n\tAn error occour then try to open hylapex'
      print 'All will be saved in:', path, "\n"
      print Ex
      print os.path.join(my_path, 'hylapex.py/exe'), args
      out(1)

def ctrl_header(file2read, file2write=None):
  #Control the header for the already opened file object
  header = file2read.read(4)
  if header in (r'%PDF', r'%!PS'):
    #We don't care about the pdf or ps
    out_type = "ps"
    suffix = "ps"
  elif header[:2] in ("II", "MM") and "*" in header[2:4]:
    #We have a tiff file
    out_type = "tiff"
    suffix = "tiff"
  else:
    #Why I'm here? What type of file did we have?
    out_type = "ps"
    suffix = "ps"

  if file2write is None:
    fd, path = tempfile.mkstemp(dir=tmp_dir, prefix="hylaprint_tmp_",
      suffix=".%s" % suffix)
    tmpfile = os.fdopen(fd, 'wb')
  else:
    tmpfile = open(file2write, 'wb')
    path = file2write
    
  tmpfile.write(header)
  tmpfile.write(file2read.read())
  tmpfile.close()
  
  return path


def go():
  try:
    if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
      path = ctrl_header(open(sys.argv[1], "rb"))
    else:
      if "-t" in sys.argv:
        #we are on terminal server, talk with the pipes
        if sys.platform.startswith("win"):
            username = os.environ.get('REDMON_USER', "").strip()
        else:
            username = os.environ.get("USER", None)
        
        if not username:
            raise ValueError("No user!")
        
        from library.named_pipes import named_pipe
        pipe = named_pipe.NamedPipe("hylapex_%s" % username)
        if pipe.create_client_pipe():
            raise ValueError("No listeners!")
        
        if sys.platform.startswith("win"):
            path = pipe.read_pipe()[1].strip()
            ctrl_header(sys.stdin, path)
        else:
            path = ctrl_header(sys.stdin)
        
        pipe.write_pipe(path)
        pipe.close_pipe()
        
        #sys.exit()
        
      else:
        # -- work as usual
        
        #Load the header for see if the file passed are tif or ps|pdf
        path = ctrl_header(sys.stdin)
        my_var.file_name_path = path
        
        #Go to talk with server
        factory = snd()
        reactor.connectTCP('localhost', 8003, factory)
        reactor.run()
        
  except Exception, ex:
    print traceback.format_exc()
    out()

def out(err = 0):
  if err:print 'Please use %s only with redmon' % (sys.argv[0])
  reactor.callLater(2, reactor.stop)

def main():
  go()
  

if __name__ == '__main__':
  main()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.