Ejemplo n.º 1
0
async def test_number_hops_validation():
    assert DownloadDefaultsSettings(number_hops=1)

    with pytest.raises(ValueError):
        DownloadDefaultsSettings(number_hops=-1)

    with pytest.raises(ValueError):
        DownloadDefaultsSettings(number_hops=4)
Ejemplo n.º 2
0
class TriblerConfigSections(BaseSettings):
    """ Base Tribler config class that contains section listing.
    """
    class Config:
        extra = Extra.ignore  # ignore extra attributes during model initialization

    general: GeneralSettings = GeneralSettings()
    tunnel_community: TunnelCommunitySettings = TunnelCommunitySettings()
    bandwidth_accounting: BandwidthAccountingSettings = BandwidthAccountingSettings(
    )
    bootstrap: BootstrapSettings = BootstrapSettings()
    ipv8: Ipv8Settings = Ipv8Settings()
    discovery_community: DiscoveryCommunitySettings = DiscoveryCommunitySettings(
    )
    dht: DHTSettings = DHTSettings()
    trustchain: TrustchainSettings = TrustchainSettings()
    watch_folder: WatchFolderSettings = WatchFolderSettings()
    chant: ChantSettings = ChantSettings()
    torrent_checking: TorrentCheckerSettings = TorrentCheckerSettings()
    libtorrent: LibtorrentSettings = LibtorrentSettings()
    download_defaults: DownloadDefaultsSettings = DownloadDefaultsSettings()
    api: APISettings = APISettings()
    resource_monitor: ResourceMonitorSettings = ResourceMonitorSettings()
    popularity_community: PopularityCommunitySettings = PopularityCommunitySettings(
    )
    remote_query_community: RemoteQueryCommunitySettings = RemoteQueryCommunitySettings(
    )
Ejemplo n.º 3
0
    def __init__(self,
                 state_dir,
                 notifier: Notifier,
                 peer_mid: bytes,
                 config: LibtorrentSettings = None,
                 download_defaults: DownloadDefaultsSettings = None,
                 bootstrap_infohash=None,
                 socks_listen_ports: Optional[List[int]] = None,
                 dummy_mode: bool = False):
        super().__init__()
        self.dummy_mode = dummy_mode
        self._logger = logging.getLogger(self.__class__.__name__)

        self.state_dir = state_dir
        self.ltsettings = {
        }  # Stores a copy of the settings dict for each libtorrent session
        self.ltsessions = {}
        self.dht_health_manager = None
        self.listen_ports = {}

        self.socks_listen_ports = socks_listen_ports

        # TODO: Remove the dependency on notifier and refactor it to instead use callbacks injection
        self.notifier = notifier
        self.peer_mid = peer_mid
        self.config = config or LibtorrentSettings()
        self.bootstrap_infohash = bootstrap_infohash
        self.download_defaults = download_defaults or DownloadDefaultsSettings(
        )
        self._libtorrent_port = None

        self.set_upload_rate_limit(0)
        self.set_download_rate_limit(0)

        self.downloads = {}

        self.metadata_tmpdir = None
        # Dictionary that maps infohashes to download instances. These include only downloads that have
        # been made specifically for fetching metainfo, and will be removed afterwards.
        self.metainfo_requests = {}
        self.metainfo_cache = {
        }  # Dictionary that maps infohashes to cached metainfo items

        self.default_alert_mask = lt.alert.category_t.error_notification | lt.alert.category_t.status_notification | \
                                  lt.alert.category_t.storage_notification | lt.alert.category_t.performance_warning | \
                                  lt.alert.category_t.tracker_notification | lt.alert.category_t.debug_notification
        self.session_stats_callback = None
        self.state_cb_count = 0

        # Status of libtorrent session to indicate if it can safely close and no pending writes to disk exists.
        self.lt_session_shutdown_ready = {}
        self._dht_ready_task = None
        self.dht_readiness_timeout = self.config.dht_readiness_timeout if not self.dummy_mode else 0
        self._last_states_list = []
