summaryrefslogtreecommitdiffstats
path: root/deluge/ui/console/commands/add.py
blob: 37a3eb2aa18fed5359a97c97de93e5c340588924 (plain)
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
#
# add.py
#
# Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com>
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge.    If not, write to:
# 	The Free Software Foundation, Inc.,
# 	51 Franklin Street, Fifth Floor
# 	Boston, MA  02110-1301, USA.
#
#    In addition, as a special exception, the copyright holders give
#    permission to link the code of portions of this program with the OpenSSL
#    library.
#    You must obey the GNU General Public License in all respects for all of
#    the code used other than OpenSSL. If you modify file(s) with this
#    exception, you may extend this exception to your version of the file(s),
#    but you are not obligated to do so. If you do not wish to do so, delete
#    this exception statement from your version. If you delete this exception
#    statement from all source files in the program, then also delete it here.
#
#
from twisted.internet import defer

from deluge.ui.console.main import BaseCommand
import deluge.ui.console.colors as colors
from deluge.ui.client import client
import deluge.component as component
import deluge.common

from optparse import make_option
import os
import base64

class Command(BaseCommand):
    """Add a torrent"""
    option_list = BaseCommand.option_list + (
            make_option('-p', '--path', dest='path',
                        help='save path for torrent'),
            make_option('-u', '--urls', action='store_true', default=False, dest='force_url',
                        help='Interpret all given torrent-file arguments as URLs'),
            make_option('-f', '--files', action='store_true', default=False, dest='force_file',
                        help='Interpret all given torrent-file arguments as files'),
    )

    usage = "Usage: add [-p <save-location>] [-u | --urls] [-f | --files] <torrent-file> [<torrent-file> ...]\n"\
            "             <torrent-file> arguments can be file paths, URLs or magnet uris"

    def handle(self, *args, **options):
        self.console = component.get("ConsoleUI")

        if options["force_file"] and options["force_url"]:
            self.console.write("{!error!}Cannot specify --urls and --files at the same time")
            return

        t_options = {}
        if options["path"]:
            t_options["download_location"] = os.path.expanduser(options["path"])

        def on_success(result):
            self.console.write("{!success!}Torrent added!")
        def on_fail(result):
            self.console.write("{!error!}Torrent was not added! %s" % result)

        # Keep a list of deferreds to make a DeferredList
        deferreds = []
        for arg in args:
            if not options["force_file"] and (deluge.common.is_url(arg) or options["force_url"]):
                self.console.write("{!info!}Attempting to add torrent from url: %s" % arg)
                deferreds.append(client.core.add_torrent_url(arg, t_options).addCallback(on_success).addErrback(on_fail))
            elif not options["force_file"] and (deluge.common.is_magnet(arg)):
                self.console.write("{!info!}Attempting to add torrent from magnet uri: %s" % arg)
                deferreds.append(client.core.add_torrent_magnet(arg, t_options).addCallback(on_success).addErrback(on_fail))
            else:
                if not os.path.exists(arg):
                    self.console.write("{!error!}%s doesn't exist!" % arg)
                    continue
                if not os.path.isfile(arg):
                    self.console.write("{!error!}This is a directory!")
                    continue
                self.console.write("{!info!}Attempting to add torrent: %s" % arg)
                filename = os.path.split(arg)[-1]
                filedump = base64.encodestring(open(arg, "rb").read())

                deferreds.append(client.core.add_torrent_file(filename, filedump, t_options).addCallback(on_success).addErrback(on_fail))

        return defer.DeferredList(deferreds)

    def complete(self, line):
        line = os.path.abspath(os.path.expanduser(line))
        ret = []
        if os.path.exists(line):
            # This is a correct path, check to see if it's a directory
            if os.path.isdir(line):
                # Directory, so we need to show contents of directory
                #ret.extend(os.listdir(line))
                for f in os.listdir(line):
                    # Skip hidden
                    if f.startswith("."):
                        continue
                    f = os.path.join(line, f)
                    if os.path.isdir(f):
                        f += "/"
                    ret.append(f)
            else:
                # This is a file, but we could be looking for another file that
                # shares a common prefix.
                for f in os.listdir(os.path.dirname(line)):
                    if f.startswith(os.path.split(line)[1]):
                        ret.append(os.path.join( os.path.dirname(line), f))
        else:
            # This path does not exist, so lets do a listdir on it's parent
            # and find any matches.
            ret = []
            if os.path.isdir(os.path.dirname(line)):
                for f in os.listdir(os.path.dirname(line)):
                    if f.startswith(os.path.split(line)[1]):
                        p = os.path.join(os.path.dirname(line), f)

                        if os.path.isdir(p):
                            p += "/"
                        ret.append(p)

        return ret