~ubuntu-branches/ubuntu/saucy/nautilus-dropbox/saucy

« back to all changes in this revision

Viewing changes to .pc/dropbox-update.patch/dropbox.in

  • Committer: Package Import Robot
  • Author(s): Raphaël Hertzog
  • Date: 2011-10-29 16:28:59 UTC
  • mfrom: (1.1.3)
  • Revision ID: package-import@ubuntu.com-20111029162859-tk6xyv31rbfxlwt1
Tags: 0.7.0-2
Fix the distribution in the changelog entry for version 0.7.0-1
(UNRELEASED → unstable).

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
#
22
22
from __future__ import with_statement
23
23
 
24
 
import sys
 
24
import errno
 
25
import fcntl
 
26
import locale
25
27
import optparse
26
 
import socket
27
28
import os
 
29
import platform
28
30
import shutil
29
 
import time
30
 
import platform
 
31
import socket
 
32
import StringIO
 
33
import subprocess
 
34
import sys
31
35
import tarfile
 
36
import tempfile
32
37
import threading
 
38
import time
33
39
import urllib
34
 
import subprocess
35
 
import fcntl
36
 
import errno
37
 
import locale
38
 
from contextlib import closing
 
40
 
 
41
try:
 
42
    import gpgme
 
43
except ImportError:
 
44
    gpgme = None
 
45
 
 
46
from contextlib import closing, contextmanager
39
47
from posixpath import curdir, sep, pardir, join, abspath, commonprefix
40
48
 
41
49
INFO = u"Dropbox is the easiest way to share and store your files online. Want to learn more? Head to"
42
50
LINK = u"http://www.dropbox.com/"
43
51
WARNING = u"In order to use Dropbox, you must download the proprietary daemon."
 
52
GPG_WARNING = u"Note: python-gpgme is not installed, we will not be able to verify binary signatures."
44
53
 
45
54
DOWNLOADING = u"Downloading Dropbox... %d%%"
46
55
UNPACKING = u"Unpacking Dropbox... %d%%"
47
56
 
48
 
PARENT_DIR = os.path.expanduser("~")
 
57
PARENT_DIR = os.path.expanduser("/var/lib/dropbox")
49
58
DROPBOXD_PATH = "%s/.dropbox-dist/dropboxd" % PARENT_DIR
50
59
 
51
60
enc = locale.getpreferredencoding()
52
61
 
 
62
# Available from http://linux.dropbox.com/fedora/rpm-public-key.asc
 
63
DROPBOX_PUBLIC_KEY = """
 
64
-----BEGIN PGP PUBLIC KEY BLOCK-----
 
65
Version: SKS 1.1.0
 
66
 
 
67
mQENBEt0ibEBCACv4hZRPqwtpU6z8+BB5YZU1a3yjEvg2W68+a6hEwxtCa2U++4dzQ+7EqaU
 
68
q5ybQnwtbDdpFpsOi9x31J+PCpufPUfIG694/0rlEpmzl2GWzY8NqfdBFGGm/SPSSwvKbeNc
 
69
FMRLu5neo7W9kwvfMbGjHmvUbzBUVpCVKD0OEEf1q/Ii0Qcekx9CMoLvWq7ZwNHEbNnij7ec
 
70
nvwNlE2MxNsOSJj+hwZGK+tM19kuYGSKw4b5mR8IyThlgiSLIfpSBh1n2KX+TDdk9GR+57TY
 
71
vlRu6nTPu98P05IlrrCP+KF0hYZYOaMvQs9Rmc09tc/eoQlN0kkaBWw9Rv/dvLVc0aUXABEB
 
72
AAG0MURyb3Bib3ggQXV0b21hdGljIFNpZ25pbmcgS2V5IDxsaW51eEBkcm9wYm94LmNvbT6J
 
73
ATYEEwECACAFAkt0ibECGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRD8kYszUESRLi/z
 
74
B/wMscEa15rS+0mIpsORknD7kawKwyda+LHdtZc0hD/73QGFINR2P23UTol/R4nyAFEuYNsF
 
75
0C4IAD6y4pL49eZ72IktPrr4H27Q9eXhNZfJhD7BvQMBx75L0F5gSQwuC7GdYNlwSlCD0AAh
 
76
Qbi70VBwzeIgITBkMQcJIhLvllYo/AKD7Gv9huy4RLaIoSeofp+2Q0zUHNPl/7zymOqu+5Ox
 
77
e1ltuJT/kd/8hU+N5WNxJTSaOK0sF1/wWFM6rWd6XQUP03VyNosAevX5tBo++iD1WY2/lFVU
 
78
JkvAvge2WFk3c6tAwZT/tKxspFy4M/tNbDKeyvr685XKJw9ei6GcOGHD
 
79
=5rWG
 
80
-----END PGP PUBLIC KEY BLOCK-----
 
81
"""
 
