Пример #1
0
    def split_magnets(self, filename):
        log.debug('Attempting to open %s for splitting magnets.', filename)
        magnets = []
        try:
            with open(filename, 'r') as _file:
                magnets = list(filter(len, _file.read().splitlines()))
        except IOError as ex:
            log.warning('Unable to open %s: %s', filename, ex)

        if len(magnets) < 2:
            return []

        path = filename.rsplit(os.sep, 1)[0]
        for magnet in magnets:
            if not is_magnet(magnet):
                log.warning('Found line which is not a magnet: %s', magnet)
                continue

            for part in magnet.split('&'):
                if part.startswith('dn='):
                    name = part[3:].strip()
                    if name:
                        mname = os.sep.join([path, name + '.magnet'])
                        break
            else:
                short_hash = magnet.split('btih:')[1][:8]
                mname = '.'.join([os.path.splitext(filename)[0], short_hash, 'magnet'])

            try:
                with open(mname, 'w') as _mfile:
                    _mfile.write(magnet)
            except IOError as ex:
                log.warning('Unable to open %s: %s', mname, ex)
        return magnets
Пример #2
0
    def add_torrents(self, torrents):
        """
        Add torrents by file

        :param torrents: A list of dictionaries containing the torrent \
            path and torrent options to add with.
        :type torrents: list

        ::

            json_api.web.add_torrents([{
                "path": "/tmp/deluge-web/some-torrent-file.torrent",
                "options": {"download_location": "/home/deluge/"}
            }])

        """
        deferreds = []

        for torrent in torrents:
            if is_magnet(torrent['path']):
                log.info('Adding torrent from magnet uri `%s` with options `%r`',
                         torrent['path'], torrent['options'])
                d = client.core.add_torrent_magnet(torrent['path'], torrent['options'])
                deferreds.append(d)
            else:
                filename = os.path.basename(torrent['path'])
                with open(torrent['path'], 'rb') as _file:
                    fdump = base64.encodestring(_file.read())
                log.info('Adding torrent from file `%s` with options `%r`',
                         filename, torrent['options'])
                d = client.core.add_torrent_file(filename, fdump, torrent['options'])
                deferreds.append(d)
        return DeferredList(deferreds, consumeErrors=False)
Пример #3
0
    def add_torrent(self, metainfo, options=None):
        """Adds a torrent with the given options.
        metainfo could either be base64 torrent data or a magnet link.

        Returns `torrent_id` string or None.

        Available options are listed in deluge.core.torrent.TorrentOptions.

        :rtype: None|str
        """
        if options is None:
            options = {}

        coreconfig = component.get('CoreConfig')

        if 'download_location' not in options.keys():
            options.update({'download_location': coreconfig.get("download_location")})

        metainfo = metainfo.encode()

        if common.is_magnet(metainfo):
            LOGGER.info('Adding torrent from magnet URI `%s` using options `%s` ...', metainfo, options)
            result = client.core.add_torrent_magnet(metainfo, options)

        else:
            LOGGER.info('Adding torrent from base64 string using options `%s` ...', options)
            result = client.core.add_torrent_file(None, metainfo, options)

        return result
Пример #4
0
    def split_magnets(self, filename):
        log.debug('Attempting to open %s for splitting magnets.', filename)
        magnets = []
        try:
            with open(filename, 'r') as _file:
                magnets = list(filter(len, _file.read().splitlines()))
        except IOError as ex:
            log.warning('Unable to open %s: %s', filename, ex)

        if len(magnets) < 2:
            return []

        path = filename.rsplit(os.sep, 1)[0]
        for magnet in magnets:
            if not is_magnet(magnet):
                log.warning('Found line which is not a magnet: %s', magnet)
                continue

            for part in magnet.split('&'):
                if part.startswith('dn='):
                    name = part[3:].strip()
                    if name:
                        mname = os.sep.join([path, name + '.magnet'])
                        break
            else:
                short_hash = magnet.split('btih:')[1][:8]
                mname = '.'.join([os.path.splitext(filename)[0], short_hash, 'magnet'])

            try:
                with open(mname, 'w') as _mfile:
                    _mfile.write(magnet)
            except IOError as ex:
                log.warning('Unable to open %s: %s', mname, ex)
        return magnets
