-
Notifications
You must be signed in to change notification settings - Fork 2
/
wakatime.py
335 lines (264 loc) · 9.28 KB
/
wakatime.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
""" ==========================================================
File: wakatime.py
Description: Wing IDE plugin for metrics about your programming.
Maintainer: WakaTime <[email protected]>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
==========================================================="""
__version__ = '1.0.0'
import wingapi
import json
import logging
import os
import platform
import sys
import time
from subprocess import Popen, STDOUT, PIPE
try:
import Queue as queue # py2
except ImportError:
import queue # py3
logger = logging.getLogger('wakatime')
is_py2 = (sys.version_info[0] == 2)
is_py3 = (sys.version_info[0] == 3)
if is_py2:
def u(text):
if text is None:
return None
if isinstance(text, unicode): # noqa: F821
return text
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
try:
return unicode(text) # noqa: F821
except:
try:
return text.decode('utf-8', 'replace')
except:
try:
return unicode(str(text)) # noqa: F821
except:
return unicode('') # noqa: F821
elif is_py3:
def u(text):
if text is None:
return None
if isinstance(text, bytes):
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
pass
try:
return str(text)
except:
return text.decode('utf-8', 'replace')
else:
raise Exception('Unsupported Python version: {0}.{1}.{2}'.format(
sys.version_info[0],
sys.version_info[1],
sys.version_info[2],
))
# globals
HEARTBEAT_FREQUENCY = 2
EDITOR_VERSION = wingapi.gApplication.GetProductInfo()[0]
LAST_HEARTBEAT = {
'time': 0,
'file': None,
}
HEARTBEATS = queue.Queue()
def _set_timeout(callback, seconds):
"""Runs the callback after the given seconds delay.
If this is Sublime Text 3, runs the callback on an alternate thread. If this
is Sublime Text 2, runs the callback in the main thread.
"""
wingapi.gApplication.InstallTimeout(seconds * 1000, callback)
def _resources_folder():
return os.path.join(os.path.expanduser('~'), '.wakatime')
def _architecture():
arch = platform.machine() or platform.processor()
if arch == 'armv7l':
return 'arm'
if arch == 'aarch64':
return 'arm64'
if 'arm' in arch:
return 'arm64' if sys.maxsize > 2**32 else 'arm'
return 'amd64' if sys.maxsize > 2**32 else '386'
def _cliLocation():
osname = platform.system().lower()
binary = 'wakatime-cli-{osname}-{arch}{ext}'.format(
osname=osname,
arch=_architecture(),
ext='.exe' if osname == 'windows' else '',
)
return os.path.join(_resources_folder(), binary)
def _config_file():
home = os.environ.get('WAKATIME_HOME')
if home:
return os.path.join(os.path.expanduser(home), '.wakatime.cfg')
return os.path.join(os.path.expanduser('~'), '.wakatime.cfg')
def _obfuscate_apikey(command_list):
cmd = list(command_list)
apikey_index = None
for num in range(len(cmd)):
if cmd[num] == '--key':
apikey_index = num + 1
break
if apikey_index is not None and apikey_index < len(cmd):
cmd[apikey_index] = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' + cmd[apikey_index][-4:]
return cmd
def _should_track(filename, timestamp, is_write):
last_file = LAST_HEARTBEAT['file']
if filename != last_file or _enough_time_passed(timestamp, is_write):
return True
return False
def _enough_time_passed(timestamp, is_write):
if timestamp - LAST_HEARTBEAT['time'] > HEARTBEAT_FREQUENCY * 60:
return True
if is_write and timestamp - LAST_HEARTBEAT['time'] > 2:
return True
return False
def _append_heartbeat(filename, timestamp, is_write, project):
global LAST_HEARTBEAT
project_name = None
if project:
project_name = os.path.basename(project.GetFilename()).rstrip('.wpr')
# add this heartbeat to queue
heartbeat = {
'entity': filename,
'timestamp': timestamp,
'is_write': is_write,
'cursorpos': None,
'project': project_name,
}
HEARTBEATS.put_nowait(heartbeat)
# make this heartbeat the LAST_HEARTBEAT
LAST_HEARTBEAT = {
'file': filename,
'time': timestamp,
}
# process the queue of heartbeats in the future
seconds = 4
_set_timeout(_process_queue, seconds)
def _process_queue():
global LAST_HEARTBEAT
try:
heartbeat = HEARTBEATS.get_nowait()
except queue.Empty:
return
has_extra_heartbeats = False
extra_heartbeats = []
try:
while True:
extra_heartbeats.append(HEARTBEATS.get_nowait())
has_extra_heartbeats = True
except queue.Empty:
pass
thread = SendHeartbeatsThread(heartbeat)
if has_extra_heartbeats:
thread.add_extra_heartbeats(extra_heartbeats)
thread.start()
return None # prevent this timeout from repeating
class SendHeartbeatsThread(object):
def __init__(self, heartbeat):
self.heartbeat = heartbeat
self.has_extra_heartbeats = False
def add_extra_heartbeats(self, extra_heartbeats):
self.has_extra_heartbeats = True
self.extra_heartbeats = extra_heartbeats
def start(self):
self.send_heartbeats()
def build_heartbeat(self, entity=None, timestamp=None, is_write=None,
cursorpos=None, project=None):
"""Returns a dict for passing to wakatime-cli as arguments."""
heartbeat = {
'entity': entity,
'timestamp': timestamp,
'is_write': is_write,
}
if project:
heartbeat['alternate_project'] = project
if cursorpos is not None:
heartbeat['cursorpos'] = '{0}'.format(cursorpos)
return heartbeat
def send_heartbeats(self):
heartbeat = self.build_heartbeat(**self.heartbeat)
ua = 'wing/{editor_version} wing-wakatime/{plugin_version}'.format(
editor_version=EDITOR_VERSION,
plugin_version=__version__,
)
cmd = [
_cliLocation(),
'--entity', heartbeat['entity'],
'--time', str('%f' % heartbeat['timestamp']),
'--plugin', ua,
]
if heartbeat['is_write']:
cmd.append('--write')
if heartbeat.get('alternate_project'):
cmd.extend(['--alternate-project', heartbeat['alternate_project']])
if heartbeat.get('cursorpos') is not None:
cmd.extend(['--cursorpos', heartbeat['cursorpos']])
if self.has_extra_heartbeats:
cmd.append('--extra-heartbeats')
stdin = PIPE
extra_heartbeats = [self.build_heartbeat(**x) for x in self.extra_heartbeats]
extra_heartbeats = json.dumps(extra_heartbeats)
else:
extra_heartbeats = None
stdin = None
logger.info(' '.join(_obfuscate_apikey(cmd)))
try:
process = Popen(cmd, stdin=stdin, stdout=PIPE, stderr=STDOUT)
inp = None
if self.has_extra_heartbeats:
inp = "{0}\n".format(extra_heartbeats)
inp = inp.encode('utf-8')
output, err = process.communicate(input=inp)
output = u(output)
retcode = process.poll()
logger.info(retcode)
if retcode:
msg = 'wakatime-cli exited with status: {0}'.format(retcode)
if retcode == 102 or retcode == 112:
logger.warn(msg)
else:
logger.error(msg)
if output:
logger.error(u('wakatime-cli output: {0}').format(output))
except:
logger.error(u(sys.exc_info()[1]))
def _handle_activity(is_write):
document = wingapi.gApplication.GetActiveEditor().GetDocument()
if document:
filename = document.GetFilename()
timestamp = time.time()
if _should_track(filename, timestamp, is_write):
project = wingapi.gApplication.GetProject()
_append_heartbeat(filename, timestamp, is_write, project)
def _on_selection_changed(start, end):
_handle_activity(False)
return None
def _on_saved(cacheFile):
_handle_activity(True)
return None
def _setup_signals():
try:
wingapi.gApplication.GetActiveEditor().connect('selection-changed', _on_selection_changed)
wingapi.gApplication.GetActiveEditor().fSingletons.fGuiMgr.GetActiveDocument().fCache.connect('write-completed', _on_saved)
except AttributeError:
_set_timeout(_setup_signals, 1)
return None
def _init(plugin_id):
logger.info('Initializing WakaTime plugin v{ver}'.format(ver=__version__))
wingapi.gApplication.EnablePlugin(plugin_id, True)
_setup_signals()
logger.info('Finished initializing WakaTime plugin.')
return True
_plugin = ['WakaTime', _init]