Example #1
0
    def download_torrent_file(self, torrent_url, cookies=None, headers=None):
        download = TorrentDownload()
        download.url = torrent_url
        download.cookies = cookies
        args = {"verify": False}
        if cookies is not None:
            args["cookies"] = cookies
        if headers is not None:
            args["headers"] = headers
        download.headers = headers
        try:
            r = requests.get(torrent_url, **args)
            download.filedump = r.content
        except Exception as e:
            error_msg = "Failed to download torrent url: '%s'. Exception: %s" % (
                torrent_url, str(e))
            self.log.error(error_msg)
            download.set_error(error_msg)
            return download

        if download.filedump is None:
            error_msg = "Filedump is None"
            download.set_error(error_msg)
            self.log.warning(error_msg)
            return download

        try:
            # Get the info to see if any exceptions are raised
            lt.torrent_info(lt.bdecode(download.filedump))
        except Exception as e:
            error_msg = "Unable to decode torrent file! (%s) URL: '%s'" % (
                str(e), torrent_url)
            download.set_error(error_msg)
            self.log.error(error_msg)
        return download
def check_torrent(filename):
    # Test loading with libtorrent to make sure it's valid
    from deluge._libtorrent import lt
    lt.torrent_info(filename)

    # Test loading with our internal TorrentInfo class
    from deluge.ui.common import TorrentInfo
    ti = TorrentInfo(filename)
Example #3
0
def check_torrent(filename):
    # Test loading with libtorrent to make sure it's valid
    from deluge._libtorrent import lt
    lt.torrent_info(filename)

    # Test loading with our internal TorrentInfo class
    from deluge.ui.common import TorrentInfo
    ti = TorrentInfo(filename)
Example #4
0
    def add(self,
            torrent_info=None,
            state=None,
            options=None,
            save_state=True,
            filedump=None,
            filename=None,
            magnet=None,
            resume_data=None):
        """Add a torrent to the manager and returns it's torrent_id"""

        if torrent_info is None and state is None and filedump is None and magnet is None:
            log.debug(
                "You must specify a valid torrent_info, torrent state or magnet."
            )
            return

        log.debug("torrentmanager.add")
        add_torrent_params = {}

        if filedump is not None:
            try:
                torrent_info = lt.torrent_info(lt.bdecode(filedump))
            except Exception, e:
                log.error("Unable to decode torrent file!: %s", e)
                # XXX: Probably should raise an exception here..
                return
Example #5
0
class TorrentHandler(object):
    def __init__(self, logger):
        self.log = logger

    def download_torrent_file(self, torrent_url, cookie_header):
        filedump = None
        opener = urllib2.build_opener()

        if cookie_header.has_key("Cookie"):
            opener.addheaders.append(("Cookie", cookie_header["Cookie"]))
        try:
            webFile = opener.open(torrent_url)
            filedump = webFile.read()
        except Exception, e:
            self.log.error(
                "Failed to download torrent url: '%s'. Exception: %s" %
                (torrent_url, str(e)))
            return None
        # Get the info to see if any exceptions are raised
        try:
            torrent_info = lt.torrent_info(lt.bdecode(filedump))
        except Exception, e:
            self.log.error("Unable to decode torrent file! (%s) URL: '%s'" %
                           (str(e), torrent_url))
            return None
Example #6
0
    def add(self,
            torrent_info=None,
            state=None,
            options=None,
            save_state=True,
            filedump=None,
            filename=None,
            magnet=None,
            resume_data=None,
            owner=None):
        """Add a torrent to the manager and returns it's torrent_id"""
        if owner is None:
            owner = component.get("RPCServer").get_session_user()
            if not owner:
                owner = "localclient"

        if torrent_info is None and state is None and filedump is None and magnet is None:
            log.debug(
                "You must specify a valid torrent_info, torrent state or magnet."
            )
            return

        add_torrent_params = {}

        if filedump is not None:
            try:
                torrent_info = lt.torrent_info(lt.bdecode(filedump))
            except Exception, e:
                log.error("Unable to decode torrent file!: %s", e)
                # XXX: Probably should raise an exception here..
                return