82
 
53
83
# Futures
54
84
 
55
85
def methodcaller(name, *args, **kwargs):
105
135
            return False
106
136
        else:
107
137
            console_print(u"Sorry, I didn't understand that. Please type yes or no.")
108
 
    
 
138
 
109
139
def plat():
110
140
    if sys.platform.lower().startswith('linux'):
111
141
        arch = platform.machine()
137
167
def unicode_abspath(path):
138
168
    global enc
139
169
    assert type(path) is unicode
140
 
    # shouldn't pass unicode to this craphead, it appends with os.getcwd() which is always a str 
 
170
    # shouldn't pass unicode to this craphead, it appends with os.getcwd() which is always a str
141
171
    return os.path.abspath(path.encode(sys.getfilesystemencoding())).decode(sys.getfilesystemencoding())
142
172
 
 
173
@contextmanager
 
174
def gpgme_context(keys):
 
175
    gpg_conf_contents = ''
 
176
    _gpghome = tempfile.mkdtemp(prefix='tmp.gpghome')
 
177
 
 
178
    try:
 
179
        os.environ['GNUPGHOME'] = _gpghome
 
180
        fp = open(os.path.join(_gpghome, 'gpg.conf'), 'wb')
 
181
        fp.write(gpg_conf_contents)
 
182
        fp.close()
 
183
        ctx = gpgme.Context()
 
184
 
 
185
        loaded = []
 
186
        for key_file in keys:
 
187
            result = ctx.import_(key_file)
 
188
            key = ctx.get_key(result.imports[0][0])
 
189
            loaded.append(key)
 
190
 
 
191
        ctx.signers = loaded
 
192
 
 
193
        yield ctx
 
194
    finally:
 
195
        del os.environ['GNUPGHOME']
 
196
        shutil.rmtree(_gpghome, ignore_errors=True)
 
197
 
 
198
def verify_signature(key_file, sig_file, plain_file):
 
199
    with gpgme_context([key_file]) as ctx:
 
200
        sigs = ctx.verify(sig_file, plain_file, None)
 
201
        return sigs[0].status == None
 
202
 
 
203
def download_file_chunk(socket, buf, size):
 
204
    progress = 0
 
205
    with closing(socket) as f:
 
206
        while True:
 
207
            try:
 
208
                chunk = os.read(f.fileno(), 4096)
 
209
                progress += len(chunk)
 
210
                buf.write(chunk)
 
211
                yield (progress, True)
 
212
                if progress == size:
 
213
                    break
 
214
            except OSError, e:
 
215
                if hasattr(e, 'errno') and e.errno == errno.EAGAIN:
 
216
                    # nothing left to read
 
217
                    yield (progress, False)
 
218
                else:
 
219
                    raise
 
220
 
 
221
def download_uri_to_buffer(uri):
 
222
    try:
 
223
        socket = urllib.urlopen(uri)
 
224
    except IOError:
 
225
        FatalVisibleError("Trouble connecting to Dropbox servers. Maybe your internet connection is down, or you need to set your http_proxy environment variable.")
 
