-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpEditor.py
366 lines (281 loc) · 11.1 KB
/
HttpEditor.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import sublime
import sublime_plugin
import json
import shutil
import zipfile
import io
import os
import sys
import re
from threading import Thread
from .lib.urllib3 import PoolManager, make_headers
from .http_editor.commands import RemoteToLocalFileCommand
#import httplib
st_version = 2
if int(sublime.version()) > 3000:
st_version = 3
# костыли для третьего sublime
if st_version == 3:
from imp import reload
mod_load_prefix = 'HttpEditor.'
class ITransportInterface:
def localToRemoteFile(self, filePath): raise NotImplementedError
class HttpTransport():
# на удаленный сервер
uploadPathComand = 'upload_path'
uploadFileComand = 'upload_file'
# с удаленного сервера
downloadPathComand = 'download_path'
downloadFileComand = 'download_file'
def __init__(self, settings):
if settings.get('httpUrl'):
httpUrl = settings.get('httpUrl')
if settings.get('httpUrl') is None:
httpUrl = settings.get('type')+'://'+settings.get('host')
if settings.get('type'):
httpUrl = httpUrl+':'+settings.get('port')
if settings.get('uri'):
httpUrl = httpUrl+'/'+settings.get('uri')
manager = PoolManager(10)
# инициализируем переменные класса
self.httpUrl = httpUrl
self.manager = manager
headers={}
if settings.get('user') and settings.get('password'):
headers = make_headers(basic_auth=settings.get('user') + ':' + settings.get('password'))
headers.update({"Authorization": headers.get('authorization')})
headers.pop('authorization', None)
pass
self.headers=headers
#Сохраняет файл на удаленный сервер
def localToRemoteFile(self, filePath):
manager = self.manager
shortFileName = SublimePluginUtils.filePathInProject(filePath)
with open(filePath, 'rb') as fp:
file_data = fp.read()
r = manager.request('POST', self.httpUrl+'/'+self.uploadFileComand, fields={
'file': shortFileName,
'fileData': (shortFileName, file_data, 'text/plain'),
}, headers=self.headers)
if r.status == 400:
view = sublime.active_window().active_view()
# sublime.set_timeout_async(lambda: sublime.message_dialog("message_dialog check:sdsds"), 0) кнопка ок
view.show_popup('ERROR SAVE: '+r.data.decode("utf-8"), location=-1, max_width=800, on_hide=True)
return
if r.status == 403:
sublime.error_message(
u'Ошибка аутентификации'
)
return
if r.status != 200:
sublime.error_message(
u'Ошибка сохранения'
)
return
if r.status == 200:
view = sublime.active_window().active_view()
view.show_popup('Успешно сохраннео'+r.data.decode("utf-8"), location=-1, max_width=800, on_hide=True, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY)
return
#Сохраняет папки на удаленный сервер
def localToRemotePath(self, filePath):
manager = self.manager
shortFileName = SublimePluginUtils.filePathInProject(filePath)
with open(filePath, 'rb') as fp:
file_data = fp.read()
r = manager.request('POST', self.httpUrl+'/'+self.uploadPathComand, fields={
'file': shortFileName,
'pathData': (shortFileName, file_data, 'text/plain'),
}, headers=self.headers)
if r.status == 403:
sublime.error_message(
u'Ошибка аутентификации'
)
return
if r.status != 200:
sublime.error_message(
u'Ошибка сохранения'
)
return
#Обновление файла в локальной директории
def remoteToLocalFile(self, filePath):
if filePath is None:
return
manager = self.manager
shortFileName = SublimePluginUtils.filePathInProject(filePath)
r = manager.request('GET', self.httpUrl+'/'+self.downloadFileComand, fields={'file': shortFileName}, headers=self.headers)
if r.status == 403:
sublime.error_message(
u'Ошибка аутентификации'
)
return
if r.status == 404:
sublime.error_message(
u'Файл на сервере не найден'
)
return
if r.status == 404:
sublime.error_message(
u'Файл на сервере не найден'
)
return
if r.status != 200:
sublime.error_message(
u'Ошибка обновления файла'
)
return
overloadedFile = open(filePath, "wb")
overloadedFile.write(r.data)
overloadedFile.close()
#Обновление файла в локальной директории
def remoteToLocalPath(self, filePath):
if filePath is None:
return
manager = self.manager
shortFileName = SublimePluginUtils.filePathInProject(filePath)
r = manager.request('GET', self.httpUrl+'/'+self.downloadPathComand, fields={'path': shortFileName}, headers=self.headers)
if r.status == 403:
sublime.error_message(
u'Ошибка аутентификации'
)
return
if r.status != 200:
sublime.error_message(
u'Ошибка сохранения'
)
return
zf = zipfile.ZipFile(io.BytesIO(r.data), "r")
SublimePluginUtils.clearFolder(filePath)
zf.extractall(filePath)
zf.close()
class SublimePluginUtils():
# чистим папку
def clearFolder(folderPath):
# надо выпилить потом как нить
configName = 'http-editor-config.json'
for the_file in os.listdir(folderPath):
if configName in the_file :
continue
file_path = os.path.join(folderPath, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(e)
# Определяет рутовый каталог по файлу
def rootDirPath(viewFilePath):
curentWindow = sublime.active_window()
folderPath = curentWindow.folders()
for path in folderPath:
if viewFilePath is not None and viewFilePath.startswith( path ):
return path
pass
pass
return folderPath[0]
def filePathInProject(viewFilePath):
curentWindow = sublime.active_window()
folderPath = curentWindow.folders()
for path in folderPath:
if viewFilePath == path :
return "/"
if viewFilePath is not None and viewFilePath.startswith( path ):
return viewFilePath.replace(path, "")
pass
pass
return viewFilePath
def jsonData(settingPath):
if os.path.isfile(settingPath) is False:
return
RE_COMMENTS = re.compile('[^:]\/\/[^\\n]*', re.S)
try:
with open(settingPath) as f:
content = f.read()
pass
except Exception as e:
print('Ошибка обработки файла настройки', e)
return
jsonObj = json.loads(RE_COMMENTS.sub('', content))
return jsonObj
class HttpEditor(sublime_plugin.ViewEventListener):
def __init__(self, view):
configName = 'http-editor-config.json'
if view.file_name() is not None and configName in view.file_name():
return
pass
rootPath = SublimePluginUtils.rootDirPath(view.file_name())
localSettingsPath = rootPath+'/'+configName
jsonSettings = SublimePluginUtils.jsonData(localSettingsPath)
if jsonSettings is None:
return
transport = HttpTransport(jsonSettings)
SessionView.setFromView(view, 'transport', transport)
transport.remoteToLocalFile(view.file_name())
@classmethod
def is_applicable(cls, settings):
return True
class HttpEditorListener(sublime_plugin.EventListener):
def on_post_save(self, view):
transport = SessionView.get('transport')
if transport is None:
return
transport.localToRemoteFile(view.file_name())
class HttpEditorUploadCommand(sublime_plugin.WindowCommand):
def run(self, paths):
configName = 'http-editor-config.json'
view = sublime.active_window().active_view()
if configName in view.file_name():
pass
transport = SessionView.get('transport')
if transport is None:
return
transport.remoteToLocalFile(view.file_name())
class HttpEditorUploadPathCommand(sublime_plugin.WindowCommand):
def run(self, paths):
path = paths[0]
configName = 'http-editor-config.json'
if configName in path:
pass
rootPath = SublimePluginUtils.rootDirPath(path)
transport = SessionRootPath.getFromPath(rootPath, 'transport')
print('transport ',transport)
if transport is None:
localSettingsPath = rootPath+'/'+configName
jsonSettings = SublimePluginUtils.jsonData(localSettingsPath)
if jsonSettings is None:
return
transport = HttpTransport(jsonSettings)
if os.path.isfile(path):
transport.remoteToLocalFile(path)
return
t = Thread(group=None, target=transport.remoteToLocalPath, name="T1", args=(path,), kwargs={})
t.start()
class SessionView():
sharedAttrs = {}
def setFromView(externalView, key, val):
fullKey = str(externalView.buffer_id())+'_'+key
SessionView.sharedAttrs[fullKey] = val
def set(key, val):
curentView = sublime.active_window().active_view()
fullKey = str(curentView.buffer_id())+'_'+key
SessionView.sharedAttrs[fullKey] = val
def get(key):
curentView = sublime.active_window().active_view()
fullKey = str(curentView.buffer_id())+'_'+key
try:
return SessionView.sharedAttrs[fullKey]
pass
except Exception as e:
return
class SessionRootPath():
sharedAttrs = {}
def setFromPath(externalPath, key, val):
fullKey = str(externalPath)+'_'+key
SessionView.sharedAttrs[fullKey] = val
def getFromPath(externalPath, key):
fullKey = str(externalPath)+'_'+key
try:
return SessionRootPath.sharedAttrs[fullKey]
pass
except Exception as e:
return