-
Notifications
You must be signed in to change notification settings - Fork 1
/
testaustime.py
221 lines (168 loc) · 6.8 KB
/
testaustime.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
import sublime
import sublime_plugin
import urllib
import json
import time
import os
import threading
import subprocess
PLUGIN_SETTINGS_KEY = "testaustime.sublime-settings"
API_SETTINGS_KEY = "api_key"
ENDPOINT_SETTINGS_KEY = "endpoint_url"
last_heartbeat = 0.0
can_show_missing_key_popup = True
class Testaustime:
def __init__(self):
self.settings = sublime.load_settings(PLUGIN_SETTINGS_KEY)
if not self.get_endpoint_url():
print("no endpoint url defined, setting the value to https://api.testaustime.fi")
self.save_endpoint_url("https://api.testaustime.fi")
if not self.get_api_key():
self.missing_api_key_popup()
def missing_api_key_popup(self):
sublime.active_window()
global can_show_missing_key_popup
if can_show_missing_key_popup:
sublime.message_dialog("You haven't set the API key yet.\nSet it from 'Preferences -> testaustime -> Set API key")
can_show_missing_key_popup = False
def save_api_key(self, api_key):
self.settings.set(API_SETTINGS_KEY, api_key)
sublime.save_settings(PLUGIN_SETTINGS_KEY)
def save_endpoint_url(self, endpoint_url):
self.settings.set(ENDPOINT_SETTINGS_KEY, endpoint_url)
sublime.save_settings(PLUGIN_SETTINGS_KEY)
def get_api_key(self):
key = self.settings.get(API_SETTINGS_KEY, None)
if key:
return str(key)
def get_endpoint_url(self):
endpoint = self.settings.get(ENDPOINT_SETTINGS_KEY, None)
if endpoint:
return str(endpoint)
if Testaustime().get_api_key():
sublime.status_message(" Testaustime is ready. happy coding")
else:
sublime.status_message(" Testaustime API token not set")
def startupMessage():
time.sleep(0.5)
if Testaustime().get_api_key():
sublime.status_message(" Testaustime is ready. happy coding")
else:
print(Testaustime().get_api_key())
sublime.status_message(" Testaustime API token not set")
"""
This is kinda stupid (I think?) but we have to wait for one second before showing the user the greeter.
This has to be done, because the settings storage where we store our API key, is initialized only after all plugins have been loaded.
Because of this the user will get the message "Testaustime API token not set" every time.
I know 0.5 seconds is A LOT in computer time, but if we thread the code it shoudln't be an issue.
"""
waitForSettings = threading.Thread(target=startupMessage)
waitForSettings.start()
class prompt_api_key(sublime_plugin.WindowCommand):
def run(self):
self.window.show_input_panel("API key:", "", self._on_input_done, None, None)
def _on_input_done(self, user_input):
sublime.message_dialog("API key set")
Testaustime().save_api_key(user_input)
class prompt_url_endpoint(sublime_plugin.WindowCommand):
def run(self):
self.window.show_input_panel("Endpoint URL:", "", self._on_input_done, None, None)
def _on_input_done(self, user_input):
if not user_input.startswith("https://") and not user_input.startswith("http://"):
user_input = "https://" + user_input
if user_input.endswith("/"):
user_input = user_input[:-1]
Testaustime().save_endpoint_url(user_input)
sublime.message_dialog("Endpoint set")
class ApiCredHandler(sublime_plugin.TextCommand):
def retrieve_api_key(self, edit):
api_key = prompt_api_key()
Testaustime.save_api_key(api_key)
class get_project_name(sublime_plugin.TextCommand):
def run(self, edit):
get_current_project_name()
def AsyncApiCall(self, timeout, endpoint, has_body):
try:
if assemble_data() and assemble_headers():
if has_body:
request = urllib.request.Request(Testaustime().get_endpoint_url() + endpoint,
data=assemble_data(), headers=assemble_headers())
else:
request = urllib.request.Request(Testaustime().get_endpoint_url() + endpoint,
headers=assemble_headers())
response = urllib.request.urlopen(request)
response_text = response.read().decode('utf-8')
return response_text
except (urllib.error.HTTPError) as e:
err = '%s: HTTP error %s contacting API' % (__name__, str(e.code))
print(err)
sublime.message_dialog(err)
except (urllib.error.URLError) as e:
err = '%s: URL error %s contacting API' % (__name__, str(e.reason))
print(err)
sublime.message_dialog(err)
"""
FUNCTIONS
"""
def get_current_syntax():
view = sublime.active_window().active_view()
syntax = view.settings().get('syntax')
syntax = syntax.split('/')[-1].split('.')[0]
return syntax
def show_project():
view = sublime.active_window().active_view()
if view.window() is None:
return
project_file = view.window().project_file_name()
if project_file is not None:
project_name = os.path.splitext(os.path.basename(project_file))[0]
return project_name
filename = view.file_name()
if filename is None:
return
git_project = git_root(filename)
if len(git_project) > 0:
return str(os.path.basename(git_project))
return str(os.path.basename(os.path.dirname(filename)))
def git_root(file):
proc = subprocess.Popen(["git", "rev-parse", "--show-toplevel"], cwd=os.path.dirname(file), stdout=subprocess.PIPE)
proc.wait()
repo = proc.stdout.read().split(b"\n")[0].decode('utf-8')
return os.path.basename(repo)
def assemble_data():
data = {
'language': get_current_syntax(),
'hostname': os.uname()[1],
'editor_name': 'SublimeText',
'project_name': show_project()
}
data = json.dumps(data).encode('utf-8')
return data
def assemble_headers():
if Testaustime().get_api_key():
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + Testaustime().get_api_key(),
}
return headers
def get_user_data():
thread = threading.Thread(target=AsyncApiCall, args=(AsyncApiCall,5,'/users/@me', False))
thread.start()
def heartbeat():
thread = threading.Thread(target=AsyncApiCall, args=(AsyncApiCall,5,'/activity/update', True))
thread.start()
def flush():
thread = threading.Thread(target=AsyncApiCall, args=(AsyncApiCall,5,'/activity/flush', True))
thread.start()
class IdleHandler(sublime_plugin.EventListener):
def on_modified(view, event):
global last_activity
global last_heartbeat
now = time.time()
last_activity = now
if now - last_heartbeat > 30:
sublime.set_timeout_async(heartbeat(), 0)
last_heartbeat = now
class ExitHandler(sublime_plugin.EventListener):
def on_pre_close(self, view):
flush()