226
 
 
227
    fcntl.fcntl(socket, fcntl.F_SETFL, os.O_NONBLOCK)
 
228
    size = int(socket.info()['content-length'])
 
229
 
 
230
    buf = StringIO.StringIO()
 
231
    download_chunk = download_file_chunk(socket, buf, size)
 
232
 
 
233
    for _ in download_chunk:
 
234
        pass
 
235
 
 
236
    buf.seek(0)
 
237
    return buf
 
238
 
143
239
# This sets a custom User-Agent
144
240
class DropboxURLopener(urllib.FancyURLopener):
145
241
    version = "DropboxLinuxDownloader/@PACKAGE_VERSION@"
148
244
class DownloadState(object):
149
245
    def __init__(self):
150
246
        try:
151
 
            self.file = urllib.urlopen("http://www.dropbox.com/download?plat=%s" % plat())
 
247
            self.socket = urllib.urlopen("http://www.dropbox.com/download?plat=%s" % plat())
152
248
        except IOError:
153
 
            FatalVisibleError("Trouble connecting to Dropbox servers. Maybe your internet connection is down, or you need to set your http_proxy environment variable.")
154
 
            
155
 
        fcntl.fcntl(self.file, fcntl.F_SETFL, os.O_NONBLOCK)
156
 
        
157
 
        self.size = int(self.file.info()['content-length'])
158
 
        self.progress = 0
159
 
 
160
 
        self.local_path = "%s/dropbox.tar.gz" % PARENT_DIR
161
 
        self.local_file = open(self.local_path, 'wb')
 
249
            FatalVisibleError("Trouble connecting to Dropbox servers. Maybe your internet connection is down, or you need to set your http_proxy environment variable")
 
250
 
 
251
        fcntl.fcntl(self.socket, fcntl.F_SETFL, os.O_NONBLOCK)
 
252
        self.size = int(self.socket.info()['content-length'])
 
253
 
 
254
        self.local_file = StringIO.StringIO()
 
255
        self.download_chunk = download_file_chunk(self.socket, self.local_file, self.size)
162
256
 
163
257
    def copy_data(self):
164
 
        while True:
165
 
            try:
166
 
                chunk = os.read(self.file.fileno(), 4096)
167
 
                self.progress += len(chunk)
168
 
                self.local_file.write(chunk)
169
 
                yield True
170
 
                if self.progress == self.size:
171
 
                    break
172
 
            except OSError, e:
173
 
                if hasattr(e, 'errno') and e.errno == errno.EAGAIN:
174
 
                    # nothing left to read
175
 
                    yield False
176
 
                else:
177
 
                    raise
178
 
 
179
 
        self.file.close()
 
258
        return self.download_chunk
180
259
 
181
260
    def unpack(self):
182
 
        self.local_file.close()
183
 
        archive = tarfile.open(self.local_path, 'r:gz')
 
261
        # download signature
 
262
        signature = download_uri_to_buffer("http://www.dropbox.com/download?plat=%s&signature=1" % plat())
 
263
 
 
264
        self.local_file.seek(0)
 
265
        if gpgme:
 
266
            if not verify_signature(StringIO.StringIO(DROPBOX_PUBLIC_KEY), signature, self.local_file):
 
267
                FatalVisibleError("Downloaded binary does not match Dropbox signature, aborting install.")
 
268
 
 
269
        self.local_file.seek(0)
 
270
        archive = tarfile.open(fileobj=self.local_file, mode='r:gz')
184
271
        total_members = len(archive.getmembers())
185
272
        for i, member in enumerate(archive.getmembers()):
 
273
            filename = os.path.join(PARENT_DIR, member.name)
 
274
            if os.path.exists(filename) and not os.path.isdir(filename):
 
275
                os.unlink(filename)
186
276
            archive.extract(member, PARENT_DIR)
187
277
            yield member.name, i, total_members
188
278
        archive.close()
189
 
        os.remove(self.local_path)
190
279
 
191
280
    def cancel(self):
