-
Notifications
You must be signed in to change notification settings - Fork 2
/
timedscreenshot.py
189 lines (161 loc) · 6.96 KB
/
timedscreenshot.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
##############################################################################
#
# 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]>
##############################################################################
from myutils import to_unicode
from Queue import Empty
from threading import Event
import os
import os.path
import logging
import time
import re
import sys
import datetime
if os.name == 'nt':
import win32api
import ImageGrab
elif os.name == 'posix':
import gtk
pass
else:
print "OS is not recognised as windows or linux"
sys.exit()
from baseeventclasses import (FirstStageBaseEventClass,
SecondStageBaseEventClass)
from onclickimagecapture import CropBox, Point
from constants import IMG_SET, TIMEDATE
class TimedScreenshotFirstStage(FirstStageBaseEventClass):
'''
Takes screenshots at fixed interval.
Only if any user keyboard or mouse activity is detected in between.
Does not count mouse motion, only clicks.
Sets the secondstage event to notify of activity.
'''
def __init__(self, username, *args, **kwargs):
FirstStageBaseEventClass.__init__(self, username, *args, **kwargs)
self.task_function = self.process_event
def process_event(self):
try:
# Need the timeout so that thread terminates properly when exiting.
event = self.q.get(timeout=0.05)
self.sst_q.set()
self.logger.debug("User activity detected")
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 spawn_second_stage_thread(self):
self.sst_q = Event()
self.sst = TimedScreenshotSecondStage(self.username, self.dir_lock,
self.sst_q, self.loggername)
class TimedScreenshotSecondStage(SecondStageBaseEventClass):
def __init__(self, username, dir_lock, *args, **kwargs):
SecondStageBaseEventClass.__init__(self, username, dir_lock, *args, **kwargs)
self.task_function = self.process_event
self.logger = logging.getLogger(self.loggername)
self.sleep_counter = 0
def process_event(self):
try:
# Break up the sleep into short bursts, to allow for quick
# and clean exit.
time.sleep(0.05)
self.sleep_counter += 0.05
if self.sleep_counter > \
self.subsettings['General']['Screenshot Interval']:
if self.q.isSet():
self.logger.debug("capturing timed screenshot...")
try:
savefilename = os.path.join(
self.settings['General']['Log Directory'],
self.subsettings['General']['Log Subdirectory'],
self.parse_filename())
self.capture_image(savefilename)
self.write_to_logfile(savefilename)
finally:
self.q.clear()
self.sleep_counter = 0
except:
self.logger.debug("some exception was caught in the "
"screenshot loop...\nhere it is:\n",
exc_info=True)
pass # let's keep iterating
def write_to_logfile(self, savefilename):
# TODO: Do not hardcode pipe
self.logger.info(str(time.time()) + "|" + savefilename)
def capture_image(self, savefilename):
screensize = self.get_screen_size()
# The cropbox will take care of making sure our image is within
# screen boundaries.
cropbox = CropBox(topleft=Point(0, 0),
bottomright=screensize,
min=Point(0, 0),
max=screensize)
self.logger.debug(cropbox)
if os.name == 'posix':
screengrab = gtk.gdk.Pixbuf(
gtk.gdk.COLORSPACE_RGB,
False,
8,
screensize.x,
screensize.y)
screengrab.get_from_drawable(
gtk.gdk.get_default_root_window(),
gtk.gdk.colormap_get_system(),
0, 0, 0, 0,
screensize.x,
screensize.y)
save_options_dict = {}
img_format = self.subsettings['General']['Screenshot Image Format']
img_format.lower()
img_quality = to_unicode(
self.subsettings['General']['Screenshot Image Quality'])
if img_format in IMG_SET:
self.subsettings['General']['Screenshot Image Format'] = 'jpeg'
save_options_dict = {'quality': img_quality}
screengrab.save(savefilename,
self.subsettings['General']['Screenshot Image Format'],
save_options_dict)
if os.name == 'nt':
image_data = ImageGrab.grab((cropbox.topleft.x, cropbox.topleft.y,
cropbox.bottomright.x,
cropbox.bottomright.y))
image_data.save(savefilename,
quality=self.subsettings['General']['Screenshot Image Quality'])
def get_screen_size(self):
if os.name == 'posix':
return Point(gtk.gdk.screen_width(),
gtk.gdk.screen_height())
if os.name == 'nt':
return Point(win32api.GetSystemMetrics(0),
win32api.GetSystemMetrics(1))
def parse_filename(self):
filepattern = self.subsettings['General']['Screenshot Image Filename']
fileextension = self.subsettings['General']['Screenshot Image Format']
filepattern = re.sub(r'%time%',
datetime.datetime.today().strftime(TIMEDATE) +
str(datetime.datetime.today().microsecond),
filepattern)
filepattern = filepattern + '.' + fileextension
return filepattern