summaryrefslogtreecommitdiffstats
path: root/deluge/ui/console/cmdline/commands/add.py
blob: e6282d9a2627b902f3c469b53a4b22baf5ff73ed (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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2009 Ido Abramovich <ido.deluge@gmail.com>
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#

from __future__ import unicode_literals

import base64
import os

from twisted.internet import defer

import deluge.common
import deluge.component as component
from deluge.ui.client import client

from . import BaseCommand

try:
    from urllib.parse import urlparse
    from urllib.request import url2pathname
except ImportError:
    # PY2 fallback
    from urlparse import urlparse  # pylint: disable=ungrouped-imports
    from urllib import url2pathname  # pylint: disable=ungrouped-imports


class Command(BaseCommand):
    """Add torrents"""

    def add_arguments(self, parser):
        parser.add_argument('-p', '--path', dest='path', help=_('download folder for torrent'))
        parser.add_argument('torrents', metavar='<torrent>', nargs='+',
                            help=_('One or more torrent files, URLs or magnet URIs'))

    def handle(self, options):
        self.console = component.get('ConsoleUI')

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

        def on_success(result):
            if not result:
                self.console.write('{!error!}Torrent was not added: Already in session')
            else:
                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 torrent in options.torrents:
            if not torrent.strip():
                continue
            if deluge.common.is_url(torrent):
                self.console.write('{!info!}Attempting to add torrent from url: %s' % torrent)
                deferreds.append(client.core.add_torrent_url(torrent, t_options).addCallback(on_success).addErrback(
                    on_fail))
            elif deluge.common.is_magnet(torrent):
                self.console.write('{!info!}Attempting to add torrent from magnet uri: %s' % torrent)
                deferreds.append(client.core.add_torrent_magnet(torrent, t_options).addCallback(on_success).addErrback(
                    on_fail))
            else:
                # Just a file
                if urlparse(torrent).scheme == 'file':
                    torrent = url2pathname(urlparse(torrent).path)
                path = os.path.abspath(os.path.expanduser(torrent))
                if not os.path.exists(path):
                    self.console.write('{!error!}%s does not exist!' % path)
                    continue
                if not os.path.isfile(path):
                    self.console.write('{!error!}This is a directory!')
                    continue
                self.console.write('{!info!}Attempting to add torrent: %s' % path)
                filename = os.path.split(path)[-1]
                with open(path, 'rb') as _file:
                    filedump = base64.encodestring(_file.read())
                deferreds.append(
                    client.core.add_torrent_file_async(
                        filename, filedump, t_options,
                    ).addCallback(on_success).addErrback(on_fail)
                )

        return defer.DeferredList(deferreds)

    def complete(self, line):
        return component.get('ConsoleUI').tab_complete_path(line, ext='.torrent', sort='date')