192
281
        if not self.local_file.closed:
193
282
            self.local_file.close()
194
 
        if os.path.exists(self.local_path):
195
 
            os.remove(self.local_path)
196
283
 
197
284
def load_serialized_images():
198
285
    global box_logo_pixbuf, window_icon
249
336
                self.ok.hide()
250
337
                self.download = DownloadState()
251
338
                self.one_chunk = self.download.copy_data()
252
 
                self.watch = gobject.io_add_watch(self.download.file,
253
 
                                                  gobject.IO_IN | 
 
339
                self.watch = gobject.io_add_watch(self.download.socket,
 
340
                                                  gobject.IO_IN |
254
341
                                                  gobject.IO_PRI |
255
342
                                                  gobject.IO_ERR |
256
343
                                                  gobject.IO_HUP,
270
357
                elif condition == gobject.IO_ERR:
271
358
                    FatalVisibleError("Unexpected error occurred with download.")
272
359
                try:
273
 
                    while self.one_chunk.next():
274
 
                        self.update_progress(DOWNLOADING, float(self.download.progress)/self.download.size)
 
360
                    while True:
 
361
                        progress, status = self.one_chunk.next()
 
362
                        if not status:
 
363
                            break
 
364
                        self.update_progress(DOWNLOADING, float(progress)/self.download.size)
275
365
                except StopIteration:
276
366
                    self.update_progress(DOWNLOADING, 1.0)
277
367
                    self.unpack_dropbox()
278
368
                    return False
279
369
                else:
280
 
                    self.update_progress(DOWNLOADING, float(self.download.progress)/self.download.size)
 
370
                    self.update_progress(DOWNLOADING, float(progress)/self.download.size)
281
371
                    return True
282
372
 
283
373
            def unpack_dropbox(self):
344
434
                self.progress.set_property('width-request', 300)
345
435
 
346
436
                self.label = gtk.Label()
347
 
                self.label.set_markup('%s <span foreground="#000099" underline="single" weight="bold">%s</span>\n\n%s' % (INFO, LINK, WARNING))
 
437
                GPG_WARNING_MSG = (u"\n\n" + GPG_WARNING) if not gpgme else u""
 
438
                self.label.set_markup('%s <span foreground="#000099" underline="single" weight="bold">%s</span>\n\n%s%s' % (INFO, LINK, WARNING, GPG_WARNING_MSG))
348
439
                self.label.set_line_wrap(True)
349
440
                self.label.set_property('width-request', 300)
350
441
                self.label.show()
431
522
            write(save)
432
523
            flush()
433
524
        console_print(u"%s %s\n" % (INFO, LINK))
 
525
        GPG_WARNING_MSG = (u"\n%s" % GPG_WARNING) if not gpgme else u""
434
526
 
435
 
        if not yes_no_question(WARNING):
 
527
        if not yes_no_question("%s%s" % (WARNING, GPG_WARNING_MSG)):
436
528
            return
437
529
 
438
530
        download = DownloadState()
439
531
        one_chunk = download.copy_data()
440
532
 
441
 
        try:    
 
533
        try:
442
534
            while True:
443
 
                one_chunk.next()
444
 
                setprogress(DOWNLOADING, float(download.progress)/download.size)
 
535
                progress = one_chunk.next()[0]
 
536
                setprogress(DOWNLOADING, float(progress)/download.size)
445
537
        except StopIteration:
446
538
            setprogress(DOWNLOADING, 1.0)
447
539
            console_print()
481
573
                sys.stderr.flush()
482
574
            i += 1
483
575
        sys.stderr.flush()
484
 
                
 
576
 
485
577
 
486
578
class DropboxCommand(object):
487
579
    class CouldntConnectError(Exception): pass
521
613
                                             [v])) + u"\n").encode('utf8')
522
614
                          for k,v in args.iteritems())
523
615
        self.f.write(u"done\n".encode('utf8'))
524
 
                
 
616
 
525
617
        self.f.flush()
526
618
 
527
619
        # Start a ticker
