Esempio n. 1
0
def test_create_invalid_tdef():
    """
    Test whether creating invalid TorrentDef objects result in ValueErrors
    """
    invalid_metainfo = {}
    with pytest.raises(ValueError):
        TorrentDef.load_from_memory(bencode(invalid_metainfo))

    invalid_metainfo = {b'info': {}}
    with pytest.raises(ValueError):
        TorrentDef.load_from_memory(bencode(invalid_metainfo))
    async def test_create_torrent(self):
        """
        Testing whether the API returns a proper base64 encoded torrent
        """
        torrent_path = self.files_path / "video.avi.torrent"
        expected_tdef = TorrentDef.load(torrent_path)
        export_dir = self.temporary_directory()

        post_data = {
            "files": [self.files_path / "video.avi",
                      self.files_path / "video.avi.torrent"],
            "description": "Video of my cat",
            "trackers": "http://localhost/announce",
            "name": "test_torrent",
            "export_dir": export_dir
        }
        response_dict = await self.do_request('createtorrent?download=1', 200, None, 'POST', post_data)
        torrent = base64.b64decode(response_dict["torrent"])
        tdef = TorrentDef.load_from_memory(torrent)

        # Copy expected creation date and created by (Tribler version) from actual result
        creation_date = tdef.get_creation_date()
        expected_tdef.metainfo[b"creation date"] = creation_date
        expected_tdef.metainfo[b"created by"] = tdef.metainfo[b'created by']

        self.assertEqual(dir(expected_tdef), dir(tdef))
        self.assertTrue((export_dir / "test_torrent.torrent").exists())
Esempio n. 3
0
 def get_metainfo(infohash, timeout=20, hops=None, url=None):
     if hops is not None:
         hops_list.append(hops)
     with open(TESTS_DATA_DIR / "ubuntu-15.04-desktop-amd64.iso.torrent",
               mode='rb') as torrent_file:
         torrent_data = torrent_file.read()
     tdef = TorrentDef.load_from_memory(torrent_data)
     assert url
     assert url == unquote_plus(path)
     return succeed(tdef.get_metainfo())
Esempio n. 4
0
    async def add_torrent_to_channel(self, request):
        channel_pk, channel_id = self.get_channel_from_request(request)
        with db_session:
            channel = self.session.mds.CollectionNode.get(
                public_key=database_blob(channel_pk), id_=channel_id)
        if not channel:
            return RESTResponse({"error": "Unknown channel"},
                                status=HTTP_NOT_FOUND)

        parameters = await request.json()

        extra_info = {}
        if parameters.get('description', None):
            extra_info = {'description': parameters['description']}

        # First, check whether we did upload a magnet link or URL
        if parameters.get('uri', None):
            uri = parameters['uri']
            if uri.startswith("http:") or uri.startswith("https:"):
                async with ClientSession() as session:
                    response = await session.get(uri)
                    data = await response.read()
                tdef = TorrentDef.load_from_memory(data)
            elif uri.startswith("magnet:"):
                _, xt, _ = parse_magnetlink(uri)
                if (xt and is_infohash(codecs.encode(xt, 'hex')) and
                    (self.session.mds.torrent_exists_in_personal_channel(xt)
                     or channel.copy_torrent_from_infohash(xt))):
                    return RESTResponse({"added": 1})

                meta_info = await self.session.dlmgr.get_metainfo(xt,
                                                                  timeout=30,
                                                                  url=uri)
                if not meta_info:
                    raise RuntimeError("Metainfo timeout")
                tdef = TorrentDef.load_from_dict(meta_info)
            else:
                return RESTResponse({"error": "unknown uri type"},
                                    status=HTTP_BAD_REQUEST)

            added = 0
            if tdef:
                channel.add_torrent_to_channel(tdef, extra_info)
                added = 1
            return RESTResponse({"added": added})

        torrents_dir = None
        if parameters.get('torrents_dir', None):
            torrents_dir = parameters['torrents_dir']
            if not path_util.isabs(torrents_dir):
                return RESTResponse(
                    {"error": "the torrents_dir should point to a directory"},
                    status=HTTP_BAD_REQUEST)

        recursive = False
        if parameters.get('recursive'):
            recursive = parameters['recursive']
            if not torrents_dir:
                return RESTResponse(
                    {
                        "error":
                        "the torrents_dir parameter should be provided when the recursive parameter is set"
                    },
                    status=HTTP_BAD_REQUEST,
                )

        if torrents_dir:
            torrents_list, errors_list = channel.add_torrents_from_dir(
                torrents_dir, recursive)
            return RESTResponse({
                "added": len(torrents_list),
                "errors": errors_list
            })

        if not parameters.get('torrent', None):
            return RESTResponse({"error": "torrent parameter missing"},
                                status=HTTP_BAD_REQUEST)

        # Try to parse the torrent data
        # Any errors will be handled by the error_middleware
        torrent = base64.b64decode(parameters['torrent'])
        torrent_def = TorrentDef.load_from_memory(torrent)
        channel.add_torrent_to_channel(torrent_def, extra_info)
        return RESTResponse({"added": 1})
Esempio n. 5
0
 def fake_get_metainfo(*_, **__):
     with open(TESTS_DIR / 'data/sample_channel/channel.torrent',
               mode='rb') as torrent_file:
         torrent_data = torrent_file.read()
     tdef = TorrentDef.load_from_memory(torrent_data)
     return succeed(tdef.get_metainfo())