1# -*- coding: utf-8 -*-
2#
3# Copyright (C) 2011 Nick Lanham <nick@afternight.org>
4#
5# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
6# the additional special exception to link portions of this program with the OpenSSL library.
7# See LICENSE for more details.
8#
9
10from __future__ import unicode_literals
11
12import logging
13
14import deluge.common
15from deluge.ui.client import client
16from deluge.ui.console.widgets.popup import InputPopup, SelectablePopup
17
18log = logging.getLogger(__name__)
19
20
21def report_add_status(torrentlist, succ_cnt, fail_cnt, fail_msgs):
22    if fail_cnt == 0:
23        torrentlist.report_message(
24            'Torrents Added', '{!success!}Successfully added %d torrent(s)' % succ_cnt
25        )
26    else:
27        msg = (
28            '{!error!}Failed to add the following %d torrent(s):\n {!input!}' % fail_cnt
29        ) + '\n '.join(fail_msgs)
30        if succ_cnt != 0:
31            msg += '\n \n{!success!}Successfully added %d torrent(s)' % succ_cnt
32        torrentlist.report_message('Torrent Add Report', msg)
33
34
35def show_torrent_add_popup(torrentlist):
36    def do_add_from_url(data=None, **kwargs):
37        torrentlist.pop_popup()
38        if not data or kwargs.get('close', False):
39            return
40
41        def fail_cb(msg, url):
42            log.debug('failed to add torrent: %s: %s', url, msg)
43            error_msg = '{!input!} * %s: {!error!}%s' % (url, msg)
44            report_add_status(torrentlist, 0, 1, [error_msg])
45
46        def success_cb(tid, url):
47            if tid:
48                log.debug('added torrent: %s (%s)', url, tid)
49                report_add_status(torrentlist, 1, 0, [])
50            else:
51                fail_cb('Already in session (probably)', url)
52
53        url = data['url']['value']
54        if not url:
55            return
56
57        t_options = {
58            'download_location': data['path']['value'],
59            'add_paused': data['add_paused']['value'],
60        }
61
62        if deluge.common.is_magnet(url):
63            client.core.add_torrent_magnet(url, t_options).addCallback(
64                success_cb, url
65            ).addErrback(fail_cb, url)
66        elif deluge.common.is_url(url):
67            client.core.add_torrent_url(url, t_options).addCallback(
68                success_cb, url
69            ).addErrback(fail_cb, url)
70        else:
71            torrentlist.report_message(
72                'Error', '{!error!}Invalid URL or magnet link: %s' % url
73            )
74            return
75
76        log.debug(
77            'Adding Torrent(s): %s (dl path: %s) (paused: %d)',
78            url,
79            data['path']['value'],
80            data['add_paused']['value'],
81        )
82
83    def show_add_url_popup():
84        add_paused = 1 if 'add_paused' in torrentlist.coreconfig else 0
85        popup = InputPopup(
86            torrentlist, 'Add Torrent (Esc to cancel)', close_cb=do_add_from_url
87        )
88        popup.add_text_input('url', 'Enter torrent URL or Magnet link:')
89        popup.add_text_input(
90            'path',
91            'Enter save path:',
92            torrentlist.coreconfig.get('download_location', ''),
93            complete=True,
94        )
95        popup.add_select_input(
96            'add_paused', 'Add Paused:', ['Yes', 'No'], [True, False], add_paused
97        )
98        torrentlist.push_popup(popup)
99
100    def option_chosen(selected, *args, **kwargs):
101        if not selected or selected == 'cancel':
102            torrentlist.pop_popup()
103            return
104        if selected == 'file':
105            torrentlist.consoleui.set_mode('AddTorrents')
106        elif selected == 'url':
107            show_add_url_popup()
108
109    popup = SelectablePopup(torrentlist, 'Add torrent', option_chosen)
110    popup.add_line('file', '- From _File(s)', use_underline=True)
111    popup.add_line('url', '- From _URL or Magnet', use_underline=True)
112    popup.add_line('cancel', '- _Cancel', use_underline=True)
113    torrentlist.push_popup(popup, clear=True)
114