Example #7
0
 def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None):
     tor = component.get("TorrentManager").torrents.get(infohash, None)
     
     if tor is None:
         logger.info('Did not find torrent, must add it')
         
         if not filedump and url:
             filedump = yield client.getPage(url)
         
         if not filedump:
             defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'})
         
         torrent_info = lt.torrent_info(lt.bdecode(filedump))
         infohash = str(torrent_info.info_hash())
     
         core = component.get("Core")
         try:
             yield core.add_torrent_file('file.torrent', filedump.encode('base64'), {'add_paused': True})
         except:
             defer.returnValue({'status': 'error', 'message': 'failed to add torrent'})
         
     try:
         tf = self.torrent_handler.get_stream(infohash, filepath_or_index)
     except UnknownTorrentException:
         defer.returnValue({'status': 'error', 'message': 'unable to find torrent, probably failed to add it'})
     
     defer.returnValue({
         'status': 'success',
         'use_stream_urls': self.config['use_stream_urls'],
         'auto_open_stream_urls': self.config['auto_open_stream_urls'],
         'url': 'http://%s:%s/file/%s/%s' % (self.config.config['ip'], self.config.config['port'],
                                             self.fsr.add_file(tf), urllib.quote_plus(os.path.basename(tf.path)))
     })
Example #8
0
    def add(
        self,
        torrent_info=None,
        state=None,
        options=None,
        save_state=True,
        filedump=None,
        filename=None,
        magnet=None,
        resume_data=None,
    ):
        """Add a torrent to the manager and returns it's torrent_id"""

        if torrent_info is None and state is None and filedump is None and magnet is None:
            log.debug("You must specify a valid torrent_info, torrent state or magnet.")
            return

        log.debug("torrentmanager.add")
        add_torrent_params = {}

        if filedump is not None:
            try:
                torrent_info = lt.torrent_info(lt.bdecode(filedump))
            except Exception, e:
                log.error("Unable to decode torrent file!: %s", e)
                # XXX: Probably should raise an exception here..
                return
class TorrentHandler(object):
    def __init__(self, logger):
        self.log = logger

    def listen_on_torrent_finished(self, enable=True):
        component.get("EventManager").register_event_handler(
            "TorrentFinishedEvent", self.on_torrent_finished_event)

    def download_torrent_file(self, torrent_url, cookies=None, headers=None):
        download = TorrentDownload()
        download.url = torrent_url
        download.cookies = cookies
        args = {"verify": False}
        if cookies is not None:
            args["cookies"] = cookies
        if headers is not None:
            args["headers"] = headers
        download.headers = headers
        try:
            r = requests.get(torrent_url, **args)
            download.filedump = r.content
        except Exception, e:
            error_msg = "Failed to download torrent url: '%s'. Exception: %s" % (
                torrent_url, str(e))
            self.log.error(error_msg)
            download.set_error(error_msg)
            return download
        try:
            # Get the info to see if any exceptions are raised
            lt.torrent_info(lt.bdecode(download.filedump))
        except Exception, e:
            error_msg = "Unable to decode torrent file! (%s) URL: '%s'" % (
                str(e), torrent_url)
            download.set_error(error_msg)
            self.log.error(error_msg)
Example #10
0
    def stream_torrent(self,
                       infohash=None,
                       url=None,
                       filedump=None,
                       filepath_or_index=None):
        tor = component.get("TorrentManager").torrents.get(infohash, None)

        if tor is None:
            logger.info('Did not find torrent, must add it')

            if not filedump and url:
                filedump = yield client.getPage(url)

            if not filedump:
                defer.returnValue({
                    'status':
                    'error',
                    'message':
                    'unable to find torrent, provide infohash, url or filedump'
                })

            torrent_info = lt.torrent_info(lt.bdecode(filedump))
            infohash = str(torrent_info.info_hash())

            core = component.get("Core")
            try:
                yield core.add_torrent_file('file.torrent',
                                            filedump.encode('base64'),
                                            {'add_paused': True})
            except:
                defer.returnValue({
                    'status': 'error',
                    'message': 'failed to add torrent'
                })

        try:
            tf = self.torrent_handler.get_stream(infohash, filepath_or_index)
        except UnknownTorrentException:
            defer.returnValue({
                'status':
                'error',
                'message':
                'unable to find torrent, probably failed to add it'
            })

        defer.returnValue({
            'status':
            'success',
            'use_stream_urls':
            self.config['use_stream_urls'],
            'auto_open_stream_urls':
            self.config['auto_open_stream_urls'],
            'url':
            'http://%s:%s/file/%s/%s' %
            (self.config.config['ip'], self.config.config['port'],
             self.fsr.add_file(tf), urllib.quote_plus(os.path.basename(
                 tf.path)))
        })
