utils.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 » utils.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, imp, tempfile, time

from library.ftp import read_conf
import log, i18n

do_debug=None
debug_funct=None

class DoDebug(object):
    """
    """
    def __init__(self):
        """
        """
        self._time = time.time()
        
    def _timeCtrl(self):
        """ Control the time passed
        """
        time_passed = time.time() - self._time
        self._time = time.time()
        
        return time_passed, self._time

    def do_debug(self, *args, **kw):
        """
        """
        self._ctrl_debug()
        
        args = list(args)
        
        if kw.pop("time", None) or self.debug4:
            args += ["TIME PASSED: %s" % str(self._timeCtrl())]
            
        if kw.pop("story", None) or self.debug4: 
            args = create_story_call() + args
        
        args += [ "%s:%s" % (str(k), str(v)) for k, v in kw.iteritems() ]
        
        msg = "\n".join( ("DEBUG: %s" % str(x).rstrip() for x in args) )
        
        if self.debug1:
            print msg
        
        debug_funct(msg)
    
    def set_debug_level(self, d_level):
        """ Set the debug level
        """
        for k, value in d_level.iteritems():
            if not (isinstance(k, (int, long)) or k.isdigit()):
                continue
            setattr(self, "debug%s" % k, value)
        
    def _ctrl_debug(self):
        """
        """
        for i in xrange(5):
            if not hasattr(self, "debug%s" % i):
                setattr(self, "debug%s" % i, 0)
        
    def __call__(self, *args, **kw):
        """
        """
        self.do_debug(*args, **kw)
    
def _set_value_opt_cls(opt_cls, opt, value):
    if not opt_cls.has_option(opt):
        opt_cls.set(opt, value)

# ctrl the opt_cls passed and set the values if need
def ctrl_opt_cls_hylapex(opt_cls):
    
    modifies = False
    
    #db_archive parameters
    if not opt_cls.has_option("db_archive_rcv_usage"):
        opt_cls.set("db_archive_rcv_usage", "0")
        opt_cls.set("db_archive_rcv_type", "")
        opt_cls.set("db_archive_rcv_vals", "")
        opt_cls.set("db_archive_rcv_grid", "")
        modifies = True
        
    #smtp server
    if not opt_cls.has_option("txt_smtp_host"):
        opt_cls.set("txt_smtp_host", "localhost")
        
        lst_empty_str = ("txt_smtp_from", "txt_smtp_user", "txt_smtp_pass", 
            "txt_smtp_regarding")
        for i in lst_empty_str:
            opt_cls.set(i, "")
        
        modifies = True
    
    if not opt_cls.has_option("rd_smtp_local"):
        opt_cls.set("rd_smtp_local", "0")
        modifies = True
        
    if not opt_cls.has_option("color_new"):
        opt_cls.set("color_new", "255,255,130")
        opt_cls.set("color_failed", "225,252,186")
        opt_cls.set("color_alarm", "0,255,255")
        modifies = True

    if sys.platform.startswith("win"):
        txt_exe_report = "%windir%\\Notepad.exe"
    else:
        txt_exe_report = ""
    
    gr_report = "Sender: %sender%;;;To: %company% (%external%), JobId: %jobid%, Tot.Pages:%totpages%, Time: %tts%;;;\\n;;;Status: %msg_ok%%msg_failed%"
    
    for opt, value in  (("path_save_qfile","."),("txt_autoupdate","1"),
                    ("txt_debug","0"),("chk_local_time_zone", 1),
                    ("path_new_file", "."), ("path_save_as","."), 
                    ("txt_report_date_hour", "%d/%m/%y %H:%M"),
                    ("txt_exe_report", txt_exe_report), 
                    ("txt_report_page_separator", "-*-*-*-*-*-*-*-"), 
                    ("gr_report", gr_report), ("txt_report_msg_ok", "OK"), ("txt_report_msg_failed", "Failed !"),
                    ("txt_update", "30"),
                    ("path_save_preview_img", "./"),
                    ):
        _set_value_opt_cls(opt_cls, opt, value)
        #("",""),
    
    
    
    return modifies