Пример #5
0
    def add_torrent(self, metainfo, options=None):
        """Adds a torrent with the given options.
        metainfo could either be base64 torrent data or a magnet link.

        Returns `torrent_id` string or None.

        Available options are listed in deluge.core.torrent.TorrentOptions.

        :rtype: None|str
        """
        if options is None:
            options = {}

        coreconfig = component.get('CoreConfig')
        options.update(
            {'download_location': coreconfig.get("download_location")})

        metainfo = metainfo.encode()
        if common.is_magnet(metainfo):
            LOGGER.info(
                'Adding torrent from magnet URI `%s` using options `%s` ...',
                metainfo, options)
            result = client.core.add_torrent_magnet(metainfo, options)
        else:
            LOGGER.info(
                'Adding torrent from base64 string using options `%s` ...',
                options)
            result = client.core.add_torrent_file(None, metainfo, options)

        return result
Пример #6
0
    def add_torrents(self, torrents):
        """
        Add torrents by file

        :param torrents: A list of dictionaries containing the torrent \
        path and torrent options to add with.
        :type torrents: list

        **Usage**

        >>> json_api.web.add_torrents([{
                "path": "/tmp/deluge-web/some-torrent-file.torrent",
                "options": {"download_location": "/home/deluge/"}
            }])

        """
        for torrent in torrents:
            if common.is_magnet(torrent["path"]):
                log.info("Adding torrent from magnet uri `%s` with options `%r`",
                         torrent["path"], torrent["options"])
                client.core.add_torrent_magnet(torrent["path"], torrent["options"])
            else:
                filename = os.path.basename(torrent["path"])
                fdump = base64.encodestring(open(torrent["path"], "rb").read())
                log.info("Adding torrent from file `%s` with options `%r`",
                         filename, torrent["options"])
                client.core.add_torrent_file(filename, fdump, torrent["options"])
        return True
Пример #7
0
    def add_magnet(self, bot, update):
        if str(update.message.chat.id) in self.whitelist:
            try:
                user = update.message.chat.id
                log.debug("addmagnet of %s: %s" % (str(user), update.message.text))

                try:
                    # options = None
                    metainfo = update.message.text
                    """Adds a torrent with the given options.
                    metainfo could either be base64 torrent
                    data or a magnet link. Available options
                    are listed in deluge.core.torrent.TorrentOptions.
                    """
                    if self.opts is None:
                        self.opts = {}
                    if is_magnet(metainfo):
                        log.debug(prelog() + 'Adding torrent from magnet ' +
                                  'URI `%s` using options `%s` ...',
                                  metainfo, self.opts)
                        tid = self.core.add_torrent_magnet(metainfo, self.opts)
                        self.apply_label(tid)
                    else:
                        update.message.reply_text(STRINGS['not_magnet'],
                                                  reply_markup=ReplyKeyboardRemove())
                except Exception as e:
                    log.error(prelog() + str(e) + '\n' + traceback.format_exc())

                return ConversationHandler.END

            except Exception as e:
                log.error(prelog() + str(e) + '\n' + traceback.format_exc())
Пример #8
0
    def add_torrents(self, torrents):
        """
        Add torrents by file

        :param torrents: A list of dictionaries containing the torrent \
        path and torrent options to add with.
        :type torrents: list

        **Usage**

        >>> json_api.web.add_torrents([{
                "path": "/tmp/deluge-web/some-torrent-file.torrent",
                "options": {"download_location": "/home/deluge/"}
            }])

        """
        for torrent in torrents:
            if common.is_magnet(torrent["path"]):
                log.info(
                    "Adding torrent from magnet uri `%s` with options `%r`",
                    torrent["path"], torrent["options"])
                client.core.add_torrent_magnet(torrent["path"],
                                               torrent["options"])
            else:
                filename = os.path.basename(torrent["path"])
                fdump = base64.encodestring(open(torrent["path"], "rb").read())
                log.info("Adding torrent from file `%s` with options `%r`",
                         filename, torrent["options"])
                client.core.add_torrent_file(filename, fdump,
                                             torrent["options"])
        return True