Example #11
0
    def load_torrent(self, filename, magnet):
        log.debug('Attempting to open %s for add.', filename)
        file_mode = 'r' if magnet else 'rb'
        try:
            with open(filename, file_mode) as _file:
                filedump = _file.read()
        except IOError as ex:
            log.warning('Unable to open %s: %s', filename, ex)
            raise ex

        if not filedump:
            raise EOFError('Torrent is 0 bytes!')

        # Get the info to see if any exceptions are raised
        if not magnet:
            lt.torrent_info(lt.bdecode(filedump))

        return filedump
Example #12
0
File: core.py Project: zluca/deluge
    def load_torrent(self, filename, magnet):
        log.debug('Attempting to open %s for add.', filename)
        file_mode = 'r' if magnet else 'rb'
        try:
            with open(filename, file_mode) as _file:
                filedump = _file.read()
        except IOError as ex:
            log.warning('Unable to open %s: %s', filename, ex)
            raise ex

        if not filedump:
            raise EOFError('Torrent is 0 bytes!')

        # Get the info to see if any exceptions are raised
        if not magnet:
            lt.torrent_info(lt.bdecode(filedump))

        return filedump
Example #13
0
 def get_torrent_atp(self, filename):
     filename = common.get_test_data_file(filename)
     with open(filename, 'rb') as _file:
         info = lt.torrent_info(lt.bdecode(_file.read()))
     atp = {'ti': info}
     atp['save_path'] = os.getcwd()
     atp['storage_mode'] = lt.storage_mode_t.storage_mode_sparse
     atp['add_paused'] = False
     atp['auto_managed'] = True
     atp['duplicate_is_error'] = True
     return atp
Example #14
0
    def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None, includes_name=False, wait_for_end_pieces=False, label=None, as_inline=False):
        logger.debug('Trying to stream infohash:%s, url:%s, filepath_or_index:%s' % (infohash, url, filepath_or_index))
        torrent = get_torrent(infohash)

        if torrent is None:
            logger.info('Did not find torrent, must add it')

            if not filedump and url:
                filedump = yield client.getPage(url)

            if not filedump:
                defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'})

            torrent_info = lt.torrent_info(lt.bdecode(filedump))
            infohash = str(torrent_info.info_hash())

            core = component.get("Core")
            try:
                yield core.add_torrent_file('file.torrent', base64.b64encode(filedump), {'add_paused': True})
                if label and 'Label' in component.get('CorePluginManager').get_enabled_plugins():
                    label_plugin = component.get('CorePlugin.Label')
                    if label not in label_plugin.get_labels():
                        label_plugin.add(label)

                    try:
                        label_plugin.set_torrent(infohash, label)
                    except:
                        logger.exception('Failed to set label')
            except:
                logger.exception('Failed to add torrent')
                defer.returnValue({'status': 'error', 'message': 'failed to add torrent'})

        if filepath_or_index is None:
            fn = ''
        elif isinstance(filepath_or_index, int):
            status = torrent.get_status(['files'])
            fn = status['files'][filepath_or_index]['path']
        else:
            fn = filepath_or_index

        try:
            stream_or_item = yield defer.maybeDeferred(self.torrent_handler.stream, infohash, fn, wait_for_end_pieces=wait_for_end_pieces)
            stream_url = self.thomas_http_output.serve_item(stream_or_item, as_inline=as_inline)
        except:
            logger.exception('Failed to stream torrent')
            defer.returnValue({'status': 'error', 'message': 'failed to stream torrent'})

        defer.returnValue({
            'status': 'success',
            'filename': stream_or_item.id,
            'use_stream_urls': self.config['use_stream_urls'],
            'auto_open_stream_urls': self.config['auto_open_stream_urls'],
            'url': '%s/streaming/%s' % (self.base_url, stream_url.lstrip('/'))
        })
