Debian Codegraph @

dropbox.in

raw ◀ ▶
Source reconstructed at patch state 0 of 6 — not the installed (fully patched) source.
6 Debian patches touch this file
1 #!/usr/bin/env python3
2 #
3 # Copyright (c) Dropbox, Inc.
4 #
5 # dropbox
6 # Dropbox frontend script
7 # This file is part of nautilus-dropbox @PACKAGE_VERSION@.
8 #
9 # nautilus-dropbox is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # nautilus-dropbox is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with nautilus-dropbox. If not, see <http://www.gnu.org/licenses/>.
21 #
22 from __future__ import with_statement
23
24 import errno
25 import locale
26 import optparse
27 import os
28 import platform
29 import shutil
30 import socket
31 import subprocess
32 import sys
33 import tarfile
34 import tempfile
35 import threading
36 import _thread
37 import time
38 import traceback
39 import urllib.request
40
41 try:
42 import gpg
43 gpgme = None
44 except ImportError:
45 gpg = None
46 # Still support gpgme for now. Remove this once we only support 17.04+.
47 try:
48 import gpgme
49 except ImportError:
50 gpgme = None
51
52 from contextlib import closing, contextmanager
53 from io import BytesIO
54 from operator import methodcaller
55 from os.path import relpath
56 from posixpath import curdir, sep, pardir, join, abspath, commonprefix
57
58 INFO = "Dropbox is the easiest way to share and store your files online. Want to learn more? Head to"
59 LINK = "https://www.dropbox.com/"
60 WARNING = "In order to use Dropbox, you must download the proprietary daemon."
61 GPG_WARNING = "Note: python3-gpg (python3-gpgme for Ubuntu 16.10 and lower) is not installed, we will not be able to verify binary signatures."
62 ERROR_CONNECTING = "Trouble connecting to Dropbox servers. Maybe your internet connection is down, or you need to set your http_proxy environment variable."
63 ERROR_SIGNATURE = "Downloaded binary does not match Dropbox signature, aborting install."
64 ERROR_INVALID_DROPBOX = "Could not start the Dropbox daemon. Make sure your computer meets the minimum requirements:\nhttps://www.dropbox.com/help/desktop-web/system-requirements#desktop"
65
66 DOWNLOAD_LOCATION_FMT = "https://www.dropbox.com/download?plat=%s"
67 SIGNATURE_LOCATION_FMT = "https://www.dropbox.com/download?plat=%s&signature=1"
68
69 DOWNLOADING = "Downloading Dropbox... %d%%"
70 UNPACKING = "Unpacking Dropbox... %d%%"
71
72 PARENT_DIR = os.path.expanduser("~")
73 DROPBOX_DIST_PATH = "%s/.dropbox-dist" % PARENT_DIR
74 DROPBOXD_PATH = os.path.join(DROPBOX_DIST_PATH, "dropboxd")
75 DESKTOP_FILE = "@DESKTOP_FILE_DIR@/dropbox.desktop"
76
77 enc = locale.getpreferredencoding()
78
79 # Available from https://linux.dropbox.com/fedora/rpm-public-key.asc
80 DROPBOX_PUBLIC_KEY = b"""
81 -----BEGIN PGP PUBLIC KEY BLOCK-----
82 Version: SKS 1.1.0
83
84 mQENBEt0ibEBCACv4hZRPqwtpU6z8+BB5YZU1a3yjEvg2W68+a6hEwxtCa2U++4dzQ+7EqaU
85 q5ybQnwtbDdpFpsOi9x31J+PCpufPUfIG694/0rlEpmzl2GWzY8NqfdBFGGm/SPSSwvKbeNc
86 FMRLu5neo7W9kwvfMbGjHmvUbzBUVpCVKD0OEEf1q/Ii0Qcekx9CMoLvWq7ZwNHEbNnij7ec
87 nvwNlE2MxNsOSJj+hwZGK+tM19kuYGSKw4b5mR8IyThlgiSLIfpSBh1n2KX+TDdk9GR+57TY
88 vlRu6nTPu98P05IlrrCP+KF0hYZYOaMvQs9Rmc09tc/eoQlN0kkaBWw9Rv/dvLVc0aUXABEB
89 AAG0MURyb3Bib3ggQXV0b21hdGljIFNpZ25pbmcgS2V5IDxsaW51eEBkcm9wYm94LmNvbT6J
90 ATYEEwECACAFAkt0ibECGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRD8kYszUESRLi/z
91 B/wMscEa15rS+0mIpsORknD7kawKwyda+LHdtZc0hD/73QGFINR2P23UTol/R4nyAFEuYNsF
92 0C4IAD6y4pL49eZ72IktPrr4H27Q9eXhNZfJhD7BvQMBx75L0F5gSQwuC7GdYNlwSlCD0AAh
93 Qbi70VBwzeIgITBkMQcJIhLvllYo/AKD7Gv9huy4RLaIoSeofp+2Q0zUHNPl/7zymOqu+5Ox
94 e1ltuJT/kd/8hU+N5WNxJTSaOK0sF1/wWFM6rWd6XQUP03VyNosAevX5tBo++iD1WY2/lFVU
95 JkvAvge2WFk3c6tAwZT/tKxspFy4M/tNbDKeyvr685XKJw9ei6GcOGHD
96 =5rWG
97 -----END PGP PUBLIC KEY BLOCK-----
98 """
99
100
101 def console_print(st="", f=sys.stdout, linebreak=True):
102 f.write(st)
103 if linebreak: f.write(os.linesep)
104
105 def console_flush(f=sys.stdout):
106 f.flush()
107
108 def yes_no_question(question):
109 while True:
110 console_print(question, linebreak=False)
111 console_print(" [y/n] ", linebreak=False)
112 console_flush()
113 text = input()
114 if text.lower().startswith("y"):
115 return True
116 elif text.lower().startswith("n"):
117 return False
118 else:
119 console_print("Sorry, I didn't understand that. Please type yes or no.")
120
121 def plat():
122 if sys.platform.lower().startswith('linux'):
123 arch = subprocess.Popen(["dpkg", "--print-architecture"],
124 stdout=subprocess.PIPE).communicate()[0].decode('utf-8')
125 arch = arch.rstrip("\n")
126 if arch == "i386":
127 plat = "x86"
128 elif arch == "amd64":
129 plat = "x86_64"
130 else:
131 FatalVisibleError("Platform not supported")
132 return "lnx.%s" % plat
133 else:
134 FatalVisibleError("Platform not supported")
135
136 def is_dropbox_running():
137 pidfile = os.path.expanduser("~/.dropbox/dropbox.pid")
138
139 try:
140 with open(pidfile, "r") as f:
141 pid = int(f.read())
142 with open("/proc/%d/cmdline" % pid, "r") as f:
143 cmdline = f.read().lower()
144 except:
145 cmdline = ""
146
147 return "dropbox" in cmdline
148
149 @contextmanager
150 def gpg_context(keys):
151 gpg_conf_contents = b''
152 _gpghome = tempfile.mkdtemp(prefix='tmp.gpghome')
153
154 try:
155 os.environ['GNUPGHOME'] = _gpghome
156 fp = open(os.path.join(_gpghome, 'gpg.conf'), 'wb')
157 fp.write(gpg_conf_contents)
158 fp.close()
159 if gpg:
160 ctx = gpg.Context()
161 else:
162 ctx = gpgme.Context()
163
164 loaded = []
165 for key_file in keys:
166 if gpg:
167 ctx.op_import(key_file.read())
168 result = ctx.op_import_result()
169 key = ctx.get_key(result.imports[0].fpr)
170 else:
171 result = ctx.import_(key_file)
172 key = ctx.get_key(result.imports[0][0])
173 loaded.append(key)
174
175 ctx.signers = loaded
176
177 yield ctx
178 finally:
179 del os.environ['GNUPGHOME']
180 shutil.rmtree(_gpghome, ignore_errors=True)
181
182 class SignatureVerifyError(Exception):
183 pass
184
185 def verify_signature(key_file, sig_file, plain_file):
186 with gpg_context([key_file]) as ctx:
187 if gpg:
188 ctx.op_verify(sig_file.read(), plain_file.read(), None)
189 result = ctx.op_verify_result()
190 return result.signatures[0].status == 0
191 # gpgme exists
192 sigs = ctx.verify(sig_file, plain_file, None)
193 return sigs[0].status == None
194
195
196 def download_file_chunk(url, buf):
197 opener = urllib.request.build_opener()
198 opener.addheaders = [('User-Agent', "DropboxLinuxDownloader/@PACKAGE_VERSION@")]
199
200 with closing(opener.open(url)) as f:
201 size = int(f.info()['content-length'])
202 bufsize = int(max(size / 200, 4096))
203 progress = 0
204 yield (0, True)
205 while True:
206 try:
207 chunk = f.read(bufsize)
208 progress += len(chunk)
209 buf.write(chunk)
210 yield (float(progress)/size, True)
211 if progress == size:
212 break
213 except OSError as e:
214 if hasattr(e, 'errno') and e.errno == errno.EAGAIN:
215 # nothing left to read
216 yield (float(progress)/size, False)
217 else:
218 raise
219
220 class DownloadState(object):
221 def __init__(self):
222 self.local_file = BytesIO()
223
224 def copy_data(self):
225 return download_file_chunk(DOWNLOAD_LOCATION_FMT % plat(), self.local_file)
226
227 def unpack(self):
228 # download signature
229 signature = BytesIO()
230 for _ in download_file_chunk(SIGNATURE_LOCATION_FMT % plat(), signature):
231 pass
232 signature.seek(0)
233 self.local_file.seek(0)
234
235 if gpg or gpgme:
236 if not verify_signature(BytesIO(DROPBOX_PUBLIC_KEY), signature, self.local_file):
237 raise SignatureVerifyError()
238
239 self.local_file.seek(0)
240 archive = tarfile.open(fileobj=self.local_file, mode='r:gz')
241 total_members = len(archive.getmembers())
242 for i, member in enumerate(archive.getmembers()):
243 filename = os.path.join(PARENT_DIR, member.name)
244 if os.path.exists(filename) and not os.path.isdir(filename):
245 os.unlink(filename)
246 archive.extract(member, PARENT_DIR)
247 yield member.name, i, total_members
248 archive.close()
249
250 def cancel(self):
251 if not self.local_file.closed:
252 self.local_file.close()
253
254 def is_dropbox_valid(self):
255 """
256 Validate that Dropbox runs, so we can show an error
257 message to the user if it doesn't work.
258
259 Returns True if Dropbox can run, false otherwise.
260 """
261 f = open("/dev/null", "w")
262 try:
263 a = subprocess.Popen([DROPBOXD_PATH, "/testrun", "0"], preexec_fn=os.setsid, cwd=os.path.expanduser("~"),
264 stderr=sys.stderr, stdout=f, close_fds=True)
265 except Exception as e:
266 print(e)
267 return False
268
269 # in seconds
270 interval = 0.5
271 wait_for = 30
272 for _ in range(int(wait_for / interval)):
273 ret_val = a.poll()
274 if ret_val is None:
275 time.sleep(interval)
276 continue
277 return ret_val == 0
278
279 return False
280
281
282 def load_serialized_images():
283 global box_logo_pixbuf, window_icon
284 import gi
285 gi.require_version('GdkPixbuf', '2.0')
286 from gi.repository import GdkPixbuf
287 box_logo_pixbuf = @IMAGEDATA64@
288 window_icon = @IMAGEDATA16@
289
290 GUI_AVAILABLE = os.environ.get("DISPLAY", '')
291
292 if GUI_AVAILABLE:
293 def download():
294 import gi
295 gi.require_version('Gdk', '3.0')
296 gi.require_version('Gtk', '3.0')
297 from gi.repository import GObject
298 from gi.repository import Gdk
299 from gi.repository import Gtk
300 from gi.repository import Pango
301 import webbrowser
302
303 GObject.threads_init()
304
305 load_serialized_images()
306
307 global FatalVisibleError
308 def FatalVisibleError(s):
309 error = Gtk.MessageDialog(parent = None,
310 flags = Gtk.DialogFlags.MODAL,
311 type = Gtk.MessageType.ERROR,
312 buttons = Gtk.ButtonsType.OK,
313 message_format = s)
314 error.set_title("Error")
315 error.run()
316 Gtk.main_quit()
317 sys.exit(-1)
318
319 class GeneratorTask(object):
320 def __init__(self, generator, loop_callback, on_done=None, on_exception=None):
321 self.generator = generator
322 self.loop_callback = loop_callback
323 self.on_done = on_done
324 self.on_exception = on_exception
325
326 def _run(self, *args, **kwargs):
327 self._stopped = False
328 try:
329 for ret in self.generator(*args, **kwargs):
330 if ret is None:
331 ret = ()
332 if not isinstance(ret, tuple):
333 ret = (ret,)
334 GObject.idle_add(self.loop_callback, *ret)
335
336 if self._stopped:
337 _thread.exit()
338 except Exception as e:
339 print(e)
340 if self.on_exception is not None:
341 GObject.idle_add(self.on_exception, e)
342 else:
343 if self.on_done is not None:
344 GObject.idle_add(self.on_done)
345
346 def start(self, *args, **kwargs):
347 t = threading.Thread(target=self._run, args=args, kwargs=kwargs)
348 t.setDaemon(True)
349 t.start()
350
351 def stop(self):
352 self._stopped = True
353
354 class DownloadDialog(Gtk.Dialog):
355 def handle_delete_event(self, wid, ev, data=None):
356 self.handle_cancel(wid)
357
358 def handle_dont_show_toggle(self, button, data=None):
359 reroll_autostart(not button.get_active())
360
361 def handle_cancel(self, button):
362 if self.task:
363 self.task.stop()
364 if self.download:
365 self.download.cancel()
366 Gtk.main_quit()
367 self.user_cancelled = True
368
369 def handle_ok(self, button):
370 # begin download
371 self.ok.hide()
372 self.download = DownloadState()
373
374 self.label.hide()
375 if self.dont_show_again_align is not None:
376 self.dont_show_again_align.hide()
377 self.progress.show()
378
379 def download_progress(progress, status):
380 if not status:
381 self.task.stop()
382 self.update_progress(DOWNLOADING, progress)
383
384 def finished():
385 self.update_progress(DOWNLOADING, 1.0)
386 self.unpack_dropbox()
387
388 def error(ex):
389 FatalVisibleError(ERROR_CONNECTING)
390
391 self.update_progress(DOWNLOADING, 0)
392 self.task = GeneratorTask(self.download.copy_data,
393 download_progress,
394 finished, error).start()
395
396 def update_progress(self, text, fraction):
397 self.progress.set_text(text % int(fraction*100))
398 self.progress.set_fraction(fraction)
399
400 def unpack_dropbox(self):
401 def unpack_progress(name, i, total):
402 self.update_progress(UNPACKING, float(i)/total)
403
404 def finished():
405 self.update_progress(UNPACKING, 1.0)
406 if not self.download.is_dropbox_valid():
407 FatalVisibleError(ERROR_INVALID_DROPBOX)
408 Gtk.main_quit()
409
410 def error(ex):
411 if isinstance(ex, SignatureVerifyError):
412 FatalVisibleError(ERROR_SIGNATURE)
413 else:
414 FatalVisibleError(ERROR_CONNECTING)
415
416 self.task = GeneratorTask(self.download.unpack,
417 unpack_progress,
418 finished, error).start()
419
420 def mouse_down(self, widget, event):
421 if self.hovering:
422 self.clicked_link = True
423
424 def mouse_up(self, widget, event):
425 if self.clicked_link:
426 webbrowser.open(LINK)
427 self.clicked_link = False
428
429 def label_motion(self, widget, event):
430 offx, offy = self.label.get_layout_offsets()
431 layout = self.label.get_layout()
432 index = layout.xy_to_index(int((offx+event.x)*Pango.SCALE),
433 int((offy+event.y)*Pango.SCALE))[1]
434 link_index = layout.get_text().find(LINK)
435 if index >= link_index and index < link_index+len(LINK):
436 self.hovering = True
437 self.label_box.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.HAND2))
438 else:
439 self.hovering = False
440 self.label_box.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.ARROW))
441
442
443 def __init__(self):
444 super(DownloadDialog, self).__init__(parent = None,
445 title = "Dropbox Installation")
446
447 self.download = None
448 self.hovering = False
449 self.clicked_link = False
450 self.user_cancelled = False
451 self.task = None
452
453 self.ok = ok = Gtk.Button(stock=Gtk.STOCK_OK)
454 ok.connect('clicked', self.handle_ok)
455 self.action_area.add(ok)
456 ok.show()
457
458 cancel = Gtk.Button(stock=Gtk.STOCK_CANCEL)
459 cancel.connect('clicked', self.handle_cancel)
460 self.action_area.add(cancel)
461 cancel.show()
462
463 self.connect('delete_event', self.handle_delete_event)
464
465 self.box_logo = Gtk.Image.new_from_pixbuf(box_logo_pixbuf)
466 self.box_logo.show()
467
468 self.set_icon(window_icon)
469
470 self.progress = Gtk.ProgressBar()
471 self.progress.set_property('width-request', 300)
472 self.progress.set_property('show-text', True)
473
474 self.label = Gtk.Label()
475 GPG_WARNING_MSG = ("\n\n" + GPG_WARNING) if not gpg and not gpgme else ""
476 self.label.set_markup('%s <span foreground="#000099" underline="single" weight="bold">%s</span>\n\n%s%s' % (INFO, LINK, WARNING, GPG_WARNING_MSG))
477 self.label.set_line_wrap(True)
478 self.label.set_property('width-request', 300)
479 self.label.show()
480
481 self.label_box = Gtk.EventBox()
482 self.label_box.add(self.label)
483 self.label_box.connect("button-release-event", self.mouse_up)
484 self.label_box.connect("button-press-event", self.mouse_down)
485 self.label_box.connect("motion-notify-event", self.label_motion)
486
487 self.label_box.show()
488 def on_realize(widget):
489 self.label_box.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
490 self.label_box.connect("realize", on_realize)
491
492 self.hbox = Gtk.HBox(spacing=10)
493 self.hbox.set_property('border-width',10)
494 self.hbox.pack_start(self.box_logo, False, False, 0)
495 self.hbox.pack_start(self.label_box, False, False, 0)
496 self.hbox.pack_start(self.progress, False, False, 0)
497 self.hbox.show()
498
499 self.vbox.add(self.hbox)
500
501 self.dont_show_again_align = None
502
503 try:
504 if can_reroll_autostart():
505 dont_show_again = Gtk.CheckButton.new_with_mnemonic("_Don't show this again")
506 dont_show_again.connect('toggled', self.handle_dont_show_toggle)
507 dont_show_again.show()
508
509 self.dont_show_again_align = Gtk.Alignment(xalign=1.0, yalign=0.0, xscale=0.0, yscale=0.0)
510 self.dont_show_again_align.add(dont_show_again)
511 self.dont_show_again_align.show()
512
513 hbox = Gtk.HBox()
514 hbox.set_property('border-width', 10)
515 hbox.pack_start(self.dont_show_again_align, True, True, 0)
516 hbox.show()
517
518 self.vbox.add(hbox)
519
520 self.set_resizable(False)
521 except:
522 traceback.print_exc()
523
524 self.ok.grab_focus()
525
526 dialog = DownloadDialog()
527 dialog.show()
528 Gtk.main()
529 if dialog.user_cancelled:
530 raise Exception("user cancelled download!!!")
531 else:
532 def download():
533 global FatalVisibleError
534 def FatalVisibleError(s):
535 console_print("\nError: %s" % s, f=sys.stderr)
536 sys.exit(-1)
537
538
539 ESC = "\x1b"
540 save = ESC+"7"
541 unsave = ESC+"8"
542 erase_to_start = ESC+"[1K"
543 write = sys.stdout.write
544 flush = sys.stdout.flush
545
546 last_progress = [None, None]
547 def setprogress(text, frac):
548 if last_progress == [text, frac]:
549 return
550 if sys.stdout.isatty():
551 write(erase_to_start)
552 write(unsave)
553 console_print(text % int(100*frac), linebreak=not sys.stdout.isatty())
554 if sys.stdout.isatty():
555 flush()
556 last_progress[0], last_progress[1] = text, frac
557
558 console_print()
559 if sys.stdout.isatty():
560 write(save)
561 flush()
562 console_print("%s %s\n" % (INFO, LINK))
563 if not gpg and not gpgme:
564 if not yes_no_question("%s" % (GPG_WARNING)):
565 return
566
567 download = DownloadState()
568
569 try:
570 for progress, status in download.copy_data():
571 if not status:
572 break
573 setprogress(DOWNLOADING, progress)
574 except Exception:
575 traceback.print_exc()
576 FatalVisibleError(ERROR_CONNECTING)
577 else:
578 setprogress(DOWNLOADING, 1.0)
579 console_print()
580 write(save)
581
582 try:
583 for _, i, total in download.unpack():
584 setprogress(UNPACKING, float(i)/total)
585 except SignatureVerifyError:
586 traceback.print_exc()
587 FatalVisibleError(ERROR_SIGNATURE)
588 except Exception:
589 traceback.print_exc()
590 FatalVisibleError(ERROR_CONNECTING)
591 else:
592 setprogress(UNPACKING, 1.0)
593
594 if not download.is_dropbox_valid():
595 FatalVisibleError(ERROR_INVALID_DROPBOX)
596
597 console_print()
598
599 class CommandTicker(threading.Thread):
600 def __init__(self):
601 threading.Thread.__init__(self)
602 self.stop_event = threading.Event()
603
604 def stop(self):
605 self.stop_event.set()
606
607 def run(self):
608 ticks = ['[. ]', '[.. ]', '[...]', '[ ..]', '[ .]', '[ ]']
609 i = 0
610 first = True
611 while True:
612 self.stop_event.wait(0.25)
613 if self.stop_event.isSet(): break
614 if i == len(ticks):
615 first = False
616 i = 0
617 if not first:
618 sys.stderr.write("\r%s\r" % ticks[i])
619 sys.stderr.flush()
620 i += 1
621 sys.stderr.flush()
622
623
624 class DropboxCommand(object):
625 class CouldntConnectError(Exception): pass
626 class BadConnectionError(Exception): pass
627 class EOFError(Exception): pass
628 class CommandError(Exception): pass
629
630 def __init__(self, timeout=5):
631 self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
632 self.s.settimeout(timeout)
633 try:
634 self.s.connect(os.path.expanduser('~/.dropbox/command_socket'))
635 except socket.error:
636 raise DropboxCommand.CouldntConnectError()
637 self.f = self.s.makefile("rw", 4096)
638
639 def close(self):
640 self.f.close()
641 self.s.close()
642
643 def __readline(self):
644 try:
645 toret = self.f.readline().rstrip("\n")
646 except socket.error:
647 raise DropboxCommand.BadConnectionError()
648 if toret == '':
649 raise DropboxCommand.EOFError()
650 else:
651 return toret
652
653 # atttribute doesn't exist, i know what you want
654 def send_command(self, name, args):
655 self.f.write(name)
656 self.f.write("\n")
657 self.f.writelines(("\t".join([k] + ([v]
658 if isinstance(v, str) else
659 list(v))) + "\n")
660 for k,v in args.items())
661 self.f.write("done\n")
662
663 self.f.flush()
664
665 # Start a ticker
666 ticker_thread = CommandTicker()
667 ticker_thread.start()
668
669 # This is the potentially long-running call.
670 try:
671 ok = self.__readline() == "ok"
672 except KeyboardInterrupt:
673 raise DropboxCommand.BadConnectionError("Keyboard interruption detected")
674 finally:
675 # Tell the ticker to stop.
676 ticker_thread.stop()
677 ticker_thread.join()
678
679 if ok:
680 toret = {}
681 for i in range(21):
682 if i == 20:
683 raise Exception("close this connection!")
684
685 line = self.__readline()
686 if line == "done":
687 break
688
689 argval = line.split("\t")
690 toret[argval[0]] = argval[1:]
691
692 return toret
693 else:
694 problems = []
695 for i in range(21):
696 if i == 20:
697 raise Exception("close this connection!")
698
699 line = self.__readline()
700 if line == "done":
701 break
702
703 problems.append(line)
704
705 raise DropboxCommand.CommandError("\n".join(problems))
706
707 # this is the hotness, auto marshalling
708 def __getattr__(self, name):
709 try:
710 return super(DropboxCommand, self).__getattr__(name)
711 except:
712 def __spec_command(**kw):
713 return self.send_command(str(name), kw)
714 self.__setattr__(name, __spec_command)
715 return __spec_command
716
717 commands = {}
718 aliases = {}
719
720 def command(meth):
721 global commands, aliases
722 assert meth.__doc__, "All commands need properly formatted docstrings (even %r!!)" % meth
723 if hasattr(meth, 'im_func'): # bound method, if we ever have one
724 meth = meth.im_func
725 commands[meth.__name__] = meth
726 meth_aliases = [str(alias) for alias in aliases.keys() if aliases[alias].__name__ == meth.__name__]
727 if meth_aliases:
728 meth.__doc__ += "\nAliases: %s" % ",".join(meth_aliases)
729 return meth
730
731 def alias(name):
732 def decorator(meth):
733 global commands, aliases
734 assert name not in commands, "This alias is the name of a command."
735 aliases[name] = meth
736 return meth
737 return decorator
738
739 def requires_dropbox_running(meth):
740 def newmeth(*n, **kw):
741 if is_dropbox_running():
742 return meth(*n, **kw)
743 else:
744 console_print("Dropbox isn't running!")
745 newmeth.__name__ = meth.__name__
746 newmeth.__doc__ = meth.__doc__
747 return newmeth
748
749 def start_dropbox():
750 if os.access(DROPBOXD_PATH, os.X_OK):
751 f = open("/dev/null", "w")
752
753 # Fix indicator icon and menu on Unity environments. (LP: #1559249)
754 # Fix indicator icon and menu in Budgie environment. (LP: #1683051)
755 new_env = os.environ.copy()
756 current_env = os.environ.get("XDG_CURRENT_DESKTOP", '').split(":")
757 to_check = ['Unity', 'Budgie']
758 if any(word in to_check for word in current_env):
759 new_env['XDG_CURRENT_DESKTOP'] = 'Unity'
760
761 # we don't reap the child because we're gonna die anyway, let init do it
762 subprocess.Popen([DROPBOXD_PATH], preexec_fn=os.setsid, cwd=os.path.expanduser("~"),
763 stderr=sys.stderr, stdout=f, close_fds=True, env=new_env)
764
765 # in seconds
766 interval = 0.5
767 wait_for = 60
768 for _ in range(int(wait_for / interval)):
769 if is_dropbox_running():
770 return True
771 # back off from connect for a while
772 time.sleep(interval)
773
774 return False
775 else:
776 return False
777
778 # Extracted and modified from os.cmd.Cmd
779 def columnize(list, display_list=None, display_width=None):
780 if not list:
781 console_print("<empty>")
782 return
783
784 non_str = [i for i in range(len(list)) if not (isinstance(list[i], str))]
785 if non_str:
786 raise TypeError("list[i] not a string for i in %s" %
787 ", ".join(map(str, non_str)))
788
789 if not display_width:
790 d = os.popen('stty size', 'r').read().split()
791 if d:
792 display_width = int(d[1])
793 else:
794 for item in list:
795 console_print(item)
796 return
797
798 if not display_list:
799 display_list = list
800
801 size = len(list)
802 if size == 1:
803 console_print(display_list[0])
804 return
805
806 for nrows in range(1, len(list)):
807 ncols = (size+nrows-1) // nrows
808 colwidths = []
809 totwidth = -2
810 for col in range(ncols):
811 colwidth = 0
812 for row in range(nrows):
813 i = row + nrows*col
814 if i >= size:
815 break
816 x = list[i]
817 colwidth = max(colwidth, len(x))
818 colwidths.append(colwidth)
819 totwidth += colwidth + 2
820 if totwidth > display_width:
821 break
822 if totwidth <= display_width:
823 break
824 else:
825 nrows = len(list)
826 ncols = 1
827 colwidths = [0]
828 lines = []
829 for row in range(nrows):
830 texts = []
831 display_texts = []
832 for col in range(ncols):
833 i = row + nrows*col
834 if i >= size:
835 x = ""
836 y = ""
837 else:
838 x = list[i]
839 y = display_list[i]
840 texts.append(x)
841 display_texts.append(y)
842 while texts and not texts[-1]:
843 del texts[-1]
844 original_texts = texts[:]
845 for col in range(len(texts)):
846 texts[col] = texts[col].ljust(colwidths[col])
847 texts[col] = texts[col].replace(original_texts[col], display_texts[col])
848 line = " ".join(texts)
849 lines.append(line)
850 for line in lines:
851 console_print(line)
852
853 @command
854 def update(args):
855 """download latest version of Dropbox
856 dropbox update
857
858 Downloads the latest version of Dropbox. This should not be required
859 normally, as Dropbox automatically updates itself.
860 """
861 download()
862
863 @command
864 def update(args):
865 u"""download latest version of dropbox
866 dropbox update
867
868 Downloads the latest version of dropbox.
869 """
870 download()
871
872 @command
873 @requires_dropbox_running
874 @alias('stat')
875 def filestatus(args):
876 """get current sync status of one or more files
877 dropbox filestatus [-l] [-a] [FILE]...
878
879 Prints the current status of each FILE.
880
881 options:
882 -l --list Prints out information in a format similar to ls. Works best when your console supports color :)
883 -a --all Do not ignore entries starting with "."
884 """
885 global enc
886
887 oparser = optparse.OptionParser()
888 oparser.add_option("-l", "--list", action="store_true", dest="list")
889 oparser.add_option("-a", "--all", action="store_true", dest="all")
890 (options, args) = oparser.parse_args(args)
891
892 try:
893 with closing(DropboxCommand()) as dc:
894 if options.list:
895 # Listing.
896
897 # Separate directories from files.
898 if len(args) == 0:
899 dirs, nondirs = ["."], []
900 else:
901 dirs, nondirs = [], []
902
903 for a in args:
904 try:
905 (dirs if os.path.isdir(a) else nondirs).append(a)
906 except UnicodeDecodeError:
907 continue
908
909 if len(dirs) == 0 and len(nondirs) == 0:
910 #TODO: why?
911 exit(1)
912
913 dirs.sort(key=methodcaller('lower'))
914 nondirs.sort(key=methodcaller('lower'))
915
916 # Gets a string representation for a path.
917 def path_to_string(file_path):
918 if not os.path.exists(file_path):
919 path = "%s (File doesn't exist!)" % os.path.basename(file_path)
920 return (path, path)
921 try:
922 status = dc.icon_overlay_file_status(path=file_path).get('status', [None])[0]
923 except DropboxCommand.CommandError as e:
924 path = "%s (%s)" % (os.path.basename(file_path), e)
925 return (path, path)
926
927 env_term = os.environ.get('TERM','')
928 supports_color = (sys.stderr.isatty() and (
929 env_term.startswith('vt') or
930 env_term.startswith('linux') or
931 'xterm' in env_term or
932 'color' in env_term
933 )
934 )
935
936 # TODO: Test when you don't support color.
937 if not supports_color:
938 path = os.path.basename(file_path)
939 return (path, path)
940
941 if status == "up to date":
942 init, cleanup = "\x1b[32;1m", "\x1b[0m"
943 elif status == "syncing":
944 init, cleanup = "\x1b[36;1m", "\x1b[0m"
945 elif status == "unsyncable":
946 init, cleanup = "\x1b[41;1m", "\x1b[0m"
947 elif status == "selsync":
948 init, cleanup = "\x1b[37;1m", "\x1b[0m"
949 else:
950 init, cleanup = '', ''
951
952 path = os.path.basename(file_path)
953 return (path, "%s%s%s" % (init, path, cleanup))
954
955 # Prints a directory.
956 def print_directory(name):
957 clean_paths = []
958 formatted_paths = []
959 for subname in sorted(os.listdir(name), key=methodcaller('lower')):
960 if type(subname) != str:
961 continue
962
963 if not options.all and subname[0] == '.':
964 continue
965
966 try:
967 clean, formatted = path_to_string(os.path.abspath(os.path.join(name, subname)))
968 clean_paths.append(clean)
969 formatted_paths.append(formatted)
970 except (UnicodeEncodeError, UnicodeDecodeError):
971 continue
972
973 columnize(clean_paths, formatted_paths)
974
975 try:
976 if len(dirs) == 1 and len(nondirs) == 0:
977 print_directory(dirs[0])
978 else:
979 nondir_formatted_paths = []
980 nondir_clean_paths = []
981 for name in nondirs:
982 try:
983 clean, formatted = path_to_string(os.path.abspath(name))
984 nondir_clean_paths.append(clean)
985 nondir_formatted_paths.append(formatted)
986 except (UnicodeEncodeError, UnicodeDecodeError):
987 continue
988
989 if nondir_clean_paths:
990 columnize(nondir_clean_paths, nondir_formatted_paths)
991
992 if len(nondirs) == 0:
993 console_print(dirs[0] + ":")
994 print_directory(dirs[0])
995 dirs = dirs[1:]
996
997 for name in dirs:
998 console_print()
999 console_print(name + ":")
1000 print_directory(name)
1001
1002 except DropboxCommand.EOFError:
1003 console_print("Dropbox daemon stopped.")
1004 except DropboxCommand.BadConnectionError:
1005 console_print("Dropbox isn't responding!")
1006 else:
1007 if len(args) == 0:
1008 args = [name for name in sorted(os.listdir("."), key=methodcaller('lower')) if type(name) == str]
1009 if len(args) == 0:
1010 # Bail early if there's nothing to list to avoid crashing on indent below
1011 console_print("<empty>")
1012 return
1013 indent = max(len(st)+1 for st in args)
1014 for file in args:
1015
1016 try:
1017 if type(file) is not str:
1018 file = file.decode(enc)
1019 fp = os.path.abspath(file)
1020 except (UnicodeEncodeError, UnicodeDecodeError):
1021 continue
1022 if not os.path.exists(fp):
1023 console_print("%-*s %s" % \
1024 (indent, file+':', "File doesn't exist"))
1025 continue
1026
1027 try:
1028 status = dc.icon_overlay_file_status(path=fp).get('status', ['unknown'])[0]
1029 console_print("%-*s %s" % (indent, file+':', status))
1030 except DropboxCommand.CommandError as e:
1031 console_print("%-*s %s" % (indent, file+':', e))
1032 except DropboxCommand.CouldntConnectError:
1033 console_print("Dropbox isn't running!")
1034
1035 @command
1036 @requires_dropbox_running
1037 def ls(args):
1038 """list directory contents with current sync status
1039 dropbox ls [FILE]...
1040
1041 This is an alias for filestatus -l
1042 """
1043 return filestatus(["-l"] + args)
1044
1045 @command
1046 @requires_dropbox_running
1047 def puburl(args):
1048 """get public url of a file in your Dropbox's public folder
1049 dropbox puburl FILE
1050
1051 Prints out a public url for FILE (which must be in your public folder).
1052 """
1053 if len(args) != 1:
1054 console_print(puburl.__doc__,linebreak=False)
1055 return
1056
1057 try:
1058 with closing(DropboxCommand()) as dc:
1059 try:
1060 console_print(dc.get_public_link(path=os.path.abspath(args[0])).get('link', ['No Link'])[0])
1061 except DropboxCommand.CommandError as e:
1062 console_print("Couldn't get public url: " + str(e))
1063 except DropboxCommand.BadConnectionError:
1064 console_print("Dropbox isn't responding!")
1065 except DropboxCommand.EOFError:
1066 console_print("Dropbox daemon stopped.")
1067 except DropboxCommand.CouldntConnectError:
1068 console_print("Dropbox isn't running!")
1069
1070 @command
1071 @requires_dropbox_running
1072 def sharelink(args):
1073 """get a shared link for a file in your Dropbox
1074 dropbox sharelink FILE
1075
1076 Prints out a shared link for FILE.
1077 """
1078 if len(args) != 1:
1079 console_print(sharelink.__doc__, linebreak=False)
1080 return
1081
1082 try:
1083 with closing(DropboxCommand()) as dc:
1084 try:
1085 path = os.path.abspath(args[0])
1086 link = dc.get_shared_link(path=path).get('link', ['No link'])[0]
1087 console_print(link)
1088 except DropboxCommand.CommandError as e:
1089 console_print("Couldn't get shared link: " + str(e))
1090 except DropboxCommand.BadConnectionError:
1091 console_print("Dropbox isn't responding!")
1092 except DropboxCommand.EOFError:
1093 console_print("Dropbox daemon stopped.")
1094 except DropboxCommand.CouldntConnectError:
1095 console_print("Dropbox isn't running!")
1096
1097 @command
1098 @requires_dropbox_running
1099 def proxy(args):
1100 """set proxy settings for Dropbox
1101 dropbox proxy MODE [TYPE] [HOST] [PORT] [USERNAME] [PASSWORD]
1102
1103 Set proxy settings for Dropbox.
1104
1105 MODE - one of "none", "auto", "manual"
1106 TYPE - one of "http", "socks4", "socks5" (only valid with "manual" mode)
1107 HOST - proxy hostname (only valid with "manual" mode)
1108 PORT - proxy port (only valid with "manual" mode)
1109 USERNAME - (optional) proxy username (only valid with "manual" mode)
1110 PASSWORD - (optional) proxy password (only valid with "manual" mode)
1111 """
1112 mode = None
1113 type_ = None
1114 if len(args) >= 1:
1115 mode = args[0].lower()
1116 if len(args) >= 2:
1117 type_ = args[1].lower()
1118
1119 if (len(args) == 0 or
1120 mode not in ['none', 'auto', 'manual'] or
1121 (mode == 'manual' and len(args) not in (4, 6)) or
1122 (mode != 'manual' and len(args) != 1) or
1123 (mode == 'manual' and type_ not in ['http', 'socks4', 'socks5'])):
1124 # Print help
1125 console_print(proxy.__doc__, linebreak=False)
1126 return
1127
1128 ARGS = ['mode', 'type', 'host', 'port', 'username', 'password']
1129
1130 # Load the args into a dictionary
1131 kwargs = dict(zip(ARGS, args))
1132
1133 # Re-set these two because they were coerced to lower case
1134 kwargs['mode'] = mode
1135 if type_:
1136 kwargs['type'] = type_
1137
1138 try:
1139 with closing(DropboxCommand()) as dc:
1140 try:
1141 dc.set_proxy_settings(**kwargs)
1142 console_print('set')
1143 except DropboxCommand.CommandError as e:
1144 console_print("Couldn't set proxy: " + str(e))
1145 except DropboxCommand.BadConnectionError:
1146 console_print("Dropbox isn't responding!")
1147 except DropboxCommand.EOFError:
1148 console_print("Dropbox daemon stopped.")
1149 except DropboxCommand.CouldntConnectError:
1150 console_print("Dropbox isn't running!")
1151
1152 @command
1153 @requires_dropbox_running
1154 def throttle(args):
1155 """set bandwidth limits for Dropbox
1156 dropbox throttle DOWNLOAD UPLOAD
1157
1158 Set bandwidth limits for file sync.
1159
1160 DOWNLOAD - either "unlimited" or a manual limit in KB/s
1161 UPLOAD - one of "unlimited", "auto", or a manual limit in KB/s
1162 """
1163 if len(args) != 2:
1164 console_print(throttle.__doc__, linebreak=False)
1165 return
1166
1167 downlimit = args[0].lower()
1168 uplimit = args[1].lower()
1169
1170 download_limit = None
1171 download_mode = None
1172 if downlimit == 'unlimited':
1173 download_mode = downlimit
1174 else:
1175 try:
1176 download_limit = int(downlimit)
1177 download_mode = 'manual'
1178 except ValueError:
1179 console_print(throttle.__doc__, linebreak=False)
1180 return
1181
1182 upload_limit = None
1183 upload_mode = None
1184 if uplimit in ['unlimited', 'auto']:
1185 upload_mode = uplimit
1186 else:
1187 try:
1188 upload_limit = int(uplimit)
1189 upload_mode = 'manual'
1190 except ValueError:
1191 console_print(throttle.__doc__, linebreak=False)
1192 return
1193
1194 kwargs = {
1195 'download_mode': download_mode,
1196 'upload_mode': upload_mode,
1197 }
1198 if download_limit:
1199 kwargs['download_limit'] = str(download_limit)
1200 if upload_limit:
1201 kwargs['upload_limit'] = str(upload_limit)
1202
1203 try:
1204 with closing(DropboxCommand()) as dc:
1205 try:
1206 dc.set_bandwidth_limits(**kwargs)
1207 console_print('set')
1208 except DropboxCommand.CommandError as e:
1209 console_print("Couldn't set bandwidth limits: " + str(e))
1210 except DropboxCommand.BadConnectionError:
1211 console_print("Dropbox isn't responding!")
1212 except DropboxCommand.EOFError:
1213 console_print("Dropbox daemon stopped.")
1214 except DropboxCommand.CouldntConnectError:
1215 console_print("Dropbox isn't running!")
1216
1217 @command
1218 @requires_dropbox_running
1219 def status(args):
1220 """get current status of the dropboxd
1221 dropbox status
1222
1223 Prints out the current status of the Dropbox daemon.
1224 """
1225 if len(args) != 0:
1226 console_print(status.__doc__,linebreak=False)
1227 return
1228
1229 try:
1230 with closing(DropboxCommand()) as dc:
1231 try:
1232 lines = dc.get_dropbox_status()['status']
1233 if len(lines) == 0:
1234 console_print('Idle')
1235 else:
1236 for line in lines:
1237 console_print(line)
1238 grab_link_url_if_necessary()
1239 except KeyError:
1240 console_print("Couldn't get status: daemon isn't responding")
1241 except DropboxCommand.CommandError as e:
1242 console_print("Couldn't get status: " + str(e))
1243 except DropboxCommand.BadConnectionError:
1244 console_print("Dropbox isn't responding!")
1245 except DropboxCommand.EOFError:
1246 console_print("Dropbox daemon stopped.")
1247 except DropboxCommand.CouldntConnectError:
1248 console_print("Dropbox isn't running!")
1249
1250 @command
1251 def running(argv):
1252 """return whether Dropbox is running
1253 dropbox running
1254
1255 Returns 1 if running, and 0 if not running.
1256 """
1257 return int(is_dropbox_running())
1258
1259 @command
1260 @requires_dropbox_running
1261 def stop(args):
1262 """stop dropboxd
1263 dropbox stop
1264
1265 Stops the Dropbox daemon.
1266 """
1267 try:
1268 with closing(DropboxCommand()) as dc:
1269 try:
1270 dc.tray_action_hard_exit()
1271 except DropboxCommand.BadConnectionError:
1272 console_print("Dropbox isn't responding!")
1273 except DropboxCommand.EOFError:
1274 console_print("Dropbox daemon stopped.")
1275 except DropboxCommand.CouldntConnectError:
1276 console_print("Dropbox isn't running!")
1277
1278 #returns true if link is necessary
1279 def grab_link_url_if_necessary():
1280 try:
1281 with closing(DropboxCommand()) as dc:
1282 try:
1283 link_url = dc.needs_link().get("link_url", None)
1284 if link_url is not None:
1285 console_print("To link this computer to a Dropbox account, visit the following url:\n%s" % link_url[0])
1286 return True
1287 else:
1288 return False
1289 except DropboxCommand.CommandError:
1290 pass
1291 except DropboxCommand.BadConnectionError:
1292 console_print("Dropbox isn't responding!")
1293 except DropboxCommand.EOFError:
1294 console_print("Dropbox daemon stopped.")
1295 except DropboxCommand.CouldntConnectError:
1296 console_print("Dropbox isn't running!")
1297
1298 @command
1299 @requires_dropbox_running
1300 def lansync(argv):
1301 """enables or disables LAN sync
1302 dropbox lansync [y/n]
1303
1304 options:
1305 y Dropbox will use LAN sync (default)
1306 n Dropbox will not use LAN sync
1307 """
1308 if len(argv) != 1:
1309 console_print(lansync.__doc__, linebreak=False)
1310 return
1311
1312 s = argv[0].lower()
1313 if s.startswith('y') or s.startswith('-y'):
1314 should_lansync = True
1315 elif s.startswith('n') or s.startswith('-n'):
1316 should_lansync = False
1317 else:
1318 should_lansync = None
1319
1320 if should_lansync is None:
1321 console_print(lansync.__doc__,linebreak=False)
1322 else:
1323 with closing(DropboxCommand()) as dc:
1324 dc.set_lan_sync(lansync='enabled' if should_lansync else 'disabled')
1325
1326
1327 @command
1328 @requires_dropbox_running
1329 def exclude(args):
1330 """ignores/excludes a directory from syncing
1331 dropbox exclude [list]
1332 dropbox exclude add [DIRECTORY] [DIRECTORY] ...
1333 dropbox exclude remove [DIRECTORY] [DIRECTORY] ...
1334
1335 "list" prints a list of directories currently excluded from syncing.
1336 "add" adds one or more directories to the exclusion list, then
1337 resynchronizes Dropbox.
1338 "remove" removes one or more directories from the exclusion list, then
1339 resynchronizes Dropbox.
1340
1341 With no arguments, executes "list".
1342
1343 Any specified path must be within Dropbox.
1344 """
1345 if len(args) == 0:
1346 try:
1347 with closing(DropboxCommand()) as dc:
1348 try:
1349 lines = [relpath(path) for path in dc.get_ignore_set()['ignore_set']]
1350 lines.sort()
1351 if len(lines) == 0:
1352 console_print('No directories are being ignored.')
1353 else:
1354 console_print('Excluded: ')
1355 for line in lines:
1356 console_print(str(line))
1357 except KeyError:
1358 console_print("Couldn't get ignore set: daemon isn't responding")
1359 except DropboxCommand.CommandError as e:
1360 if e.args[0].startswith("No command exists by that name"):
1361 console_print("This version of the client does not support this command.")
1362 else:
1363 console_print("Couldn't get ignore set: " + str(e))
1364 except DropboxCommand.BadConnectionError:
1365 console_print("Dropbox isn't responding!")
1366 except DropboxCommand.EOFError:
1367 console_print("Dropbox daemon stopped.")
1368 except DropboxCommand.CouldntConnectError:
1369 console_print("Dropbox isn't running!")
1370 elif len(args) == 1 and args[0] == "list":
1371 exclude([])
1372 elif len(args) >= 2:
1373 sub_command = args[0]
1374 paths = args[1:]
1375 absolute_paths = [os.path.abspath(path) for path in paths]
1376 if sub_command == "add":
1377 try:
1378 with closing(DropboxCommand(timeout=None)) as dc:
1379 try:
1380 result = dc.ignore_set_add(paths=absolute_paths)
1381 if result["ignored"]:
1382 console_print("Excluded: ")
1383 lines = [relpath(path) for path in result["ignored"]]
1384 for line in lines:
1385 console_print(str(line))
1386 except KeyError:
1387 console_print("Couldn't add ignore path: daemon isn't responding")
1388 except DropboxCommand.CommandError as e:
1389 if e.args[0].startswith("No command exists by that name"):
1390 console_print("This version of the client does not support this command.")
1391 else:
1392 console_print("Couldn't get ignore set: " + str(e))
1393 except DropboxCommand.BadConnectionError as e:
1394 console_print("Dropbox isn't responding! [%s]" % e)
1395 except DropboxCommand.EOFError:
1396 console_print("Dropbox daemon stopped.")
1397 except DropboxCommand.CouldntConnectError:
1398 console_print("Dropbox isn't running!")
1399 elif sub_command == "remove":
1400 try:
1401 with closing(DropboxCommand(timeout=None)) as dc:
1402 try:
1403 result = dc.ignore_set_remove(paths=absolute_paths)
1404 if result["removed"]:
1405 console_print("No longer excluded: ")
1406 lines = [relpath(path) for path in result["removed"]]
1407 for line in lines:
1408 console_print(str(line))
1409 except KeyError:
1410 console_print("Couldn't remove ignore path: daemon isn't responding")
1411 except DropboxCommand.CommandError as e:
1412 if e.args[0].startswith("No command exists by that name"):
1413 console_print("This version of the client does not support this command.")
1414 else:
1415 console_print("Couldn't get ignore set: " + str(e))
1416 except DropboxCommand.BadConnectionError as e:
1417 console_print("Dropbox isn't responding! [%s]" % e)
1418 except DropboxCommand.EOFError:
1419 console_print("Dropbox daemon stopped.")
1420 except DropboxCommand.CouldntConnectError:
1421 console_print("Dropbox isn't running!")
1422 else:
1423 console_print(exclude.__doc__, linebreak=False)
1424 return
1425 else:
1426 console_print(exclude.__doc__, linebreak=False)
1427 return
1428
1429 @command
1430 def start(argv):
1431 """start dropboxd
1432 dropbox start [-i]
1433
1434 Starts the Dropbox daemon, dropboxd. If dropboxd is already running,
1435 this will do nothing.
1436
1437 options:
1438 -i --install auto install dropboxd if not available on the system
1439 """
1440
1441 should_install = "-i" in argv or "--install" in argv
1442
1443 # first check if dropbox is already running
1444 if is_dropbox_running():
1445 if not grab_link_url_if_necessary():
1446 console_print("Dropbox is already running!")
1447 return
1448
1449 console_print("Starting Dropbox...", linebreak=False)
1450 console_flush()
1451 if not start_dropbox():
1452 if not should_install:
1453 console_print()
1454 console_print("The Dropbox daemon is not installed!")
1455 console_print("Run \"dropbox start -i\" to install the daemon")
1456 return
1457
1458 # install dropbox!!!
1459 try:
1460 download()
1461 except:
1462 traceback.print_exc()
1463 else:
1464 if GUI_AVAILABLE:
1465 start_dropbox()
1466 console_print("Done!")
1467 else:
1468 if start_dropbox():
1469 if not grab_link_url_if_necessary():
1470 console_print("Done!")
1471 else:
1472 if not grab_link_url_if_necessary():
1473 console_print("Done!")
1474
1475
1476 def can_reroll_autostart():
1477 return ".config" in os.listdir(os.path.expanduser('~'))
1478
1479 def reroll_autostart(should_autostart):
1480 home_dir = os.path.expanduser('~')
1481 contents = os.listdir(home_dir)
1482
1483 # UBUNTU
1484 if ".config" in contents:
1485 autostart_dir = os.path.join(home_dir, ".config", "autostart")
1486 autostart_link = os.path.join(autostart_dir, "dropbox.desktop")
1487 if should_autostart:
1488 if os.path.exists(DESKTOP_FILE):
1489 if not os.path.exists(autostart_dir):
1490 os.makedirs(autostart_dir)
1491 shutil.copyfile(DESKTOP_FILE, autostart_link)
1492 elif os.path.exists(autostart_link):
1493 os.remove(autostart_link)
1494
1495
1496
1497 @command
1498 def autostart(argv):
1499 """automatically start Dropbox at login
1500 dropbox autostart [y/n]
1501
1502 options:
1503 n Dropbox will not start automatically at login
1504 y Dropbox will start automatically at login (default)
1505
1506 Note: May only work on current Ubuntu distributions.
1507 """
1508 if len(argv) != 1:
1509 console_print(''.join(autostart.__doc__.split('\n', 1)[1:]))
1510 return
1511
1512 s = argv[0].lower()
1513 if s.startswith('y') or s.startswith('-y'):
1514 should_autostart = True
1515 elif s.startswith('n') or s.startswith('-n'):
1516 should_autostart = False
1517 else:
1518 should_autostart = None
1519
1520 if should_autostart is None:
1521 console_print(autostart.__doc__,linebreak=False)
1522 else:
1523 reroll_autostart(should_autostart)
1524
1525 @command
1526 def version(argv):
1527 """print version information for Dropbox
1528 dropbox version
1529
1530 Prints the version information for the Dropbox proprietary daemon, if
1531 it's installed, and the Dropbox command-line interface.
1532 """
1533 dropbox_daemon_version = "Not installed"
1534 try:
1535 with open(os.path.join(DROPBOX_DIST_PATH, 'VERSION')) as f:
1536 dropbox_daemon_version = f.read().strip()
1537 except OSError:
1538 pass
1539
1540 console_print("Dropbox daemon version: %s" % dropbox_daemon_version)
1541 console_print("Dropbox command-line interface version: @PACKAGE_VERSION@")
1542
1543 @command
1544 def help(argv):
1545 """provide help
1546 dropbox help [COMMAND]
1547
1548 With no arguments, print a list of commands and a short description of
1549 each. With a command, print descriptive help on how to use the
1550 command.
1551 """
1552 if not argv:
1553 return usage()
1554 for command in commands:
1555 if command == argv[0]:
1556 console_print(commands[command].__doc__.split('\n', 1)[1].strip())
1557 return
1558 for alias in aliases:
1559 if alias == argv[0]:
1560 console_print(aliases[alias].__doc__.split('\n', 1)[1].strip())
1561 return
1562 console_print("unknown command '%s'" % argv[0], f=sys.stderr)
1563
1564 def usage():
1565 console_print("Dropbox command-line interface\n")
1566 console_print("commands:\n")
1567 console_print("Note: use dropbox help <command> to view usage for a specific command.\n")
1568 out = []
1569 for command in commands:
1570 out.append((command, commands[command].__doc__.splitlines()[0]))
1571 out.sort(key=lambda x: x[0])
1572 spacing = max(len(o[0])+3 for o in out)
1573 for o in out:
1574 console_print(" %-*s%s" % (spacing, o[0], o[1]))
1575
1576 def main(argv):
1577 global commands
1578
1579 # now we need to find out if one of the commands are in the
1580 # argv list, and if so split the list at the point to
1581 # separate the argv list at that point
1582 cut = None
1583 for i in range(len(argv)):
1584 if argv[i] in commands or argv[i] in aliases:
1585 cut = i
1586 break
1587
1588 if cut == None:
1589 usage()
1590 os._exit(0)
1591 return
1592
1593 # option parsing code
1594 def set_http_proxy(option, opt_str, value, parser):
1595 os.environ["http_proxy"] = value
1596 # Need to reset _urlopener to take the new value into account
1597 urllib._urlopener = DropboxURLopener()
1598
1599 def set_https_proxy(option, opt_str, value, parser):
1600 os.environ["https_proxy"] = value
1601 # Need to reset _urlopener to take the new value into account
1602 urllib._urlopener = DropboxURLopener()
1603
1604 globaloptionparser = optparse.OptionParser()
1605 globaloptionparser.add_option("--http-proxy", action="callback",
1606 type="string", callback=set_http_proxy)
1607 globaloptionparser.add_option("--https-proxy", action="callback",
1608 type="string", callback=set_https_proxy)
1609 globaloptionparser.parse_args(argv[0:i])
1610
1611 # now dispatch and run
1612 result = None
1613 if argv[i] in commands:
1614 result = commands[argv[i]](argv[i+1:])
1615 elif argv[i] in aliases:
1616 result = aliases[argv[i]](argv[i+1:])
1617
1618 # flush, in case output is rerouted to a file.
1619 console_flush()
1620
1621 # done
1622 return result
1623
1624 if __name__ == "__main__":
1625 ret = main(sys.argv)
1626 if ret is not None:
1627 sys.exit(ret)