def create_story_call():
    numF = 2; lst = list()
    while 1:
        try: frame = sys._getframe(numF)
        except ValueError: break
        lst.append( ( frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name) )
        numF += 1
    return lst


def main_is_frozen():
   return (hasattr(sys, "frozen") or # new py2exe
           hasattr(sys, "importers") # old py2exe
           or imp.is_frozen("__main__")) # tools/freeze

def get_main_dir():
   if main_is_frozen():
       return os.path.dirname(sys.executable)
   return os.path.dirname(os.path.abspath(sys.argv[0]))

class my_paths:
    
    def __setattr__(self, name, value):
        #print "ATTR", name, value
        self.__dict__[name] = value

def empty_tmp_hylapex(path, lst_skip=()):
    """ Iterate over the temp dir and delete
        the files/directory
    """
    
    
    try:
        lst = os.listdir( path )
    except OSError, WindowsError:
        return

    for file_ in lst:
        try:
            if file_ in lst_skip: continue
            file_del = os.path.join(path, file_)
            if os.path.isdir(file_del):
                funct_del = os.rmdir
            elif os.path.isfile(file_del):
                funct_del = os.remove
            else:
                continue
            funct_del(file_del)
        except OSError, WindowsError:
            pass

def del_tmp(paths):
    if not os.path.exists(paths.tmp_dir):
        os.mkdir(paths.tmp_dir)
        return
    #File list to skip
    fl = (paths.log_file, paths.temp_file_tiff, paths.temp_file_ps, paths.log_file_crash)
    f2j = [os.path.basename(x) for x in fl]

    empty_tmp_hylapex(paths.tmp_dir, f2j)

    #Delete the other, not need, files
    tempdir = tempfile.gettempdir()
    for f in os.listdir( tempdir ):
        try:
            if not f.startswith("hyla"): continue
            os.remove( os.path.join(tempdir, f) )
        except:
            pass


def ctrl_path_gs(paths, opt):
    if not os.path.exists( opt.get('txt_gs_home') ) and sys.platform.startswith("win"):
        
        PJ = os.path.join
        def join(*tojoin):
            return PJ(paths.my_path, *tojoin)

        newGsHome = filter(lambda x: x.startswith("gs") and os.path.isdir( join("bin", x) ),
                    os.listdir( join("bin") ) )
        if not newGsHome: return

        #keep the last one
        newGsHome = max(newGsHome)

        realGsHome = filter(lambda x: x.startswith("gs") and os.path.isdir( join("bin", newGsHome, x) ),
                    os.listdir( join("bin", newGsHome) ) )
        if not realGsHome: return

        #keep the last one
        realGsHome = max(realGsHome)
        gs_home_path =  join("bin", newGsHome, realGsHome)
        gs_exe_path =  join("bin", newGsHome, realGsHome, "bin", "gswin32c.exe")
        if os.path.exists(gs_exe_path) and os.path.exists(gs_home_path):
            opt.set('txt_gs_home', gs_home_path )
            opt.set('txt_gs', gs_exe_path )