Example #15
0
 def get_torrent_atp(self, filename):
     filename = os.path.join(os.path.dirname(__file__), filename)
     e = lt.bdecode(open(filename, 'rb').read())
     info = lt.torrent_info(e)
     atp = {"ti": info}
     atp["save_path"] = os.getcwd()
     atp["storage_mode"] = lt.storage_mode_t.storage_mode_sparse
     atp["add_paused"] = False
     atp["auto_managed"] = True
     atp["duplicate_is_error"] = True
     return atp
Example #16
0
 def get_torrent_atp(self, filename):
     filename = os.path.join(os.path.dirname(__file__), filename)
     e = lt.bdecode(open(filename, 'rb').read())
     info = lt.torrent_info(e)
     atp = {"ti": info}
     atp["save_path"] = os.getcwd()
     atp["storage_mode"] = lt.storage_mode_t.storage_mode_sparse
     atp["add_paused"] = False
     atp["auto_managed"] = True
     atp["duplicate_is_error"] = True
     return atp
Example #17
0
 def get_torrent_info_from_file(self, filepath):
     """Returns a torrent_info for the file specified or None"""
     torrent_info = None
     # Get the torrent data from the torrent file
     try:
         log.debug("Attempting to create torrent_info from %s", filepath)
         _file = open(filepath, "rb")
         torrent_info = lt.torrent_info(lt.bdecode(_file.read()))
         _file.close()
     except (IOError, RuntimeError), e:
         log.warning("Unable to open %s: %s", filepath, e)
Example #18
0
 def get_torrent_atp(self, filename):
     filename = common.get_test_data_file(filename)
     with open(filename, 'rb') as _file:
         info = lt.torrent_info(lt.bdecode(_file.read()))
     atp = {'ti': info}
     atp['save_path'] = os.getcwd()
     atp['storage_mode'] = lt.storage_mode_t.storage_mode_sparse
     atp['add_paused'] = False
     atp['auto_managed'] = True
     atp['duplicate_is_error'] = True
     return atp
Example #19
0
def read_torrent_info(file_contents):
    """Returns a dictionary with basic information from torrent
    contents (see `read_torrent_file()`).

    Dict keys:
        hash - Torrent hash.
        files - A list of files within the torrent.

    """
    info_contents = lt.torrent_info(lt.bdecode(file_contents))
    files_from_torrent = [a_file.path.decode('utf-8') for a_file in info_contents.files()]
    info = {'hash': str(info_contents.info_hash()), 'files': files_from_torrent}
    return info
Example #20
0
    def test_prefetch_metadata(self):
        from deluge._libtorrent import lt

        with open(common.get_test_data_file('test.torrent'), 'rb') as _file:
            t_info = lt.torrent_info(lt.bdecode(_file.read()))
        mock_alert = mock.MagicMock()
        mock_alert.handle.info_hash = mock.MagicMock(
            return_value='ab570cdd5a17ea1b61e970bb72047de141bce173'
        )
        mock_alert.handle.get_torrent_info = mock.MagicMock(return_value=t_info)

        magnet = 'magnet:?xt=urn:btih:ab570cdd5a17ea1b61e970bb72047de141bce173'
        d = self.tm.prefetch_metadata(magnet, 30)
        self.tm.on_alert_metadata_received(mock_alert)

        expected = (
            'ab570cdd5a17ea1b61e970bb72047de141bce173',
            bencode(
                {
                    'piece length': 32768,
                    'sha1': (
                        b'2\xce\xb6\xa8"\xd7\xf0\xd4\xbf\xdc^K\xba\x1bh'
                        b'\x9d\xc5\xb7\xac\xdd'
                    ),
                    'name': 'azcvsupdater_2.6.2.jar',
                    'private': 0,
                    'pieces': (
                        b'\xdb\x04B\x05\xc3\'\xdab\xb8su97\xa9u'
                        b'\xca<w\\\x1ef\xd4\x9b\x16\xa9}\xc0\x9f:\xfd'
                        b'\x97qv\x83\xa2"\xef\x9d7\x0by!\rl\xe5v\xb7'
                        b'\x18{\xf7/"P\xe9\x8d\x01D\x9e8\xbd\x16\xe3'
                        b'\xfb-\x9d\xaa\xbcM\x11\xba\x92\xfc\x13F\xf0'
                        b'\x1c\x86x+\xc8\xd0S\xa9\x90`\xa1\xe4\x82\xe8'
                        b'\xfc\x08\xf7\xe3\xe5\xf6\x85\x1c%\xe7%\n\xed'
                        b'\xc0\x1f\xa1;\x9a\xea\xcf\x90\x0c/F>\xdf\xdagA'
                        b'\xc42|\xda\x82\xf5\xa6b\xa1\xb8#\x80wI\xd8f'
                        b'\xf8\xbd\xacW\xab\xc3s\xe0\xbbw\xf2K\xbe\xee'
                        b'\xa8rG\xe1W\xe8\xb7\xc2i\xf3\xd8\xaf\x9d\xdc'
                        b'\xd0#\xf4\xc1\x12u\xcd\x0bE?:\xe8\x9c\x1cu'
                        b'\xabb(oj\r^\xd5\xd5A\x83\x88\x9a\xa1J\x1c?'
                        b'\xa1\xd6\x8c\x83\x9e&'
                    ),
                    'length': 307949,
                    'name.utf-8': b'azcvsupdater_2.6.2.jar',
                    'ed2k': b'>p\xefl\xfa]\x95K\x1b^\xc2\\;;e\xb7',
                }
            ),
        )
        self.assertEqual(expected, self.successResultOf(d))
