forked from Floobits/floobits-sublime
/
floobits.py
649 lines (517 loc) · 20.8 KB
/
floobits.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# coding: utf-8
import sys
import os
import imp
import json
import subprocess
import threading
import traceback
import webbrowser
import sublime_plugin
import sublime
try:
import ssl
assert ssl
except ImportError:
ssl = False
if ssl is False and sublime.platform() == 'linux':
plugin_path = os.path.split(os.path.dirname(__file__))[0]
if plugin_path in ('.', ''):
plugin_path = os.getcwd()
_ssl = None
ssl_versions = ['0.9.8', '1.0.0', '10']
ssl_path = os.path.join(plugin_path, 'lib', 'linux')
lib_path = os.path.join(plugin_path, 'lib', 'linux-%s' % sublime.arch())
for version in ssl_versions:
so_path = os.path.join(lib_path, 'libssl-%s' % version)
try:
filename, path, desc = imp.find_module('_ssl', [so_path])
if filename is None:
print('Module not found at %s' % so_path)
continue
_ssl = imp.load_module('_ssl', filename, path, desc)
break
except ImportError as e:
print('Failed loading _ssl module %s: %s' % (so_path, str(e)))
if _ssl:
print('Hooray! %s is a winner!' % so_path)
filename, path, desc = imp.find_module('ssl', [ssl_path])
if filename is None:
print("Couldn't find ssl module at %s" % ssl_path)
else:
try:
ssl = imp.load_module('ssl', filename, path, desc)
except ImportError as e:
print('Failed loading ssl module at: %s' % str(e))
else:
print("Couldn't find an _ssl shared lib that's compatible with your version of linux. Sorry :(")
try:
from urllib.error import HTTPError
from .floo import api, AgentConnection, msg, shared as G, utils
from .floo.listener import Listener
assert HTTPError and api and AgentConnection and G and Listener and msg and utils
except (ImportError, ValueError):
from urllib2 import HTTPError
from floo import api, AgentConnection, msg, utils
from floo.listener import Listener
from floo import shared as G
PY2 = sys.version_info < (3, 0)
settings = sublime.load_settings('Floobits.sublime-settings')
DATA = {}
agent = None
ON_CONNECT = None
def update_recent_rooms(room):
recent_rooms = DATA.get('recent_rooms', [])
recent_rooms.insert(0, room)
recent_rooms = recent_rooms[:25]
seen = set()
new = []
for r in recent_rooms:
stringified = json.dumps(r)
if stringified not in seen:
new.append(r)
seen.add(stringified)
DATA['recent_rooms'] = new
utils.update_persistent_data(DATA)
def load_floorc():
"""try to read settings out of the .floorc file"""
s = {}
try:
fd = open(os.path.expanduser('~/.floorc'), 'rb')
except IOError as e:
if e.errno == 2:
return s
raise
default_settings = fd.read().decode('utf-8').split('\n')
fd.close()
for setting in default_settings:
# TODO: this is horrible
if len(setting) == 0 or setting[0] == '#':
continue
try:
name, value = setting.split(' ', 1)
except IndexError:
continue
s[name.upper()] = value
return s
def reload_settings():
global settings
print('Reloading settings...')
# TODO: settings doesn't seem to load most settings.
# Also, settings.get('key', 'default_value') returns None
settings = sublime.load_settings('Floobits.sublime-settings')
G.ALERT_ON_MSG = settings.get('alert_on_msg')
if G.ALERT_ON_MSG is None:
G.ALERT_ON_MSG = True
G.DEBUG = settings.get('debug')
if G.DEBUG is None:
G.DEBUG = False
G.COLAB_DIR = settings.get('share_dir') or '~/.floobits/share/'
G.COLAB_DIR = os.path.expanduser(G.COLAB_DIR)
G.COLAB_DIR = os.path.realpath(G.COLAB_DIR)
utils.mkdir(G.COLAB_DIR)
G.DEFAULT_HOST = settings.get('host') or 'floobits.com'
G.DEFAULT_PORT = settings.get('port') or 3448
G.SECURE = settings.get('secure')
if G.SECURE is None:
G.SECURE = True
G.USERNAME = settings.get('username')
G.SECRET = settings.get('secret')
floorc_settings = load_floorc()
for name, val in floorc_settings.items():
setattr(G, name, val)
if agent and agent.is_ready():
msg.log('Reconnecting due to settings change')
agent.reconnect()
print('Floobits debug is %s' % G.DEBUG)
settings.add_on_change('', reload_settings)
reload_settings()
DATA = utils.get_persistent_data()
def disconnect_dialog():
global agent
if agent and G.CONNECTED:
disconnect = bool(sublime.ok_cancel_dialog('You can only be in one room at a time. Leave the current room?'))
if disconnect:
msg.debug('Stopping agent.')
agent.stop()
agent = None
return disconnect
return True
class FloobitsBaseCommand(sublime_plugin.WindowCommand):
def is_visible(self):
return bool(self.is_enabled())
def is_enabled(self):
return bool(agent and agent.is_ready())
class FloobitsShareDirCommand(sublime_plugin.WindowCommand):
def run(self, dir_to_share=''):
reload_settings()
self.window.show_input_panel('Directory:', dir_to_share, self.on_input, None, None)
def on_input(self, dir_to_share):
global ON_CONNECT
dir_to_share = os.path.expanduser(dir_to_share)
dir_to_share = utils.unfuck_path(dir_to_share)
room_name = os.path.basename(dir_to_share)
floo_room_dir = os.path.join(G.COLAB_DIR, G.USERNAME, room_name)
print(G.COLAB_DIR, G.USERNAME, room_name, floo_room_dir)
if os.path.isfile(dir_to_share):
return sublime.error_message('Give me a directory please')
try:
utils.mkdir(dir_to_share)
except Exception:
return sublime.error_message("The directory %s doesn't exist and I can't make it." % dir_to_share)
floo_file = os.path.join(dir_to_share, '.floo')
info = {}
try:
floo_info = open(floo_file, 'rb').read().decode('utf-8')
info = json.loads(floo_info)
except (IOError, OSError):
pass
except Exception:
print("Couldn't read the floo_info file: %s" % floo_file)
room_url = info.get('url')
if room_url:
try:
result = utils.parse_url(room_url)
except Exception as e:
sublime.error_message(str(e))
else:
room_name = result['room']
floo_room_dir = os.path.join(G.COLAB_DIR, result['owner'], result['room'])
if os.path.realpath(floo_room_dir) == os.path.realpath(dir_to_share):
if result['owner'] == G.USERNAME:
try:
api.create_room(room_name)
print('Created room %s' % room_url)
except Exception as e:
print('Tried to create room' + str(e))
# they wanted to share teh dir, so always share it
return self.window.run_command('floobits_join_room', {'room_url': room_url})
# go make sym link
try:
utils.mkdir(os.path.dirname(floo_room_dir))
os.symlink(dir_to_share, floo_room_dir)
except OSError as e:
if e.errno != 17:
raise
except Exception as e:
return sublime.error_message("Couldn't create symlink from %s to %s: %s" % (dir_to_share, floo_room_dir, str(e)))
# make & join room
ON_CONNECT = lambda x: Listener.create_buf(dir_to_share)
self.window.run_command('floobits_create_room', {
'room_name': room_name,
'ln_path': floo_room_dir,
})
class FloobitsCreateRoomCommand(sublime_plugin.WindowCommand):
def run(self, room_name='', ln_path=None, prompt='Room name:'):
reload_settings()
self.ln_path = ln_path
self.window.show_input_panel(prompt, room_name, self.on_input, None, None)
def on_input(self, room_name):
try:
api.create_room(room_name)
room_url = 'https://%s/r/%s/%s' % (G.DEFAULT_HOST, G.USERNAME, room_name)
print('Created room %s' % room_url)
except HTTPError as e:
if e.code != 409:
raise
args = {
'room_name': room_name,
'prompt': 'Room %s already exists. Choose another name:' % room_name
}
if self.ln_path:
while True:
room_name = room_name + '1'
new_path = os.path.join(os.path.dirname(self.ln_path), room_name)
try:
os.rename(self.ln_path, new_path)
except OSError:
continue
args = {
'ln_path': new_path,
'room_name': room_name,
'prompt': 'Room %s already exists. Choose another name:' % room_name
}
break
return self.window.run_command('floobits_create_room', args)
except Exception as e:
sublime.error_message('Unable to create room: %s' % str(e))
return
if not disconnect_dialog():
return
webbrowser.open(room_url + '/settings', new=2, autoraise=True)
self.window.run_command('floobits_join_room', {
'room_url': room_url,
})
class FloobitsPromptJoinRoomCommand(sublime_plugin.WindowCommand):
def run(self, room=''):
self.window.show_input_panel('Room URL:', room, self.on_input, None, None)
def on_input(self, room_url):
if disconnect_dialog():
self.window.run_command('floobits_join_room', {
'room_url': room_url,
})
class FloobitsJoinRoomCommand(sublime_plugin.WindowCommand):
def run(self, room_url):
def open_room_window2(cb):
if sublime.platform() == 'linux':
subl = open('/proc/self/cmdline').read().split(chr(0))[0]
elif sublime.platform() == 'osx':
# TODO: totally explodes if you install ST2 somewhere else
subl = settings.get('sublime_executable', '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl')
elif sublime.platform() == 'windows':
subl = sys.executable
else:
raise Exception('WHAT PLATFORM ARE WE ON?!?!?')
command = [subl]
if utils.get_room_window() is None:
command.append('--new-window')
command.append('--add')
command.append(G.PROJECT_PATH)
# Maybe no msg view yet :(
print('command:', command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
poll_result = p.poll()
print('poll:', poll_result)
def truncate_chat_view(chat_view):
chat_view.set_read_only(False)
chat_view.run_command('floo_view_replace_region', {'r': [0, chat_view.size()], 'data': ''})
chat_view.set_read_only(True)
cb()
def create_chat_view():
with open(os.path.join(G.COLAB_DIR, 'msgs.floobits.log'), 'a') as msgs_fd:
msgs_fd.write('')
msg.get_or_create_chat(truncate_chat_view)
utils.set_room_window(create_chat_view)
def open_room_window3(cb):
G.ROOM_WINDOW = utils.get_room_window()
if not G.ROOM_WINDOW:
G.ROOM_WINDOW = sublime.active_window()
msg.debug('Setting project data. Path: %s' % G.PROJECT_PATH)
G.ROOM_WINDOW.set_project_data({'folders': [{'path': G.PROJECT_PATH}]})
def truncate_chat_view(chat_view):
chat_view.set_read_only(False)
chat_view.run_command('floo_view_replace_region', {'r': [0, chat_view.size()], 'data': ''})
chat_view.set_read_only(True)
cb()
with open(os.path.join(G.COLAB_DIR, 'msgs.floobits.log'), 'a') as msgs_fd:
msgs_fd.write('')
msg.get_or_create_chat(truncate_chat_view)
def open_room_window(cb):
if PY2:
open_room_window2(cb)
else:
open_room_window3(cb)
def run_agent(owner, room, host, port, secure):
global agent
if agent:
msg.debug('Stopping agent.')
agent.stop()
agent = None
try:
agent = AgentConnection(owner, room, host=host, port=port, secure=secure, on_connect=ON_CONNECT)
# owner and room name are slugfields so this should be safe
Listener.set_agent(agent)
agent.connect()
except Exception as e:
print(e)
tb = traceback.format_exc()
print(tb)
else:
joined_room = {'url': room_url}
update_recent_rooms(joined_room)
try:
result = utils.parse_url(room_url)
except Exception as e:
return sublime.error_message(str(e))
def run_thread(*args):
thread = threading.Thread(target=run_agent, kwargs=result)
thread.start()
def link_dir(d):
if d == '':
try:
utils.mkdir(G.PROJECT_PATH)
except Exception as e:
return sublime.error_message("Couldn't create directory %s: %s" % (G.PROJECT_PATH, str(e)))
return open_room_window(run_thread)
try:
utils.mkdir(os.path.dirname(G.PROJECT_PATH))
except Exception as e:
return sublime.error_message("Couldn't create directory %s: %s" % (os.path.dirname(G.PROJECT_PATH), str(e)))
d = os.path.realpath(os.path.expanduser(d))
if not os.path.isdir(d):
make_dir = sublime.ok_cancel_dialog('%s is not a directory. Create it?' % d)
if not make_dir:
return self.window.show_input_panel('%s is not a directory. Enter an existing path:' % d, d, link_dir, None, None)
try:
utils.mkdir(d)
except Exception as e:
return sublime.error_message("Could not create directory %s: %s" % (d, str(e)))
try:
os.symlink(d, G.PROJECT_PATH)
except Exception as e:
return sublime.error_message("Couldn't create symlink from %s to %s: %s" % (d, G.PROJECT_PATH, str(e)))
open_room_window(run_thread)
reload_settings()
G.PROJECT_PATH = os.path.realpath(os.path.join(G.COLAB_DIR, result['owner'], result['room']))
print('Project path is %s' % G.PROJECT_PATH)
if not os.path.isdir(G.PROJECT_PATH):
# TODO: really bad prompt here
return self.window.show_input_panel('Give me a directory to destructively dump data into (or just press enter):', '', link_dir, None, None)
open_room_window(run_thread)
class FloobitsLeaveRoomCommand(FloobitsBaseCommand):
def run(self):
global agent
if agent:
agent.stop()
agent = None
sublime.error_message('You have left the room.')
else:
sublime.error_message('You are not joined to any room.')
class FloobitsRejoinRoomCommand(FloobitsBaseCommand):
def run(self):
global agent
if agent:
room_url = utils.to_room_url({
'host': agent.host,
'owner': agent.owner,
'port': agent.port,
'room': agent.room,
'secure': agent.secure,
})
agent.stop()
agent = None
else:
try:
room_url = DATA['recent_rooms'][0]['url']
except Exception:
sublime.error_message('No recent room to rejoin.')
return
self.window.run_command('floobits_join_room', {
'room_url': room_url,
})
def is_visible(self):
return bool(self.is_enabled())
def is_enabled(self):
return True
class FloobitsPromptMsgCommand(FloobitsBaseCommand):
def run(self, msg=''):
print(('msg', msg))
self.window.show_input_panel('msg:', msg, self.on_input, None, None)
def on_input(self, msg):
self.window.run_command('floobits_msg', {'msg': msg})
class FloobitsMsgCommand(FloobitsBaseCommand):
def run(self, msg):
if not msg:
return
if agent:
agent.send_msg(msg)
def description(self):
return 'Send a message to the floobits room you are in (join a room first)'
class FloobitsClearHighlightsCommand(FloobitsBaseCommand):
def run(self):
Listener.clear_highlights(self.window.active_view())
class FloobitsPingCommand(FloobitsBaseCommand):
# TODO: ghost this option if user doesn't have permissions
def run(self):
Listener.ping(self.window.active_view())
class FloobitsJoinRecentRoomCommand(sublime_plugin.WindowCommand):
def _get_recent_rooms(self):
try:
recent_rooms = [x.get('url') for x in DATA['recent_rooms'] if x.get('url') is not None]
except Exception:
recent_rooms = []
return recent_rooms
def run(self, *args):
rooms = self._get_recent_rooms()
self.window.show_quick_panel(rooms, self.on_done)
def on_done(self, item):
if item == -1:
return
room = DATA['recent_rooms'][item]
if disconnect_dialog():
self.window.run_command('floobits_join_room', {'room_url': room['url']})
def is_enabled(self):
return bool(len(self._get_recent_rooms()) > 0)
class FloobitsOpenMessageViewCommand(FloobitsBaseCommand):
def run(self, *args):
def print_msg(chat_view):
msg.log('Opened message view')
if not agent:
msg.log('Not joined to a room.')
msg.get_or_create_chat(print_msg)
def description(self):
return 'Open the floobits messages view.'
class FloobitsAddToRoomCommand(FloobitsBaseCommand):
def run(self, paths, current_file=False):
if not self.is_enabled():
return
if paths is None and current_file:
paths = [self.window.active_view().file_name()]
for path in paths:
Listener.create_buf(path)
def description(self):
return 'Add file or directory to currently-joined Floobits room.'
class FloobitsDeleteFromRoomCommand(FloobitsBaseCommand):
def run(self, paths, current_file=False):
if not self.is_enabled():
return
confirm = bool(sublime.ok_cancel_dialog('This will delete your local copy as well. Are you sure you want do do this?'))
if not confirm:
return
if paths is None and current_file:
paths = [self.window.active_view().file_name()]
for path in paths:
Listener.delete_buf(path)
def description(self):
return 'Add file or directory to currently-joined Floobits room.'
class FloobitsEnableFollowModeCommand(FloobitsBaseCommand):
def run(self):
G.FOLLOW_MODE = True
# TODO: go to most recent highlight
def is_visible(self):
return bool(self.is_enabled())
def is_enabled(self):
return bool(agent and agent.is_ready() and not G.FOLLOW_MODE)
class FloobitsDisableFollowModeCommand(FloobitsBaseCommand):
def run(self):
G.FOLLOW_MODE = False
def is_visible(self):
return bool(self.is_enabled())
def is_enabled(self):
return bool(agent and agent.is_ready() and G.FOLLOW_MODE)
class FloobitsNotACommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
pass
def is_visible(self):
return True
def is_enabled(self):
return False
def description(self):
return
# The new ST3 plugin API sucks
class FlooViewSetMsg(sublime_plugin.TextCommand):
def run(self, edit, data, *args, **kwargs):
size = self.view.size()
self.view.set_read_only(False)
self.view.insert(edit, size, data)
self.view.set_read_only(True)
# TODO: this scrolling is lame and centers text :/
self.view.show(size)
def is_visible(self):
return False
def is_enabled(self):
return True
def description(self):
return
# The new ST3 plugin API sucks
class FlooViewReplaceRegion(sublime_plugin.TextCommand):
def run(self, edit, r, data, *args, **kwargs):
region = sublime.Region(int(r[0]), int(r[1]))
self.view.replace(edit, region, data)
def is_visible(self):
return False
def is_enabled(self):
return True
def description(self):
return
Listener.push()