528
620
        ticker_thread = CommandTicker()
529
621
        ticker_thread.start()
530
622
 
531
 
        # This is the potentially long-running call. 
 
623
        # This is the potentially long-running call.
532
624
        try:
533
625
            ok = self.__readline() == u"ok"
534
626
        except KeyboardInterrupt:
535
627
            raise DropboxCommand.BadConnectionError("Keyboard interruption detected")
536
 
        finally:    
537
 
            # Tell the ticker to stop. 
 
628
        finally:
 
629
            # Tell the ticker to stop.
538
630
            ticker_thread.stop()
539
631
            ticker_thread.join()
540
 
        
 
632
 
541
633
        if ok:
542
634
            toret = {}
543
635
            for i in range(21):
547
639
                line = self.__readline()
548
640
                if line == u"done":
549
641
                    break
550
 
                        
 
642
 
551
643
                argval = line.split(u"\t")
552
644
                toret[argval[0]] = argval[1:]
553
645
 
561
653
                line = self.__readline()
562
654
                if line == u"done":
563
655
                    break
564
 
                        
 
656
 
565
657
                problems.append(line)
566
 
                    
 
658
 
567
659
            raise DropboxCommand.CommandError(u"\n".join(problems))
568
660
 
569
661
    # this is the hotness, auto marshalling
603
695
        if is_dropbox_running():
604
696
            return meth(*n, **kw)
605
697
        else:
606
 
            console_print(u"Dropbox isn't running!")            
 
698
            console_print(u"Dropbox isn't running!")
607
699
    newmeth.func_name = meth.func_name
608
700
    newmeth.__doc__ = meth.__doc__
609
701
    return newmeth
610
702
 
611
703
def start_dropbox():
612
 
    db_path = os.path.expanduser(u"~/.dropbox-dist/dropboxd").encode(sys.getfilesystemencoding())
 
704
    db_path = os.path.expanduser(DROPBOXD_PATH).encode(sys.getfilesystemencoding())
613
705
    if os.access(db_path, os.X_OK):
614
706
        f = open("/dev/null", "w")
615
707
        # we don't reap the child because we're gonna die anyway, let init do it
616
708
        a = subprocess.Popen([db_path], preexec_fn=os.setsid, cwd=os.path.expanduser("~"),
617
709
                             stderr=sys.stderr, stdout=f, close_fds=True)
618
 
        
 
710
 
619
711
        # in seconds
620
712
        interval = 0.5
621
713
        wait_for = 60
624
716
                return True
625
717
            # back off from connect for a while
626
718
            time.sleep(interval)
627
 
                
 
719
 
628
720
        return False
629
721
    else:
630
722
        return False
634
726
    if not list:
635
727
        console_print(u"<empty>")
636
728
        return
637
 
        
 
729
 
638
730
    non_unicode = [i for i in range(len(list)) if not (isinstance(list[i], unicode))]
639
731
    if non_unicode:
640
732
        raise TypeError, ("list[i] not a string for i in %s" %
648
740
            for item in list:
649
741
                console_print(item)
650
742
            return
651
 
        
 
743
 
652
744
    if not display_list:
653
745
        display_list = list
654
 
        
 
746
 
655
747
    size = len(list)
656
748
    if size == 1:
657
749
        console_print(display_list[0])
728
820
    try:
729
821
        with closing(DropboxCommand()) as dc:
730
822
            if options.list:
731
 
                # Listing. 
 
823
                # Listing.
732
824
 
733
 
                # Separate directories from files. 
 
825
                # Separate directories from files.
734
826
                if len(args) == 0:
735
827
                    dirs, nondirs = [u"."], []
736
828
                else:
743
835
                            continue
744
836
 
745
837
                    if len(dirs) == 0 and len(nondirs) == 0:
746
 
                        #TODO: why? 
 
838
                        #TODO: why?
747
839
                        exit(1)
748
840
 
749
841
                dirs.sort(key=methodcaller('lower'))
750
842
                nondirs.sort(key=methodcaller('lower'))
751
843
 
752
 
                # Gets a string representation for a path. 
 
844
                # Gets a string representation for a path.
753
845
                def path_to_string(file_path):
754
846
                    if not os.path.exists(file_path):
755
847
                        path = u"%s (File doesn't exist!)" % os.path.basename(file_path)
757
849
                    try:
758
850
                        status = dc.icon_overlay_file_status(path=file_path).get(u'status', [None])[0]
759
851
                    except DropboxCommand.CommandError, e:
760
 
                        path =  u"%s (%s)" % (os.path.basename(file_path), e) 
 
852
                        path =  u"%s (%s)" % (os.path.basename(file_path), e)
761
853
                        return (path, path)
762
854
 
763
855
                    env_term = os.environ.get('TERM','')
764
856
                    supports_color = (sys.stderr.isatty() and (
765
 
                                        env_term.startswith('vt') or 
766
 
                                        env_term.startswith('linux') or 
767
 
                                        'xterm' in env_term or 
 
857
                                        env_term.startswith('vt') or
 
858
                                        env_term.startswith('linux') or
 
859
                                        'xterm' in env_term or
768
860
                                        'color' in env_term
769
861
                                        )
770
862
                                     )
771
 
                    
772
 
                    # TODO: Test when you don't support color.    
 
863
 
 
864
                    # TODO: Test when you don't support color.
773
865
                    if not supports_color:
774
866
                        path = os.path.basename(file_path)
775
867
                        return (path, path)
788
880
                    path = os.path.basename(file_path)
789
881
                    return (path, u"%s%s%s" % (init, path, cleanup))
790
882
 
791
 
                # Prints a directory. 
 
883
                # Prints a directory.
792
884
                def print_directory(name):
793
885
                    clean_paths = []
794
886
                    formatted_paths = []
795
887
                    for subname in sorted(os.listdir(name), key=methodcaller('lower')):
796
888
                        if type(subname) != unicode:
797
889
                            continue
798
 
                        
 
890
 
799
891
                        if not options.all and subname[0] == u'.':
800
892
                            continue
801
893
 
805
897
                            formatted_paths.append(formatted)
806
898
                        except (UnicodeEncodeError, UnicodeDecodeError), e:
807
899
                            continue
808
 
                    
 
900
 
809
901
                    columnize(clean_paths, formatted_paths)
810
902
 
811
903
                try:
822
914
                            except (UnicodeEncodeError, UnicodeDecodeError), e:
823
915
                                continue
824
916
 
825
 
                        if nondir_clean_paths:        
 
917
                        if nondir_clean_paths:
826
918
                            columnize(nondir_clean_paths, nondir_formatted_paths)
827
 
                        
 
919
 
828
920
                        if len(nondirs) == 0:
829
921
                            console_print(dirs[0] + u":")
830
922
                            print_directory(dirs[0])
834
926
                            console_print()
835
927
                            console_print(name + u":")
836
928
                            print_directory(name)
837
 
                    
 
929
 
838
930
                except DropboxCommand.EOFError:
839
931
                    console_print(u"Dropbox daemon stopped.")
840
932
                except DropboxCommand.BadConnectionError, e:
855
947
                        console_print(u"%-*s %s" % \
856
948
                                          (indent, file+':', "File doesn't exist"))
857
949
                        continue
858
 
                        
 
950
 
859
951
                    try:
860
952
                        status = dc.icon_overlay_file_status(path=fp).get(u'status', [u'unknown'])[0]
861
953
                        console_print(u"%-*s %s" % (indent, file+':', status))
893
985
            except DropboxCommand.CommandError, e:
894
986
                console_print(u"Couldn't get public url: " + str(e))
895
987
            except DropboxCommand.BadConnectionError, e:
896
 
                console_print(u"Dropbox isn't responding!")        
 
988
                console_print(u"Dropbox isn't responding!")
897
989
            except DropboxCommand.EOFError:
898
990
                console_print(u"Dropbox daemon stopped.")
899
991
    except DropboxCommand.CouldntConnectError, e:
916
1008
            try:
917
1009
                lines = dc.get_dropbox_status()[u'status']
918
1010
                if len(lines) == 0:
919
 
                    console_print(u'Idle')                    
 
1011
                    console_print(u'Idle')
920
1012
                else:
921
1013
                    for line in lines:
922
1014
                        console_print(line)
953
1045
            try:
954
1046
                dc.tray_action_hard_exit()
955
1047
            except DropboxCommand.BadConnectionError, e:
956
 
                console_print(u"Dropbox isn't responding!")        
 
1048
                console_print(u"Dropbox isn't responding!")
957
1049
            except DropboxCommand.EOFError:
958
1050
                console_print(u"Dropbox daemon stopped.")
959
1051
    except DropboxCommand.CouldntConnectError, e:
973
1065
            except DropboxCommand.CommandError, e:
974
1066
                pass
975
1067
            except DropboxCommand.BadConnectionError, e:
976
 
                console_print(u"Dropbox isn't responding!")        
 
1068
                console_print(u"Dropbox isn't responding!")
977
1069
            except DropboxCommand.EOFError:
978
1070
                console_print(u"Dropbox daemon stopped.")
979
1071
    except DropboxCommand.CouldntConnectError, e:
981
1073
 
982
1074
@command
983
1075
@requires_dropbox_running
 
1076
def lansync(argv):
 
1077
    u"""enables or disables LAN sync
 
1078
dropbox lansync [y/n]
 
1079
 
 
1080
options:
 
1081
  y  dropbox will use LAN sync (default)
 
1082
  n  dropbox will not use LAN sync
 
1083
"""
 
1084
    if len(argv) != 1:
 
1085
        console_print(lansync.__doc__, linebreak=False)
 
1086
        return
 
1087
 
 
1088
    s = argv[0].lower()
 
1089
    if s.startswith('y') or s.startswith('-y'):
 
1090
        should_lansync = True
 
1091
    elif s.startswith('n') or s.startswith('-n'):
 
1092
        should_lansync = False
 
1093
    else:
 
1094
        should_lansync = None
 
1095
 
 
1096
    if should_lansync is None:
 
1097
        console_print(lansync.__doc__,linebreak=False)
 
1098
    else:
 
1099
        with closing(DropboxCommand()) as dc:
 
1100
            dc.set_lan_sync(lansync='enabled' if should_lansync else 'disabled')
 
1101
 
 
1102
 
 
1103
@command
 
1104
@requires_dropbox_running
984
1105
def exclude(args):
985
1106
    u"""ignores/excludes a directory from syncing
986
1107
dropbox exclude [list]
987
1108
dropbox exclude add [DIRECTORY] [DIRECTORY] ...
988
1109
dropbox exclude remove [DIRECTORY] [DIRECTORY] ...
989
1110
 
990
 
"list" prints a list of directories currently excluded from syncing.  
991
 
"add" adds one or more directories to the exclusion list, then resynchronizes Dropbox. 
 
1111
"list" prints a list of directories currently excluded from syncing.
 
1112
"add" adds one or more directories to the exclusion list, then resynchronizes Dropbox.
992
1113
"remove" removes one or more directories from the exclusion list, then resynchronizes Dropbox.
993
 
With no arguments, executes "list". 
 
1114
With no arguments, executes "list".
994
1115
Any specified path must be within Dropbox.
995
1116
"""
996
1117
    if len(args) == 0:
1000
1121
                    lines = [relpath(path) for path in dc.get_ignore_set()[u'ignore_set']]
1001
1122
                    lines.sort()
1002
1123
                    if len(lines) == 0:
1003
 
                        console_print(u'No directories are being ignored.') 
 
1124
                        console_print(u'No directories are being ignored.')
1004
1125
                    else:
1005
 
                        console_print(u'Excluded: ') 
 
1126
                        console_print(u'Excluded: ')
1006
1127
                        for line in lines:
1007
1128
                            console_print(unicode(line))
1008
1129
                except KeyError:
1024
1145
        sub_command = args[0]
1025
1146
        paths = args[1:]
1026
1147
        absolute_paths = [unicode_abspath(path.decode(sys.getfilesystemencoding())) for path in paths]
1027
 
        if sub_command == u"add": 
 
1148
        if sub_command == u"add":
1028
1149
            try:
1029
1150
                with closing(DropboxCommand(timeout=None)) as dc:
1030
 
                    try: 
 
1151
                    try:
1031
1152
                        result = dc.ignore_set_add(paths=absolute_paths)
1032
1153
                        if result[u"ignored"]:
1033
 
                            console_print(u"Excluded: ") 
 
1154
                            console_print(u"Excluded: ")
1034
1155
                            lines = [relpath(path) for path in result[u"ignored"]]
1035
1156
                            for line in lines:
1036
1157
                                console_print(unicode(line))
1053
1174
                    try:
1054
1175
                        result = dc.ignore_set_remove(paths=absolute_paths)
1055
1176
                        if result[u"removed"]:
1056
 
                            console_print(u"No longer excluded: ") 
 
1177
                            console_print(u"No longer excluded: ")
1057
1178
                            lines = [relpath(path) for path in result[u"removed"]]
1058
1179
                            for line in lines:
1059
1180
                                console_print(unicode(line))
1070
1191
                        console_print(u"Dropbox daemon stopped.")
1071
1192
            except DropboxCommand.CouldntConnectError, e:
1072
1193
                console_print(u"Dropbox isn't running!")
1073
 
        else: 
 
1194
        else:
1074
1195
            console_print(exclude.__doc__, linebreak=False)
1075
1196
            return
1076
1197
    else:
1081
1202
def start(argv):
1082
1203
    u"""start dropboxd
1083
1204
dropbox start [-i]
1084
 
    
 
1205
 
1085
1206
Starts the dropbox daemon, dropboxd. If dropboxd is already running, this will do nothing.
1086
1207
 
1087
1208
options:
1089
1210
"""
1090
1211
 
1091
1212
    should_install = "-i" in argv or "--install" in argv
1092
 
    
 
1213
 
1093
1214
    # first check if dropbox is already running
1094
1215
    if is_dropbox_running():
1095
1216
        if not grab_link_url_if_necessary():
1134
1255
    if u".config" in contents:
1135
1256
        autostart_dir = os.path.join(home_dir, u".config", u"autostart")
1136
1257
        autostart_link = os.path.join(autostart_dir, u"%s.desktop" % "dropbox") #BUILD_KEY.lower()
1137
 
        desktop_file = u"/usr/local/share/applications/%s.desktop" % "dropbox" #BUILD_KEY.lower()
 
1258
        desktop_file = u"@DESKTOP_FILE_DIR@/%s.desktop" % "dropbox" #BUILD_KEY.lower()
1138
1259
        if should_autostart:
1139
1260
            if os.path.exists(desktop_file):
1140
1261
                if not os.path.exists(autostart_dir):
1203
1324
    for o in out:
1204
1325
        console_print(" %-*s%s" % (spacing, o[0], o[1]))
1205
1326
    console_print()
1206
 
    
 
1327
 
1207
1328
def main(argv):
1208
1329
    global commands
1209
1330
 
1215
1336
        if argv[i] in commands or argv[i] in aliases:
1216
1337
            cut = i
1217
1338
            break
1218
 
    
 
1339
 
1219
1340
    if cut == None:
1220
1341
        usage(argv)
1221
1342
        os._exit(0)
1232
1353
    elif argv[i] in aliases:
1233
1354
        result = aliases[argv[i]](argv[i+1:])
1234
1355
 
1235
 
    # flush, in case output is rerouted to a file. 
 
1356
    # flush, in case output is rerouted to a file.
1236
1357
    console_flush()
1237
1358
 
1238
1359
    # done