Example #21
0
 def get_torrent_atp(self, filename):
     filename = common.get_test_data_file(filename)
     with open(filename, 'rb') as _file:
         info = lt.torrent_info(lt.bdecode(_file.read()))
     atp = {
         'ti':
         info,
         'save_path':
         os.getcwd(),
         'storage_mode':
         lt.storage_mode_t.storage_mode_sparse,
         'flags': (lt.add_torrent_params_flags_t.flag_auto_managed
                   | lt.add_torrent_params_flags_t.flag_duplicate_is_error
                   & ~lt.add_torrent_params_flags_t.flag_paused),
     }
     return atp
Example #22
0
def read_torrent_info(file_contents):
    """Returns a dictionary with basic information from torrent
    contents (see `read_torrent_file()`).

    Dict keys:
        hash - Torrent hash.
        files - A list of files within the torrent.

    """
    info_contents = lt.torrent_info(lt.bdecode(file_contents))
    files_from_torrent = [
        a_file.path.decode('utf-8') for a_file in info_contents.files()
    ]
    info = {
        'hash': str(info_contents.info_hash()),
        'files': files_from_torrent
    }
    return info
Example #23
0
class Core(CorePluginBase):
    def enable(self):
        self.config = deluge.configmanager.ConfigManager("yarss.conf", DEFAULT_PREFS)
        self.update_status_timer = LoopingCall(self.update_handler)
        #self.update_handler()
        self.update_status_timer.start(self.config['updatetime'])

        
    def disable(self):
        self.update_status_timer.stop()
	self.config.save();

    def update(self):
        pass

    @export
    def set_config(self, config):
        "sets the config dictionary"
        for key in config.keys():
            self.config[key] = config[key]
        self.config.save()

    @export
    def get_config(self):
        "returns the config dictionary"
        return self.config.config

    def load_torrent(self, filename):
        try:
            log.debug("Attempting to open %s for add.", filename)
            _file = open(filename, "rb")
            filedump = _file.read()
            if not filedump:
                raise RuntimeError, "Torrent is 0 bytes!"
            _file.close()
        except IOError, e:
            log.warning("Unable to open %s: %s", filename, e)
            raise e

        # Get the info to see if any exceptions are raised
        info = lt.torrent_info(lt.bdecode(filedump))

        return filedump
Example #24
0
    def render_POST(self, request):
        log.debug("StreamXBMC: post: %r" % request.path)

        r = self.re_post.search(request.path)
        if not r:
            return self.bad_request(request)
        log.debug("StreamXBMC: request: %r" % request)

        headers = request.getAllHeaders()
        try:
            files = cgi.FieldStorage(
                fp=request.content,
                headers=headers,
                environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": headers["content-type"]},
            )
            filename, torrent = files["torrent_file"].filename, files["torrent_file"].value
            torrent_info = libtorrent.torrent_info(libtorrent.bdecode(torrent))
        except Exception, e:
            log.error("StreamXBMC: unable to parse torrent file: %s", e)
            return self.bad_request(request)