Пример #9
0
    def add_magnet(self, bot, update):
        if str(update.message.chat.id) in self.whitelist:
            try:
                user = update.message.chat.id
                log.debug("addmagnet of %s: %s" %
                          (str(user), update.message.text))

                try:
                    #options = None
                    metainfo = update.message.text
                    """Adds a torrent with the given options.
                    metainfo could either be base64 torrent data or a magnet link.
                    Available options are listed in deluge.core.torrent.TorrentOptions.
                    """
                    if self.opts is None:
                        self.opts = {}
                    if is_magnet(metainfo):
                        log.debug(
                            prelog() +
                            'Adding torrent from magnet URI `%s` using options `%s` ...',
                            metainfo, self.opts)
                        tid = self.core.add_torrent_magnet(metainfo, self.opts)
                        self.apply_label(tid)
                    else:
                        update.message.reply_text(
                            STRINGS['not_magnet'],
                            reply_markup=ReplyKeyboardRemove())
                except Exception as e:
                    log.error(prelog() + str(e) + '\n' +
                              traceback.format_exc())

                return ConversationHandler.END

            except Exception as e:
                log.error(prelog() + str(e) + '\n' + traceback.format_exc())
Пример #10
0
def process_args(args):
    """Process arguments sent to already running Deluge"""
    # Make sure args is a list
    args = list(args)
    log.debug('Processing args from other process: %s', args)
    if not client.connected():
        # We're not connected so add these to the queue
        log.debug('Not connected to host.. Adding to queue.')
        component.get('QueuedTorrents').add_to_queue(args)
        return
    config = ConfigManager('gtkui.conf')

    for arg in args:
        if not arg.strip():
            continue
        log.debug('arg: %s', arg)

        if is_url(arg):
            log.debug('Attempting to add url (%s) from external source...',
                      arg)
            if config['interactive_add']:
                component.get('AddTorrentDialog').add_from_url(arg)
                component.get('AddTorrentDialog').show(
                    config['focus_add_dialog'])
            else:
                client.core.add_torrent_url(arg, None)

        elif is_magnet(arg):
            log.debug('Attempting to add magnet (%s) from external source...',
                      arg)
            if config['interactive_add']:
                component.get('AddTorrentDialog').add_from_magnets([arg])
                component.get('AddTorrentDialog').show(
                    config['focus_add_dialog'])
            else:
                client.core.add_torrent_magnet(arg, {})

        else:
            log.debug('Attempting to add file (%s) from external source...',
                      arg)
            if urlparse(arg).scheme == 'file':
                arg = url2pathname(urlparse(arg).path)
            path = os.path.abspath(decode_bytes(arg))

            if not os.path.exists(path):
                log.error('No such file: %s', path)
                continue

            if config['interactive_add']:
                component.get('AddTorrentDialog').add_from_files([path])
                component.get('AddTorrentDialog').show(
                    config['focus_add_dialog'])
            else:
                with open(path, 'rb') as _file:
                    filedump = b64encode(_file.read())
                client.core.add_torrent_file(
                    os.path.split(path)[-1], filedump, None)
Пример #11
0
 def on_focus(self, window, param):
     if window.props.is_active and not self.first_run and self.config[
             'detect_urls']:
         text = get_clipboard_text()
         if text == self.previous_clipboard_text:
             return
         self.previous_clipboard_text = text
         if text and ((is_url(text) and text.endswith('.torrent'))
                      or is_magnet(text)):
             component.get('AddTorrentDialog').show()
             component.get('AddTorrentDialog').on_button_url_clicked(window)
     self.first_run = False
Пример #12
0
    def on_button_url_clicked(self, widget):
        log.debug('on_button_url_clicked')
        dialog = self.builder.get_object('url_dialog')
        entry = self.builder.get_object('entry_url')

        dialog.set_default_response(Gtk.ResponseType.OK)
        dialog.set_transient_for(self.dialog)
        entry.grab_focus()

        text = get_clipboard_text()
        if text and is_url(text) or is_magnet(text):
            entry.set_text(text)

        dialog.show_all()
        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            url = decode_bytes(entry.get_text())
        else:
            url = None

        entry.set_text('')
        dialog.hide()

        # This is where we need to fetch the .torrent file from the URL and
        # add it to the list.
        log.debug('url: %s', url)
        if url:
            if is_url(url):
                self.add_from_url(url)
            elif is_magnet(url):
                self.add_from_magnets([url])
            else:
                ErrorDialog(
                    _('Invalid URL'),
                    '%s %s' % (url, _('is not a valid URL.')),
                    self.dialog,
                ).run()