def contr_path():
    env_user = ''
    if '-r' in sys.argv:
        env_user = 'REDMON_USER'
    paths = my_paths()
    #Only for now my_path is this

    my_path = get_main_dir()
    if env_user:
        p = read_conf.pref('hylapex', my_path, env_user = env_user)
    else:
        p = read_conf.pref('hylapex', my_path)

    paths.my_path = p.get_my_path()
    paths.conf_dir = p.get_my_path_conf()
    #Directorys
    
    paths.imgs_dir = os.path.join(paths.my_path, 'imgs')

    # Config files
    paths.file_conf_gen = os.path.join(paths.conf_dir, 'gen.conf')
    paths.file_conf_filters = os.path.join(paths.conf_dir, 'filters.conf')

    #Language
    opt = read_conf.conf_parser(paths.file_conf_gen, 'hylapex')
    if not opt.exist() and opt.get('cho_language'):
        #cho_language is English [en]
        import wx_util
        paths.language = wx_util.get_language( opt.get('cho_language') )
    else:
        paths.language = 'en'
    
    #load the right language
    i18n.i18n(dir_path=paths.my_path, default=paths.language)
    
    paths.file_conf_order_rcv = os.path.join(paths.conf_dir, 'order_receive.conf')
    paths.file_conf_order_snd = os.path.join(paths.conf_dir, 'order_send.conf')
    paths.file_conf_order_done = os.path.join(paths.conf_dir, 'order_done.conf')
    paths.file_conf_dim_rcv = os.path.join(paths.conf_dir, 'dim_rcv.conf')
    paths.file_conf_dim_snd = os.path.join(paths.conf_dir, 'dim_snd.conf')
    paths.file_conf_dim_done = os.path.join(paths.conf_dir, 'dim_done.conf')
    paths.temp_prefix = "hylapex_"
    
    if not opt.exist():
        ctrl_path_gs( paths, opt )

    paths.tmp_dir = p.get_local_temp()
    
    #Other, Logs and help
    if sys.platform == 'win32':
        
        paths.tiff2pdf = os.path.join(paths.my_path, 'bin', 'tiff2pdf.exe')
        paths.tiffinfo = os.path.join(paths.my_path, 'bin', 'tiffinfo.exe')
        #Temporany ghostscript home. It's need only for win and hylapex 2.0

        paths.gs_home_tmp = os.path.join(paths.my_path, 'bin', 'gs854w32', 'gs8.54')
        
        if opt.has_section("hylapex") and opt.has_option('txt_user'):
           username = opt.get('txt_user')
        else:
           if "USERNAME" in os.environ:
              #Win 2k+
              username = os.environ["USERNAME"]
           else:
              #old win 9x
              username = "no_user_yet"
        
        if env_user: username += "_print"
        paths.log_file = os.path.join(paths.tmp_dir, username + '_log')
        paths.temp_file_tiff = os.path.join(paths.tmp_dir, username + '_file_tmp.tif')
        paths.temp_file_ps = os.path.join(paths.tmp_dir, username + '_file_tmp.ps')
    
    else:
        
        #Create the log and the temp files
        if os.environ.has_key('USER'):
            try:
                suffix = "%s_hylapex" % os.environ['USER']
                
                paths.log_file = os.path.join(paths.tmp_dir, suffix +'.log')
                os.access(paths.log_file, os.W_OK)
                
                fd, path_start = tempfile.mkstemp(dir=paths.tmp_dir)
                os.fdopen(fd).close()
                os.remove(path_start)
                
                paths.temp_file_tiff = "%s_%s.tiff" % (path_start, suffix)
                paths.temp_file_ps = "%s_%s.ps" % (path_start, suffix)
                
            except:
                paths.log_file = tempfile.mkstemp(dir=paths.tmp_dir, suffix='_hylapex.log')[1]
                paths.temp_file_tiff = tempfile.mkstemp(dir=paths.tmp_dir, suffix='.tiff')[1]
                paths.temp_file_ps = tempfile.mkstemp(dir=paths.tmp_dir, suffix='.ps')[1]
        
        paths.tiff2pdf = 'tiff2pdf'
        paths.tiffinfo = 'tiffinfo'
    #Need for pyCrash
    paths.log_file_crash = paths.log_file + '_CRASH.htm'
    paths.log4write = log.log(paths.log_file, tmp_dir=paths.tmp_dir)
    
    global do_debug, debug_funct
    debug_funct=paths.log4write.write
    do_debug=DoDebug()
    
    #Dbs
    paths.file_db_DT_rcv = os.path.join(paths.conf_dir, 'date_time_rcv.db')
    paths.file_fax_control = os.path.join(paths.conf_dir, 'fax_in_new.db')
    paths.file_db_fb = os.path.join(paths.conf_dir, 'fax_fb.db')
    paths.file_db_fb_link = os.path.join(paths.conf_dir, 'fax_fb_link.conf')
    if not opt.exist():
        opt.exit()

    return paths

def read_pref(paths):
    opt_cls = read_conf.conf_parser(paths.file_conf_gen, 'hylapex')
    if opt_cls.exist():
        from library.options import options
        options.frm_opt(None, opt_cls, paths).Show(True)
        return 1
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.