Example #25
0
    def add(self, torrent_info=None, state=None, options=None, save_state=True,
            filedump=None, filename=None, magnet=None, resume_data=None, owner=None):
        """Add a torrent to the manager and returns it's torrent_id"""
        if owner is None:
            owner = component.get("RPCServer").get_session_user()
            if not owner:
                owner = "localclient"

        if torrent_info is None and state is None and filedump is None and magnet is None:
            log.debug("You must specify a valid torrent_info, torrent state or magnet.")
            return

        add_torrent_params = {}

        if filedump is not None:
            try:
                torrent_info = lt.torrent_info(lt.bdecode(filedump))
            except Exception, e:
                log.error("Unable to decode torrent file!: %s", e)
                # XXX: Probably should raise an exception here..
                return
Example #26
0
    def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None, includes_name=False, wait_for_end_pieces=False):
        tor = component.get("TorrentManager").torrents.get(infohash, None)

        if tor is None:
            logger.info('Did not find torrent, must add it')

            if not filedump and url:
                filedump = yield client.getPage(url)

            if not filedump:
                defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'})

            torrent_info = lt.torrent_info(lt.bdecode(filedump))
            infohash = str(torrent_info.info_hash())

            core = component.get("Core")
            try:
                yield core.add_torrent_file('file.torrent', filedump.encode('base64'), {'add_paused': True})
            except:
                defer.returnValue({'status': 'error', 'message': 'failed to add torrent'})

        try:
            tf = self.torrent_handler.get_stream(infohash, filepath_or_index, includes_name)
        except UnknownTorrentException:
            defer.returnValue({'status': 'error', 'message': 'unable to find torrent, probably failed to add it'})

        if wait_for_end_pieces:
            logger.debug('Waiting for end pieces')
            yield tf.wait_for_end_pieces()

        filename = os.path.basename(tf.path).encode('utf-8')
        defer.returnValue({
            'status': 'success',
            'filename': filename,
            'use_stream_urls': self.config['use_stream_urls'],
            'auto_open_stream_urls': self.config['auto_open_stream_urls'],
            'url': '%s/streaming/file/%s/%s' % (self.base_url, self.fsr.add_file(tf),
                                                urllib.quote_plus(filename))
        })
Example #27
0
    def render_POST(self, request):
        log.debug('StreamXBMC: post: %r' % request.path)

        r = self.re_post.search(request.path)
        if not r:
            return self.bad_request(request)
        log.debug('StreamXBMC: request: %r' % request)

        headers = request.getAllHeaders()
        try:
            files = cgi.FieldStorage(fp=request.content,
                                     headers=headers,
                                     environ={
                                         'REQUEST_METHOD': 'POST',
                                         'CONTENT_TYPE':
                                         headers['content-type']
                                     })
            filename, torrent = files['torrent_file'].filename, files[
                'torrent_file'].value
            torrent_info = libtorrent.torrent_info(libtorrent.bdecode(torrent))
        except Exception, e:
            log.error('StreamXBMC: unable to parse torrent file: %s', e)
            return self.bad_request(request)
Example #28
0
                os.remove(filepath)

    def load_torrent(self, filename):
        try:
            log.debug("Attempting to open %s for add.", filename)
            _file = open(filename, "rb")
            filedump = _file.read()
            if not filedump:
                raise RuntimeError, "Torrent is 0 bytes!"
            _file.close()
        except IOError, e:
            log.warning("Unable to open %s: %s", filename, e)
            raise e

        # Get the info to see if any exceptions are raised
        info = lt.torrent_info(lt.bdecode(filedump))

        return filedump

    def _on_autoadd_enable(self, key, value):
        log.debug("_on_autoadd_enable")
        if value:
            component.resume("AutoAdd")
        else:
            component.pause("AutoAdd")

    def _on_autoadd_location(self, key, value):
        log.debug("_on_autoadd_location")
        # We need to resume the component just incase it was paused due to
        # an invalid autoadd location.
        if self.config["autoadd_enable"]:
Example #29
0
                os.remove(filepath)

    def load_torrent(self, filename):
        try:
            log.debug("Attempting to open %s for add.", filename)
            _file = open(filename, "rb")
            filedump = _file.read()
            if not filedump:
                raise RuntimeError, "Torrent is 0 bytes!"
            _file.close()
        except IOError, e:
            log.warning("Unable to open %s: %s", filename, e)
            raise e

        # Get the info to see if any exceptions are raised
        info = lt.torrent_info(lt.bdecode(filedump))

        return filedump

    def _on_autoadd_enable(self, key, value):
        log.debug("_on_autoadd_enable")
        if value:
            component.resume("AutoAdd")
        else:
            component.pause("AutoAdd")

    def _on_autoadd_location(self, key, value):
        log.debug("_on_autoadd_location")
        # We need to resume the component just incase it was paused due to
        # an invalid autoadd location.
        if self.config["autoadd_enable"]:
Example #30
0
class OldStateUpgrader:
    def __init__(self):
        self.config = ConfigManager("core.conf")
        self.state05_location = os.path.join(get_config_dir(),
                                             "persistent.state")
        self.state10_location = os.path.join(get_config_dir(), "state",
                                             "torrents.state")
        if os.path.exists(self.state05_location) and not os.path.exists(
                self.state10_location):
            # If the 0.5 state file exists and the 1.0 doesn't, then let's upgrade it
            self.upgrade05()

    def upgrade05(self):
        try:
            state = PickleUpgrader(open(self.state05_location, "rb")).load()
        except Exception, e:
            log.debug("Unable to open 0.5 state file: %s", e)
            return

        # Check to see if we can upgrade this file
        if type(state).__name__ == 'list':
            log.warning("0.5 state file is too old to upgrade")
            return

        new_state = deluge.core.torrentmanager.TorrentManagerState()
        for ti, uid in state.torrents.items():
            torrent_path = os.path.join(get_config_dir(), "torrentfiles",
                                        ti.filename)
            try:
                torrent_info = None
                log.debug("Attempting to create torrent_info from %s",
                          torrent_path)
                _file = open(torrent_path, "rb")
                torrent_info = lt.torrent_info(lt.bdecode(_file.read()))
                _file.close()
            except (IOError, RuntimeError), e:
                log.warning("Unable to open %s: %s", torrent_path, e)

            # Copy the torrent file to the new location
            import shutil
            shutil.copyfile(
                torrent_path,
                os.path.join(get_config_dir(), "state",
                             str(torrent_info.info_hash()) + ".torrent"))

            # Set the file prioritiy property if not already there
            if not hasattr(ti, "priorities"):
                ti.priorities = [1] * torrent_info.num_files()

            # Create the new TorrentState object
            new_torrent = deluge.core.torrentmanager.TorrentState(
                torrent_id=str(torrent_info.info_hash()),
                filename=ti.filename,
                save_path=ti.save_dir,
                compact=ti.compact,
                paused=ti.user_paused,
                total_uploaded=ti.uploaded_memory,
                max_upload_speed=ti.upload_rate_limit,
                max_download_speed=ti.download_rate_limit,
                file_priorities=ti.priorities,
                queue=state.queue.index(ti))
            # Append the object to the state list
            new_state.torrents.append(new_torrent)
        statefile = cPickle.load(statefile_handler);
    
    #get list of all subdirfiles
    allfiles=get_filepaths(contentPath)
    
    #begin processing
    i = 0
    target_path = None
    change = False
    for t in statefile.torrents:
        print i, t.filename;
        i+=1
        found = False
        #abort counter
        counter = 0
        files = lt.torrent_info(configPath+t.torrent_id+".torrent").files()
        #for all fileentries in BitTorrent .torrent Metafile
        for file in files:
            counter +=1
            if counter > 10:
                print "NOT FOUND: Aborting current file"
                break
            if found: break;
            
            #traverse list of allfiles
            for abspath in allfiles:
                if file.path in abspath:
                    found = True

                    #has unclean suffix?
                    for suffix in UNCLEANSUFFIXES: