-
Notifications
You must be signed in to change notification settings - Fork 2
/
cacher_setup.py
98 lines (79 loc) · 2.8 KB
/
cacher_setup.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
import sublime
import sublime_plugin
import json
import urllib
import time
from .lib import util, snippets
global last_run
last_run = -1
class SetupApiTokenHandler(sublime_plugin.TextInputHandler):
@staticmethod
def placeholder():
return "API Token"
@staticmethod
def validate(expr):
return util.validate_input(expr)
@staticmethod
def confirm(text):
return text
class SetupApiKeyHandler(sublime_plugin.TextInputHandler):
@staticmethod
def placeholder():
return "API Key"
@staticmethod
def validate(expr):
return util.validate_input(expr)
@staticmethod
def confirm(text):
return text
@staticmethod
def next_input(args):
return SetupApiTokenHandler()
class CacherSetupCommand(sublime_plugin.ApplicationCommand):
def run(self, setup_api_key_handler, setup_api_token_handler):
headers = {
'X-Api-Key': setup_api_key_handler,
'X-Api-Token': setup_api_token_handler
}
url = "{0}/sublime/validate".format(util.settings().get("apiHost"))
try:
req = urllib.request.Request(url, data=None, headers=headers, method="POST")
urllib.request.urlopen(req)
util.store().set("logged_in", True)
util.save_credentials(setup_api_key_handler, setup_api_token_handler)
snippets.load_snippets()
sublime.status_message("Cacher: Logged in")
except urllib.error.HTTPError as e:
self.handle_error(e)
@staticmethod
def input(args):
# De-dupe multiple calls
global last_run
if int(time.time()) - last_run < 5:
return SetupApiKeyHandler()
last_run = int(time.time())
if sublime.ok_cancel_dialog("Open Cacher to view credentials", "Open Cacher"):
util.open_url(
host=util.settings().get("appHost"),
path="/enter",
action="view_api_creds"
)
return SetupApiKeyHandler()
@staticmethod
def handle_error(e):
try:
resp = json.loads(e.read().decode("utf8"))
except ValueError:
util.show_server_error()
if e.code == 403:
if resp["error_code"] == "NoPermission":
sublime.error_message("Cacher API key or token not valid. Please try again.")
else:
if sublime.ok_cancel_dialog("Upgrade to the Pro or Team plan to use Sublime with Cacher.", "View Plans"):
util.open_url(
host=util.settings().get("appHost"),
path="/enter",
action="view_plans"
)
else:
sublime.error_message("There was an error communicating with Cacher. Please try again.")