|
| 1 | +import sublime |
| 2 | +import sublime_plugin |
| 3 | +import http.client |
| 4 | +import json |
| 5 | +import os |
| 6 | + |
| 7 | +class MmdvCommand(sublime_plugin.TextCommand): |
| 8 | + def __init__(self, view): |
| 9 | + super().__init__(view) |
| 10 | + self.BASE_URL = 'localhost:3000' |
| 11 | + self.__title = '' |
| 12 | + self.__source = '' |
| 13 | + self.__content = '' |
| 14 | + |
| 15 | + def __api(self, uri, params, method = 'POST'): |
| 16 | + conn = http.client.HTTPConnection(self.BASE_URL) |
| 17 | + headers = { |
| 18 | + 'Content-type': 'application/json' |
| 19 | + } |
| 20 | + |
| 21 | + if 'MEMDEV_ACCESS' in os.environ: |
| 22 | + headers['Authorization'] = os.environ.get('MEMDEV_ACCESS') |
| 23 | + |
| 24 | + json_data = json.dumps(params) |
| 25 | + |
| 26 | + conn.request('POST', uri, json_data, headers) |
| 27 | + response = conn.getresponse() |
| 28 | + return json.loads(response.read().decode()) |
| 29 | + |
| 30 | + def __show_source_panel(self): |
| 31 | + window = self.view.window() |
| 32 | + |
| 33 | + window.show_input_panel("Source", "", self.on_source_input_done, None, None) |
| 34 | + |
| 35 | + def on_token_input_done(self, input_val): |
| 36 | + params = {'id': input_val} |
| 37 | + response_json = self.__api('/api/v2/authorize/ext_auth', params) |
| 38 | + |
| 39 | + if response_json['token']: |
| 40 | + os.environ['MEMDEV_ACCESS'] = str(response_json['token']) |
| 41 | + |
| 42 | + self.__show_source_panel() |
| 43 | + |
| 44 | + def on_source_input_done(self, input_val): |
| 45 | + self.__source = input_val |
| 46 | + syntax = self.view.settings().get("syntax") |
| 47 | + |
| 48 | + if 'Plain text' not in syntax: |
| 49 | + syntax = syntax[syntax.rfind('/') + 1:syntax.index('sublime-syntax') - 1].lower() |
| 50 | + else: |
| 51 | + syntax = 'plain' |
| 52 | + |
| 53 | + params = { |
| 54 | + 'content': self.__content, |
| 55 | + 'title': self.__title, |
| 56 | + 'source': input_val, |
| 57 | + 'syntax': syntax, |
| 58 | + 'topic': syntax |
| 59 | + } |
| 60 | + |
| 61 | + response_json = self.__api('/api/v2/snippets', params) |
| 62 | + |
| 63 | + window = self.view |
| 64 | + window.show_popup('Your snippet has been saved!') |
| 65 | + |
| 66 | + def on_title_input_done(self, input_string): |
| 67 | + self.__title = input_string |
| 68 | + window = self.view.window() |
| 69 | + |
| 70 | + if 'MEMDEV_ACCESS' not in os.environ: |
| 71 | + window.show_input_panel("Enter your auth token", "", self.on_token_input_done, None, None) |
| 72 | + return |
| 73 | + |
| 74 | + self.__show_source_panel() |
| 75 | + |
| 76 | + def run(self, edit): |
| 77 | + window = self.view.window() |
| 78 | + view = self.view |
| 79 | + sel = view.sel() |
| 80 | + |
| 81 | + region1 = sel[0] |
| 82 | + self.__content = view.substr(region1) |
| 83 | + |
| 84 | + window.show_input_panel("I just learned how to...", "", self.on_title_input_done, None, None) |
0 commit comments