Пример #13
0
    def add_torrents(self):
        (model, row) = self.listview_torrents.get_selection().get_selected()
        if row is not None:
            self.save_torrent_options(row)

        torrents_to_add = []

        row = self.torrent_liststore.get_iter_first()
        while row is not None:
            torrent_id = self.torrent_liststore.get_value(row, 0)
            filename = xml_unescape(
                decode_bytes(self.torrent_liststore.get_value(row, 2)))
            try:
                options = self.options[torrent_id]
            except KeyError:
                options = None

            file_priorities = self.get_file_priorities(torrent_id)
            if options is not None:
                options['file_priorities'] = file_priorities

            if self.infos[torrent_id]:
                torrents_to_add.append((
                    os.path.split(filename)[-1],
                    b64encode(self.infos[torrent_id]),
                    options,
                ))
            elif is_magnet(filename):
                client.core.add_torrent_magnet(filename,
                                               options).addErrback(log.debug)

            row = self.torrent_liststore.iter_next(row)

        def on_torrents_added(errors):
            if errors:
                log.info(
                    'Failed to add %d out of %d torrents.',
                    len(errors),
                    len(torrents_to_add),
                )
                for e in errors:
                    log.info('Torrent add failed: %s', e)
            else:
                log.info('Successfully added %d torrents.',
                         len(torrents_to_add))

        if torrents_to_add:
            client.core.add_torrent_files(torrents_to_add).addCallback(
                on_torrents_added)
Пример #14
0
    def torrent_add(self, metainfo):
        """
    Adds a torrent.

    metainfo: either base64 torrent data or a magnet link
    """

        if common.is_magnet(metainfo):
            logger.info("Adding torrent from magnet URI `%s` using options `%s` ...", metainfo, options)
            client.core.add_torrent_magnet(metainfo, {})
        else:
            logger.info("Adding torrent from base64 string using options `%s` ...", options)
            client.core.add_torrent_file(None, metainfo, {})

        return True
Пример #15
0
    def add_torrent(self, metainfo, options=None):
        """Adds a torrent with the given options.
        metainfo could either be base64 torrent data or a magnet link.

        Available options are listed in deluge.core.torrent.TorrentOptions.

        """
        if options is None:
            options = {}

        if common.is_magnet(metainfo):
            LOGGER.info('Adding torrent from magnet URI `%s` using options `%s` ...', metainfo, options)
            client.core.add_torrent_magnet(metainfo, options)
        else:
            LOGGER.info('Adding torrent from base64 string using options `%s` ...', options)
            client.core.add_torrent_file(None, metainfo, options)
        return True
Пример #16
0
    def add_torrents(self, torrents):
        """
        Add torrents by file

        :param torrents: A list of dictionaries containing the torrent \
            path and torrent options to add with.
        :type torrents: list

        ::

            json_api.web.add_torrents([{
                "path": "/tmp/deluge-web/some-torrent-file.torrent",
                "options": {"download_location": "/home/deluge/"}
            }])

        """
        deferreds = []

        for torrent in torrents:
            if is_magnet(torrent['path']):
                log.info(
                    'Adding torrent from magnet uri `%s` with options `%r`',
                    torrent['path'],
                    torrent['options'],
                )
                d = client.core.add_torrent_magnet(torrent['path'],
                                                   torrent['options'])
                deferreds.append(d)
            else:
                filename = os.path.basename(torrent['path'])
                with open(torrent['path'], 'rb') as _file:
                    fdump = b64encode(_file.read())
                log.info(
                    'Adding torrent from file `%s` with options `%r`',
                    filename,
                    torrent['options'],
                )
                d = client.core.add_torrent_file_async(filename, fdump,
                                                       torrent['options'])
                deferreds.append(d)
        return DeferredList(deferreds, consumeErrors=False)
Пример #17
0
    def add_torrent(self, metainfo, options=None):
        """Adds a torrent with the given options.
        metainfo could either be base64 torrent data or a magnet link.

        Returns `torrent_id` string or None.

        Available options are listed in deluge.core.torrent.TorrentOptions.

        :rtype: None|str
        """
        if options is None:
            options = {}

        if common.is_magnet(metainfo):
            LOGGER.info('Adding torrent from magnet URI `%s` using options `%s` ...', metainfo, options)
            result = client.core.add_torrent_magnet(metainfo, options)
        else:
            LOGGER.info('Adding torrent from base64 string using options `%s` ...', options)
            result = client.core.add_torrent_file(None, metainfo, options)

        return result
Пример #18
0
 def test_is_magnet(self):
     self.assertTrue(is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN'))
Пример #19
0
 def test_is_magnet(self):
     self.assertTrue(
         is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN')
     )
     self.assertFalse(is_magnet(None))