forked from roxana-lafuente/ResearchLogger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
myutils.py
234 lines (188 loc) · 7.11 KB
/
myutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# !/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#
# 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/>.
#
# 2015 modifications by Roxana Lafuente <[email protected]>
##############################################################################
import zlib
import base64
import sys
import os
import os.path
import imp
import locale
from validate import ValidateError, VdtValueError
import re
# for the OnDemandRotatingFileHandler class
from logging.handlers import BaseRotatingHandler
import time
try:
import codecs
except ImportError:
codecs = None
# used to store the settings dict and make it globally accessible.
_settings = {}
# used to store the cmdoptions dict and make it globally accessible.
_cmdoptions = {}
# used to store a reference to the main thread and make it globally
# accessible
_mainapp = {}
def password_obfuscate(password):
return base64.b64encode(zlib.compress(password))
def password_recover(password):
return zlib.decompress(base64.b64decode(password))
# the following two functions are from the py2exe wiki:
# http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") or # old py2exe
imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
return os.path.dirname(sys.executable)
# return os.path.dirname(sys.argv[0])
return sys.path[0]
def to_unicode(x):
"""
Try to convert the input to utf-8.
"""
# return empty string if input is None
if x is None:
return ''
# if this is not a string, let's try converting it
if not isinstance(x, basestring):
x = str(x)
# if this is a unicode string, encode it and return
if isinstance(x, unicode):
return x.encode('utf-8')
# now try a bunch of likely encodings
encoding = locale.getpreferredencoding()
try:
ret = x.decode(encoding).encode('utf-8')
except UnicodeError:
try:
ret = x.decode('utf-8').encode('utf-8')
except UnicodeError:
try:
ret = x.decode('latin-1').encode('utf-8')
except UnicodeError:
ret = x.decode('utf-8', 'replace').encode('utf-8')
return ret
class VdtValueDetailError(ValidateError):
def __init__(self, value, reason):
ValidateError.__init__(self, "the value '%s' is unacceptable.\n"
"Reason: %s" % (value, reason))
def validate_log_filename(value):
'''
Check for logfile naming restrictions.
These restrictions are in place to avoid conflicts with internal
file operations.
Log filenames cannot:
* End in '.zip'
* Start with '_internal_'
This function gets plugged into an instance of validate.Validator.
'''
if not value.startswith('_internal_') and \
not value.endswith('.zip'):
return value
else:
raise VdtValueDetailError(value,
"filename cannot end in '.zip' or start "
"with '_internal_'")
def validate_image_filename(value):
'''
Check for logfile naming restrictions.
These restrictions are in place to avoid conflicts with internal
file operations and ensure unique click image filenames.
Image filenames:
* Cannot start with '_internal_'
* Must contain %time% variable somewhere.
This function gets plugged into an instance of validate.Validator.
'''
if not value.startswith('_internal_') and \
re.search(r'%time%', value):
return value
else:
raise VdtValueDetailError(value, "filename cannot start with"
" '_internal_' and must contain "
"'%time%' to ensure uniqueness")
class OnDemandRotatingFileHandler(BaseRotatingHandler):
'''
Handler which allows the rotating of the logfile on demand.
Old logs are renamed with a datetime prefix.
'''
def __init__(self, filename, mode='a', timestring_format="%Y%m%d_%H%M%S",
prefix=True, encoding=None):
'''
Open the specified file and use it as the stream for logging.
File grows indefinitely, until rollover is called.
A rollover will close the stream; rename the file to a new name,
with a prefix or suffix (prefix if prameter prefix=True)
to the filename of the current date and time, in the format specified
by timestring_format; and open a fresh log file.
For example, with a base file name of "app.log", and other arguments
as default, a rolled-over logfile might have a name of
"20090610_234620.app.log".
The file being written to is always "app.log".
timestring_format is a format string, as described for time.strftime().
'''
BaseRotatingHandler.__init__(self, filename, mode, encoding)
self.timestring_format = timestring_format
self.prefix = prefix
def doRollover(self):
'''Do a rollover, as described in __init__().'''
dirname, filename = os.path.split(self.baseFilename)
if self.prefix:
new_filename = time.strftime(self.timestring_format) + '.' + filename
else:
new_filename = filename + '.'
+ time.strftime(self.timestring_format)
newpath = os.path.join(dirname, new_filename)
self.acquire()
try:
self.stream.close()
os.rename(self.baseFilename, newpath)
if self.encoding:
self.stream = codecs.open(self.baseFilename, 'w',
self.encoding)
else:
self.stream = open(self.baseFilename, 'w')
finally:
self.release()
def shouldRollover(self, record):
'''
Always return 0, since all rollovers are on demand.
This method is here just for compatibility with the
BaseRotatingHandler class definition.
'''
return 0
def get_username():
'''
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