Ejemplo n.º 4
0
async def test_create_torrent(rest_api, tmp_path, endpoint):
    """
    Testing whether the API returns a proper base64 encoded torrent
    """
    def fake_create_torrent_file(*_, **__):
        with open(TESTS_DATA_DIR / "bak_single.torrent",
                  mode='rb') as torrent_file:
            encoded_metainfo = torrent_file.read()
        return succeed({
            "metainfo": encoded_metainfo,
            "base_dir": str(tmp_path)
        })

    endpoint.download_manager.download_defaults = DownloadDefaultsSettings()
    endpoint.download_manager.create_torrent_file = fake_create_torrent_file
    endpoint.download_manager.start_download = start_download = Mock()

    torrent_path = tmp_path / "video.avi.torrent"
    post_data = {
        "files": [
            str(torrent_path / "video.avi"),
            str(torrent_path / "video.avi.torrent")
        ],
        "description":
        "Video of my cat",
        "trackers":
        "http://localhost/announce",
        "name":
        "test_torrent",
        "export_dir":
        str(tmp_path)
    }
    response_dict = await do_request(rest_api,
                                     'createtorrent?download=1',
                                     expected_code=200,
                                     request_type='POST',
                                     post_data=post_data)
    assert response_dict["torrent"]
    assert start_download.call_args[1]['config'].get_hops(
    ) == DownloadDefaultsSettings().number_hops  # pylint: disable=unsubscriptable-object
Ejemplo n.º 5
0
    def __init__(self,
                 tdef: TorrentDef,
                 config: DownloadConfig = None,
                 download_defaults: DownloadDefaultsSettings = None,
                 notifier: Notifier = None,
                 state_dir: Path = None,
                 download_manager=None,
                 checkpoint_disabled=False,
                 hidden=False,
                 dummy=False):
        super().__init__()

        self._logger = logging.getLogger(self.__class__.__name__)

        self.dummy = dummy
        self.tdef = tdef
        self.handle = None
        self.state_dir = state_dir
        self.dlmgr = download_manager
        self.download_defaults = download_defaults or DownloadDefaultsSettings(
        )
        self.notifier = notifier

        # With hidden True download will not be in GET/downloads set, as a result will not be shown in GUI
        self.hidden = False

        # Libtorrent status
        self.lt_status = None
        self.error = None
        self.pause_after_next_hashcheck = False
        self.checkpoint_after_next_hashcheck = False
        self.tracker_status = {}  # {url: [num_peers, status_str]}
        self.checkpoint_disabled = self.dummy

        self.futures = defaultdict(list)
        self.alert_handlers = defaultdict(list)

        self.future_added = self.wait_for_alert('add_torrent_alert',
                                                lambda a: a.handle)
        self.future_removed = self.wait_for_alert('torrent_removed_alert')
        self.future_finished = self.wait_for_alert('torrent_finished_alert')
        self.future_metainfo = self.wait_for_alert(
            'metadata_received_alert', lambda a: self.tdef.get_metainfo())

        alert_handlers = {
            'tracker_reply_alert': self.on_tracker_reply_alert,
            'tracker_error_alert': self.on_tracker_error_alert,
            'tracker_warning_alert': self.on_tracker_warning_alert,
            'metadata_received_alert': self.on_metadata_received_alert,
            'performance_alert': self.on_performance_alert,
            'torrent_checked_alert': self.on_torrent_checked_alert,
            'torrent_finished_alert': self.on_torrent_finished_alert,
            'save_resume_data_alert': self.on_save_resume_data_alert,
            'state_changed_alert': self.on_state_changed_alert,
            'torrent_error_alert': self.on_torrent_error_alert,
            'add_torrent_alert': self.on_add_torrent_alert,
            'torrent_removed_alert': self.on_torrent_removed_alert
        }

        for alert_type, alert_handler in alert_handlers.items():
            self.register_alert_handler(alert_type, alert_handler)
        self.stream: Optional[Stream] = None

        self.hidden = hidden
        self.checkpoint_disabled = checkpoint_disabled or self.dummy
        self.config = config or DownloadConfig(state_dir=self.state_dir)

        self._logger.debug("Setup: %s", hexlify(self.tdef.get_infohash()))

        self.checkpoint()
Ejemplo n.º 6
0
async def test_seeding_mode():
    assert DownloadDefaultsSettings(seeding_mode=SeedingMode.forever)

    with pytest.raises(ValueError):
        DownloadDefaultsSettings(seeding_mode='')