示例#1
0
    def test_set_settings(self):
        """
        Testing whether settings in the API can be successfully set
        """
        download = DownloadConfigInterface()
        download.get_credit_mining = lambda: False
        self.session.get_downloads = lambda: [download]

        def verify_response1(_):
            self.assertEqual(download.get_seeding_mode(), 'time')
            self.assertEqual(download.get_seeding_time(), 100)

        self.should_check_equality = False
        post_data = json.dumps({'libtorrent': {'utp': False, 'max_download_rate': 50},
                                'download_defaults': {'seeding_mode': 'time', 'seeding_time': 100}})
        yield self.do_request('settings', expected_code=200, request_type='POST', raw_data=post_data) \
            .addCallback(verify_response1)

        def verify_response2(_):
            self.assertEqual(download.get_seeding_mode(), 'ratio')
            self.assertEqual(download.get_seeding_ratio(), 3)

        post_data = json.dumps({'download_defaults': {'seeding_mode': 'ratio', 'seeding_ratio': 3}})
        yield self.do_request('settings', expected_code=200, request_type='POST', raw_data=post_data) \
            .addCallback(verify_response2)

        download.get_credit_mining = lambda: True

        def verify_response3(_):
            self.assertNotEqual(download.get_seeding_mode(), 'never')

        post_data = json.dumps({'download_defaults': {'seeding_mode': 'never'}})
        yield self.do_request('settings', expected_code=200, request_type='POST', raw_data=post_data) \
            .addCallback(verify_response3)
示例#2
0
        def on_got_metainfo(metainfo):
            if not isinstance(metainfo, dict) or 'info' not in metainfo:
                self._logger.warning("Received metainfo is not a valid dictionary")
                request.setResponseCode(http.INTERNAL_SERVER_ERROR)
                request.write(json.dumps({"error": 'invalid response'}))
                self.finish_request(request)
                return

            infohash = hashlib.sha1(bencode(metainfo['info'])).digest()

            # Check if the torrent is already in the downloads
            metainfo['download_exists'] = infohash in self.session.lm.downloads

            # Update the torrent database with metainfo if it is an unnamed torrent
            if self.session.lm.torrent_db:
                self.session.lm.torrent_db.update_torrent_with_metainfo(infohash, metainfo)
                self.session.lm.torrent_db._db.commit_now()

            # Save the torrent to our store
            try:
                self.session.save_collected_torrent(infohash, bencode(metainfo))
            except TypeError:
                # Note: in libtorrent 1.1.1, bencode throws a TypeError which is a known bug
                pass

            request.write(json.dumps({"metainfo": metainfo}, ensure_ascii=False))
            self.finish_request(request)
示例#3
0
    def render_GET(self, request):
        """
        .. http:get:: /search/completions?q=(string:query)

        A GET request to this endpoint will return autocompletion suggestions for the given query. For instance,
        when searching for "pioneer", this endpoint might return "pioneer one" if that torrent is present in the
        local database. This endpoint can be used to suggest terms to users while they type their search query.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/search/completions?q=pioneer

            **Example response**:

            .. sourcecode:: javascript

                {
                    "completions": ["pioneer one", "pioneer movie"]
                }
        """
        if 'q' not in request.args:
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "query parameter missing"})

        keywords = unicode(request.args['q'][0], 'utf-8').lower()
        results = self.torrent_db_handler.getAutoCompleteTerms(keywords, max_terms=5)
        results.extend(self.session.lm.mds.TorrentMetadata.get_auto_complete_terms(keywords, max_terms=5))
        return json.dumps({"completions": results})
示例#4
0
    def render_PUT(self, request):
        """
        .. http:put:: /channels/discovered/(string: channelid)/rssfeeds/http%3A%2F%2Ftest.com%2Frss.xml

        Add a RSS feed to your channel. Returns error 409 if the supplied RSS feed already exists.
        Note that the rss feed url should be URL-encoded.

            **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/channels/discovered/abcd/rssfeeds/http%3A%2F%2Ftest.com%2Frss.xml

            **Example response**:

            .. sourcecode:: javascript

                {
                    "added": True
                }

            :statuscode 409: (conflict) if the specified RSS URL is already present in your feeds.
        """
        channel_obj, error = self.get_my_channel_obj_or_error(request)
        if channel_obj is None:
            return error

        if self.feed_url in channel_obj.get_rss_feed_url_list():
            request.setResponseCode(http.CONFLICT)
            return json.dumps({"error": "this rss feed already exists"})

        channel_obj.create_rss_feed(self.feed_url)
        return json.dumps({"added": True})
示例#5
0
    def render_POST(self, request):
        """
        .. http:get:: /market/orders/(string:order_number)/cancel

        A POST request to this endpoint will cancel a specific order.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/market/orders/3/cancel

            **Example response**:

            .. sourcecode:: javascript

                {
                    "cancelled": True
                }
        """
        market_community = self.get_market_community()
        order_id = OrderId(TraderId(market_community.mid), OrderNumber(int(self.order_number)))
        order = market_community.order_manager.order_repository.find_by_id(order_id)

        if not order:
            request.setResponseCode(http.NOT_FOUND)
            return json.dumps({"error": "order not found"})

        if order.status != "open" and order.status != "unverified":
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "only open and unverified orders can be cancelled"})

        market_community.cancel_order(order_id)

        return json.dumps({"cancelled": True})
示例#6
0
    def render_PUT(self, request):
        """
        .. http:put:: /market/asks

        A request to this endpoint will create a new ask order.

            **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/market/asks --data
                "first_asset_amount=10&second_asset_amount=10&first_asset_type=BTC&second_asset_type=MB"

            **Example response**:

            .. sourcecode:: javascript

                {
                     "timestamp": 1547587907.887339,
                     "order_number": 12,
                     "assets": {
                        "second": {
                            "amount": 1000,
                            "type": "MB"
                        },
                        "first": {
                            "amount": 100000,
                            "type": "BTC"
                        }
                    },
                    "timeout": 3600,
                    "trader_id": "9695c9e15201d08586e4230f4a8524799ebcb2d7"
                }
        """
        parameters = http.parse_qs(request.content.read(), 1)

        if not has_param(parameters, 'first_asset_amount') or not has_param(parameters, 'second_asset_amount'):
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "asset amount parameter missing"})

        if not has_param(parameters, 'first_asset_type') or not has_param(parameters, 'second_asset_type'):
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "asset type parameter missing"})

        def on_ask_created(ask):
            if not request.finished:
                request.write(json.dumps({
                    'assets': ask.assets.to_dictionary(),
                    'timestamp': float(ask.timestamp),
                    'trader_id': str(ask.order_id.trader_id),
                    'order_number': int(ask.order_id.order_number),
                    'timeout': int(ask.timeout)
                }))
                request.finish()

        self.get_market_community().create_ask(*BaseAsksBidsEndpoint.create_ask_bid_from_params(parameters))\
            .addCallback(on_ask_created)

        return NOT_DONE_YET
    def render_PUT(self, request):
        """
        .. http:put:: /channels/discovered/(string: channelid)/playlists/(int: playlistid)/(string: infohash)

        Add a torrent with a specified infohash to a specified playlist. The torrent that is added to the playlist,
        should be present in the channel.

            **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/channels/discovered/abcd/playlists/3/abcdef

            **Example response**:

            .. sourcecode:: javascript

                {
                    "added": True
                }

            :statuscode 404: if the specified channel/playlist/torrent does not exist.
            :statuscode 409: if the specified torrent is already in the specified playlist.
        """
        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsPlaylistsEndpoint.return_404(request)

        channel_community = self.get_community_for_channel_id(channel_info[0])
        if channel_community is None:
            return BaseChannelsEndpoint.return_404(request,
                                                   message="the community for the specific channel cannot be found")

        playlist = self.channel_db_handler.getPlaylist(self.playlist_id, ['Playlists.dispersy_id'])
        if playlist is None:
            return BaseChannelsEndpoint.return_404(request, message="this playlist cannot be found")

        # Check whether this torrent is present in your channel
        torrent_in_channel = False
        for torrent in self.channel_db_handler.getTorrentsFromChannelId(channel_info[0], True, ["infohash"]):
            if torrent[0] == self.infohash:
                torrent_in_channel = True
                break

        if not torrent_in_channel:
            return BaseChannelsEndpoint.return_404(request, message="this torrent is not available in your channel")

        # Check whether this torrent is not already present in this playlist
        for torrent in self.channel_db_handler.getTorrentsFromPlaylist(self.playlist_id, ["infohash"]):
            if torrent[0] == self.infohash:
                request.setResponseCode(http.CONFLICT)
                return json.dumps({"error": "this torrent is already in your playlist"})

        channel_community.create_playlist_torrents(int(self.playlist_id), [self.infohash])

        return json.dumps({"added": True})
    def render_PUT(self, request):
        """
        .. http:put:: /channels/subscribed/(string: channelid)

        Subscribe to a specific channel. Returns error 409 if you are already subscribed to this channel.

            **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/channels/subscribed/da69aaad39ccf468aba2ab9177d5f8d8160135e6

            **Example response**:

            .. sourcecode:: javascript

                {
                    "subscribed" : True
                }

            :statuscode 409: (conflict) if you are already subscribed to the specified channel.
        """
        request.setHeader('Content-Type', 'text/json')

        if self.session.config.get_chant_channel_edit():
            with db_session:
                channel = self.session.lm.mds.ChannelMetadata.get(public_key=buffer(self.cid))
                if not channel:
                    request.setResponseCode(http.NOT_FOUND)
                    return json.dumps({"error": CHANNEL_NOT_FOUND})

                if channel.subscribed:
                    request.setResponseCode(http.CONFLICT)
                    return json.dumps({"error": ALREADY_SUBSCRIBED_RESPONSE_MSG})
                channel.subscribed = True

            return json.dumps({"subscribed": True})

        channel_info = self.get_channel_from_db(self.cid)

        if channel_info is not None and channel_info[7] == VOTE_SUBSCRIBE:
            request.setResponseCode(http.CONFLICT)
            return json.dumps({"error": ALREADY_SUBSCRIBED_RESPONSE_MSG})

        def on_vote_done(_):
            request.write(json.dumps({"subscribed": True}))
            request.finish()

        def on_vote_error(failure):
            request.processingFailed(failure)

        self.vote_for_channel(self.cid, VOTE_SUBSCRIBE).addCallback(on_vote_done).addErrback(on_vote_error)

        return NOT_DONE_YET
示例#9
0
    def render_GET(self, request):
        """
        .. http:get:: /mychannel

        Return the name, description and identifier of your channel.
        This endpoint returns a 404 HTTP response if you have not created a channel (yet).

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/mychannel

            **Example response**:

            .. sourcecode:: javascript

                {
                    "overview": {
                        "name": "My Tribler channel",
                        "description": "A great collection of open-source movies",
                        "identifier": "4a9cfc7ca9d15617765f4151dd9fae94c8f3ba11"
                    }
                }

            :statuscode 404: if your channel has not been created (yet).
        """
        if self.session.config.get_chant_channel_edit():
            my_channel_id = self.session.trustchain_keypair.pub().key_to_bin()
            with db_session:
                my_channel = self.session.lm.mds.ChannelMetadata.get_channel_with_id(my_channel_id)

                if not my_channel:
                    request.setResponseCode(http.NOT_FOUND)
                    return json.dumps({"error": NO_CHANNEL_CREATED_RESPONSE_MSG})

                my_channel = my_channel.to_dict()
            return json.dumps({
                'mychannel': {
                    'identifier': str(my_channel["public_key"]).encode('hex'),
                    'name': my_channel["title"],
                    'description': my_channel["tags"],
                    'chant': True
                }})
        else:
            my_channel_id = self.channel_db_handler.getMyChannelId()
            if my_channel_id is None:
                request.setResponseCode(http.NOT_FOUND)
                return json.dumps({"error": NO_CHANNEL_CREATED_RESPONSE_MSG})

            my_channel = self.channel_db_handler.getChannel(my_channel_id)

            return json.dumps({'mychannel': {'identifier': my_channel[1].encode('hex'), 'name': my_channel[2],
                                             'description': my_channel[3]}})
    def render_POST(self, request):
        """
        .. http:post:: /channels/discovered/(string: channelid)/playlists/(int: playlistid)

        Edit a specific playlist. The new name and description should be passed as parameter.

            **Example request**:

            .. sourcecode:: none

                curl -X POST http://localhost:8085/channels/discovered/abcd/playlists/3
                --data "name=test&description=my test description"

            **Example response**:

            .. sourcecode:: javascript

                {
                    "modified": True
                }

            :statuscode 404: if the specified channel (community) or playlist does not exist or if the
            name and description parameters are missing.
        """
        parameters = http.parse_qs(request.content.read(), 1)

        if 'name' not in parameters or len(parameters['name']) == 0:
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "name parameter missing"})

        if 'description' not in parameters or len(parameters['description']) == 0:
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "description parameter missing"})

        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsPlaylistsEndpoint.return_404(request)

        playlist = self.channel_db_handler.getPlaylist(self.playlist_id, ['Playlists.id'])
        if playlist is None:
            return BaseChannelsEndpoint.return_404(request, message="this playlist cannot be found")

        channel_community = self.get_community_for_channel_id(channel_info[0])
        if channel_community is None:
            return BaseChannelsEndpoint.return_404(request,
                                                   message="the community for the specific channel cannot be found")

        channel_community.modifyPlaylist(playlist[0], {'name': parameters['name'][0],
                                                       'description': parameters['description'][0]})

        return json.dumps({"modified": True})
示例#11
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/circuits

        A GET request to this endpoint returns information about the built circuits in the tunnel community.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/circuits

            **Example response**:

            .. sourcecode:: javascript

                {
                    "circuits": [{
                        "id": 1234,
                        "state": "EXTENDING",
                        "goal_hops": 4,
                        "bytes_up": 45,
                        "bytes_down": 49,
                        "created": 1468176257,
                        "hops": [{
                            "host": "unknown"
                        }, {
                            "host": "39.95.147.20:8965"
                        }],
                        ...
                    }, ...]
                }
        """
        tunnel_community = self.session.lm.tunnel_community
        if not tunnel_community:
            request.setResponseCode(http.NOT_FOUND)
            return json.dumps({"error": "tunnel community not found"})

        circuits_json = []
        for circuit_id, circuit in tunnel_community.circuits.iteritems():
            item = {'id': circuit_id, 'state': str(circuit.state), 'goal_hops': circuit.goal_hops,
                    'bytes_up': circuit.bytes_up, 'bytes_down': circuit.bytes_down, 'created': circuit.creation_time}
            hops_array = []
            for hop in circuit.hops:
                hops_array.append({'host': 'unknown' if 'UNKNOWN HOST' in hop.host else '%s:%s' % (hop.host, hop.port)})

            item['hops'] = hops_array
            circuits_json.append(item)

        return json.dumps({'circuits': circuits_json})
    def render_DELETE(self, request):
        """
        .. http:delete:: /channels/discovered/(string: channelid)/playlists/(int: playlistid)/(string: infohash)

        Remove a torrent with a specified infohash from a specified playlist.

            **Example request**:

            .. sourcecode:: none

                curl -X DELETE http://localhost:8085/channels/discovered/abcd/playlists/3/abcdef

            **Example response**:

            .. sourcecode:: javascript

                {
                    "removed": True
                }

            :statuscode 404: if the specified channel/playlist/torrent does not exist.
        """
        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsPlaylistsEndpoint.return_404(request)

        playlist = self.channel_db_handler.getPlaylist(self.playlist_id, ['Playlists.dispersy_id'])
        if playlist is None:
            return BaseChannelsEndpoint.return_404(request, message="this playlist cannot be found")

        channel_community = self.get_community_for_channel_id(channel_info[0])
        if channel_community is None:
            return BaseChannelsEndpoint.return_404(request,
                                                   message="the community for the specific channel cannot be found")

        # Check whether this torrent is present in this playlist and if so, get the dispersy ID
        torrent_dispersy_id = -1
        for torrent in self.channel_db_handler.getTorrentsFromPlaylist(self.playlist_id,
                                                                       ["infohash", "PlaylistTorrents.dispersy_id"]):
            if torrent[0] == self.infohash:
                torrent_dispersy_id = torrent[1]
                break

        if torrent_dispersy_id == -1:
            request.setResponseCode(http.NOT_FOUND)
            return json.dumps({"error": "this torrent is not in your playlist"})

        channel_community.remove_playlist_torrents(int(self.playlist_id), [torrent_dispersy_id])

        return json.dumps({"removed": True})
示例#13
0
 def on_mdblob(filename):
     try:
         with open(filename, 'rb') as f:
             serialized_data = f.read()
         payload = read_payload(serialized_data)
         if payload.metadata_type not in [REGULAR_TORRENT, CHANNEL_TORRENT]:
             request.setResponseCode(http.INTERNAL_SERVER_ERROR)
             return json.dumps({"error": "Non-torrent metadata type"})
         magnet = payload.get_magnet()
     except InvalidSignatureException:
         request.setResponseCode(http.INTERNAL_SERVER_ERROR)
         return json.dumps({"error": "metadata has incorrect signature"})
     else:
         return on_magnet(magnet)
示例#14
0
    def write_data(self, message):
        """
        Write data over the event socket if it's open.
        """
        try:
            message_str = json.dumps(message)
        except UnicodeDecodeError:
            # The message contains invalid characters; fix them
            message_str = json.dumps(fix_unicode_dict(message))

        if len(self.events_requests) == 0:
            return
        else:
            [request.write(message_str + '\n') for request in self.events_requests]
    def render_PUT(self, request):
        """
        .. http:put:: /channels/discovered/(string: channelid)/playlists

        Create a new empty playlist with a given name and description. The name and description parameters are
        mandatory.

            **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/channels/discovered/abcd/playlists
                --data "name=My fancy playlist&description=This playlist contains some random movies"

            **Example response**:

            .. sourcecode:: javascript

                {
                    "created": True
                }

            :statuscode 400: if you are missing the name and/or description parameter
            :statuscode 404: if the specified channel does not exist
        """
        parameters = http.parse_qs(request.content.read(), 1)

        if 'name' not in parameters or len(parameters['name']) == 0:
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "name parameter missing"})

        if 'description' not in parameters or len(parameters['description']) == 0:
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps({"error": "description parameter missing"})

        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsPlaylistsEndpoint.return_404(request)

        channel_community = self.get_community_for_channel_id(channel_info[0])
        if channel_community is None:
            return BaseChannelsEndpoint.return_404(request,
                                                   message="the community for the specific channel cannot be found")

        channel_community.create_playlist(unicode(parameters['name'][0], 'utf-8'),
                                          unicode(parameters['description'][0], 'utf-8'), [])

        return json.dumps({"created": True})
示例#16
0
def _safe_extended_peer_info(ext_peer_info):
    """
    Given a string describing peer info, return a JSON.dumps() safe representation.

    :param ext_peer_info: the string to convert to a dumpable format
    :return: the safe string
    """
    # First see if we can use this as-is
    if not ext_peer_info:
        ext_peer_info = u''
    try:
        json.dumps(ext_peer_info)
        return ext_peer_info
    except UnicodeDecodeError:
        # We might have some special unicode characters in here
        return u''.join([unichr(ord(c)) for c in ext_peer_info])
示例#17
0
    def on_emptying_tokens(self, data):
        if not data:
            return
        json_data = json.dumps(data)

        if has_qr:
            self.empty_tokens_barcode_dialog = QWidget()
            self.empty_tokens_barcode_dialog.setWindowTitle("Please scan the following QR code")
            self.empty_tokens_barcode_dialog.setGeometry(10, 10, 500, 500)
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_M,
                box_size=10,
                border=5,
            )
            qr.add_data(json_data)
            qr.make(fit=True)

            img = qr.make_image()  # PIL format

            qim = ImageQt(img)
            pixmap = QtGui.QPixmap.fromImage(qim).scaled(600, 600, QtCore.Qt.KeepAspectRatio)
            label = QLabel(self.empty_tokens_barcode_dialog)
            label.setPixmap(pixmap)
            self.empty_tokens_barcode_dialog.resize(pixmap.width(), pixmap.height())
            self.empty_tokens_barcode_dialog.show()
        else:
            ConfirmationDialog.show_error(self.window(), DEPENDENCY_ERROR_TITLE, DEPENDENCY_ERROR_MESSAGE)
示例#18
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/memory/history

        A GET request to this endpoint returns information about memory usage history in the form of a list.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/memory/history

            **Example response**:

            .. sourcecode:: javascript

                {
                    "memory_history": [{
                        "time": 1504015291214,
                        "mem": 324324,
                    }, ...]
                }
        """
        history = self.session.lm.resource_monitor.get_memory_history_dict() if self.session.lm.resource_monitor else {}
        return json.dumps({"memory_history": history})
    def render_GET(self, request):
        """
        .. http:get:: /channels/discovered/(string: channelid)

        Return the name, description and identifier of a channel.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/channels/discovered/4a9cfc7ca9d15617765f4151dd9fae94c8f3ba11

            **Example response**:

            .. sourcecode:: javascript

                {
                    "overview": {
                        "name": "My Tribler channel",
                        "description": "A great collection of open-source movies",
                        "identifier": "4a9cfc7ca9d15617765f4151dd9fae94c8f3ba11"
                    }
                }

            :statuscode 404: if your channel has not been created (yet).
        """
        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsDiscoveredSpecificEndpoint.return_404(request)

        return json.dumps({'overview': {'identifier': channel_info[1].encode('hex'), 'name': channel_info[2],
                                        'description': channel_info[3]}})
示例#20
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/circuits/slots

        A GET request to this endpoint returns information about the slots in the tunnel overlay.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/circuits/slots

            **Example response**:

            .. sourcecode:: javascript

                {
                    "open_files": [{
                        "path": "path/to/open/file.txt",
                        "fd": 33,
                    }, ...]
                }
        """
        return json.dumps({
            "slots": {
                "random": self.session.lm.tunnel_community.random_slots,
                "competing": self.session.lm.tunnel_community.competing_slots
            }
        })
示例#21
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/open_files

        A GET request to this endpoint returns information about files opened by Tribler.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/open_files

            **Example response**:

            .. sourcecode:: javascript

                {
                    "open_files": [{
                        "path": "path/to/open/file.txt",
                        "fd": 33,
                    }, ...]
                }
        """
        my_process = psutil.Process()

        return json.dumps({
            "open_files": [{"path": open_file.path, "fd": open_file.fd} for open_file in my_process.open_files()]})
示例#22
0
    def render_DELETE(self, request):
        """
        .. http:delete:: /channels/discovered/(string: channelid)/rssfeeds/http%3A%2F%2Ftest.com%2Frss.xml

        Delete a RSS feed from your channel. Returns error 404 if the RSS feed that is being removed does not exist.
        Note that the rss feed url should be URL-encoded.

            **Example request**:

            .. sourcecode:: none

                curl -X DELETE http://localhost:8085/channels/discovered/abcd/rssfeeds/http%3A%2F%2Ftest.com%2Frss.xml

            **Example response**:

            .. sourcecode:: javascript

                {
                    "removed": True
                }

            :statuscode 404: if the specified RSS URL is not in your feed list.
        """
        channel_obj, error = self.get_my_channel_obj_or_error(request)
        if channel_obj is None:
            return error

        if self.feed_url not in channel_obj.get_rss_feed_url_list():
            return ChannelModifyRssFeedEndpoint.return_404(request, message="this url is not added to your RSS feeds")

        channel_obj.remove_rss_feed(self.feed_url)
        return json.dumps({"removed": True})
示例#23
0
 def _on_download_readded(_):
     """
     Success callback
     """
     request.write(json.dumps({"modified": True,
                               "infohash": hexlify(download.get_def().get_infohash())}))
     request.finish()
示例#24
0
    def render_GET(self, request):
        """
        .. http:get:: /market/matchmakers

        A GET request to this endpoint will return all known matchmakers.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/market/matchmakers

            **Example response**:

            .. sourcecode:: javascript

                {
                    "matchmakers": [{
                        "ip": "131.249.48.3",
                        "port": 7008
                    }]
                }
        """
        matchmakers = self.session.lm.market_community.matchmakers
        matchmakers_json = [{"ip": mm.address[0], "port": mm.address[1]} for mm in matchmakers]
        return dumps({"matchmakers": matchmakers_json})
示例#25
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/threads

        A GET request to this endpoint returns information about running threads.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/threads

            **Example response**:

            .. sourcecode:: javascript

                {
                    "threads": [{
                        "thread_id": 123456,
                        "thread_name": "my_thread",
                        "frames": ["my_frame", ...]
                    }, ...]
                }
        """
        watchdog = WatchDog()
        return json.dumps({"threads": watchdog.get_threads_info()})
示例#26
0
    def test_set_settings_no_key(self):
        """
        Testing whether an error is returned when we try to set a non-existing key
        """
        def verify_response(response):
            json_dict = json.loads(response)
            self.assertTrue('error' in json_dict)

        self.should_check_equality = False
        post_data = json.dumps({'general': {'b': 'c'}})
        yield self.do_request('settings', expected_code=500, request_type='POST', raw_data=post_data)\
            .addCallback(verify_response)

        post_data = json.dumps({'Tribler': {'b': 'c'}})
        yield self.do_request('settings', expected_code=500, request_type='POST', raw_data=post_data)\
            .addCallback(verify_response)
示例#27
0
 def _on_torrent_removed(_):
     """
     Success callback
     """
     request.write(json.dumps({"removed": True,
                               "infohash": hexlify(download.get_def().get_infohash())}))
     request.finish()
示例#28
0
    def render_GET(self, request):
        """
        .. http:get:: /download/(string: infohash)/files

        A GET request to this endpoint returns the file information of a specific download.

            **Example request**:

                .. sourcecode:: none

                    curl -X GET http://localhost:8085/downloads/4344503b7e797ebf31582327a5baae35b11bda01/files

            **Example response**:

            .. sourcecode:: javascript

                {
                    "files": [{
                        "index": 1,
                        "name": "test.txt",
                        "size": 12345,
                        "included": True,
                        "progress": 0.5448
                    }, ...]
                }
        """
        download = self.session.get_download(self.infohash)
        if not download:
            return DownloadExportTorrentEndpoint.return_404(request)

        return json.dumps({"files": self.get_files_info_json(download)})
    def render_GET(self, request):
        """
        .. http:get:: /channels/subscribed/(string: channelid)

        Shows the status of subscription to a specific channel along with number of existing votes in the channel

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/channels/subscribed/da69aaad39ccf468aba2ab9177d5f8d8160135e6

            **Example response**:

            .. sourcecode:: javascript

                {
                    "subscribed" : True, "votes": 111
                }
        """
        request.setHeader('Content-Type', 'text/json')
        channel_info = self.get_channel_from_db(self.cid)

        if channel_info is None:
            return ChannelsModifySubscriptionEndpoint.return_404(request)

        response = dict()
        response[u'subscribed'] = channel_info[7] == VOTE_SUBSCRIBE
        response[u'votes'] = channel_info[5]

        return json.dumps(response)
示例#30
0
    def render_GET(self, request):
        """
        .. http:get:: /channels/discovered/(string: channelid)/rssfeeds

        Returns the RSS feeds in your channel.

            .. sourcecode:: none

                curl -X GET http://localhost:8085/channels/discovered/abcd/rssfeeds

            **Example response**:

            .. sourcecode:: javascript

                {
                    "rssfeeds": [{
                        "url": "http://rssprovider.com/feed.xml",
                    }, ...]
                }
        """
        channel_obj, error = self.get_my_channel_obj_or_error(request)
        if channel_obj is None:
            return error

        request.setHeader('Content-Type', 'text/json')
        feeds_list = [{'url': rss_item} for rss_item in channel_obj.get_rss_feed_url_list()]

        return json.dumps({"rssfeeds": feeds_list})
示例#31
0
    def render_GET(self, request):
        """
        .. http:get:: /market/transactions

        A GET request to this endpoint will return all performed transactions in the market community.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/market/transactions

            **Example response**:

            .. sourcecode:: javascript

                {
                    "transactions": [{
                        "trader_id": "12c406358ba05e5883a75da3f009477e4ca699a9",
                        "order_number": 4,
                        "partner_trader_id": "34c406358ba05e5883a75da3f009477e4ca699a9",
                        "partner_order_number": 1,
                        "transaction_number": 3,
                        "assets" {
                            "first": {
                                "amount": 3,
                                "type": "BTC",
                            },
                            "second": {
                                "amount": 3,
                                "type": "MB",
                            }
                        },
                        "transferred" {
                            "first": {
                                "amount": 3,
                                "type": "BTC",
                            },
                            "second": {
                                "amount": 3,
                                "type": "MB",
                            }
                        }
                        "timestamp": 1493906434.627721,
                        "payment_complete": False
                    ]
                }
        """
        transactions = self.get_market_community(
        ).transaction_manager.find_all()
        return json.dumps({
            "transactions":
            [transaction.to_dictionary() for transaction in transactions]
        })
示例#32
0
 def on_bid_created(bid):
     if not request.finished:
         request.write(
             json.dumps({
                 'assets': bid.assets.to_dictionary(),
                 'timestamp': float(bid.timestamp),
                 'trader_id': str(bid.order_id.trader_id),
                 'order_number': int(bid.order_id.order_number),
                 'timeout': int(bid.timeout)
             }))
         request.finish()
示例#33
0
    def render_GET(self, request):
        """
        .. http:get:: /mychannel

        Return the name, description and identifier of your channel.
        This endpoint returns a 404 HTTP response if you have not created a channel (yet).

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/mychannel

            **Example response**:

            .. sourcecode:: javascript

                {
                    "overview": {
                        "name": "My Tribler channel",
                        "description": "A great collection of open-source movies",
                        "identifier": "4a9cfc7ca9d15617765f4151dd9fae94c8f3ba11"
                    }
                }

            :statuscode 404: if your channel has not been created (yet).
        """
        my_channel_id = self.channel_db_handler.getMyChannelId()
        if my_channel_id is None:
            request.setResponseCode(http.NOT_FOUND)
            return json.dumps({"error": NO_CHANNEL_CREATED_RESPONSE_MSG})

        my_channel = self.channel_db_handler.getChannel(my_channel_id)

        return json.dumps({
            'mychannel': {
                'identifier': my_channel[1].encode('hex'),
                'name': my_channel[2],
                'description': my_channel[3]
            }
        })
示例#34
0
 def on_file():
     try:
         filename = url2pathname(uri[5:].encode('utf-8') if isinstance(
             uri, text_type) else uri[5:])
         if filename.endswith(BLOB_EXTENSION):
             return on_mdblob(filename)
         metainfo_deferred.callback(bdecode(fix_torrent(filename)))
         return NOT_DONE_YET
     except TypeError:
         request.setResponseCode(http.INTERNAL_SERVER_ERROR)
         return json.dumps(
             {"error": "error while decoding torrent file"})
    def test_set_settings_invalid_dict(self):
        """
        Testing whether an error is returned if we are passing an invalid dictionary that is too deep
        """
        def verify_response(response):
            json_dict = json.loads(response)
            self.assertTrue('error' in json_dict)

        self.should_check_equality = False
        post_data = json.dumps({'a': {'b': {'c': 'd'}}})
        return self.do_request('settings', expected_code=500, request_type='POST', post_data=post_data, raw_data=True)\
            .addCallback(verify_response)
示例#36
0
 def _on_torrent_removed(_):
     """
     Success callback
     """
     request.write(
         json.dumps({
             "removed":
             True,
             "infohash":
             download.get_def().get_infohash().encode('hex')
         }))
     request.finish()
示例#37
0
 def save_to_file(self, filename, data):
     base_dir = QFileDialog.getExistingDirectory(
         self, "Select an export directory", "", QFileDialog.ShowDirsOnly)
     if len(base_dir) > 0:
         dest_path = os.path.join(base_dir, filename)
         try:
             torrent_file = open(dest_path, "wb")
             torrent_file.write(json.dumps(data))
             torrent_file.close()
         except IOError as exc:
             ConfirmationDialog.show_error(self.window(),
                                           "Error exporting file", str(exc))
示例#38
0
        def on_got_metainfo(metainfo):
            if not isinstance(metainfo, dict) or 'info' not in metainfo:
                self._logger.warning(
                    "Received metainfo is not a valid dictionary")
                request.setResponseCode(http.INTERNAL_SERVER_ERROR)
                request.write(json.dumps({"error": 'invalid response'}))
                self.finish_request(request)
                return

            infohash = hashlib.sha1(bencode(metainfo['info'])).digest()
            # Save the torrent to our store
            try:
                self.session.save_collected_torrent(infohash,
                                                    bencode(metainfo))
            except TypeError:
                # Note: in libtorrent 1.1.1, bencode throws a TypeError which is a known bug
                pass

            request.write(
                json.dumps({"metainfo": metainfo}, ensure_ascii=False))
            self.finish_request(request)
示例#39
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/log?process=<core|gui>&max_lines=<max_lines>

        A GET request to this endpoint returns a json with content of core or gui log file & max_lines requested

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/log?process=core&max_lines=5

            **Example response**:

            A JSON with content of the log file & max_lines requested, for eg.
            {
                "max_lines" : 5,
                "content" :"INFO    1506675301.76   sqlitecachedb:181   Reading database version...
                            INFO    1506675301.76   sqlitecachedb:185   Current database version is 29
                            INFO    1506675301.76   sqlitecachedb:203   Beginning the first transaction...
                            INFO    1506675301.76         upgrade:93    tribler is in the latest version,...
                            INFO    1506675302.08  LaunchManyCore:254   lmc: Starting Dispersy..."
            }

        """

        # First, flush all the logs to make sure it is written to file
        for handler in logging.getLogger().handlers:
            handler.flush()

        # Get the location of log file
        param_process = request.args['process'][0] if request.args[
            'process'] else 'core'
        log_file_name = os.path.join(self.session.config.get_log_dir(),
                                     'tribler-%s-info.log' % param_process)

        # Default response
        response = {'content': '', 'max_lines': 0}

        # Check if log file exists and return last requested 'max_lines' of log
        if os.path.exists(log_file_name):
            try:
                max_lines = int(request.args['max_lines'][0])
                with open(log_file_name, 'r') as log_file:
                    response['content'] = self.tail(log_file, max_lines)
                response['max_lines'] = max_lines
            except ValueError:
                with open(log_file_name, 'r') as log_file:
                    response['content'] = self.tail(log_file,
                                                    100)  # default 100 lines
                response['max_lines'] = 0

        return json.dumps(response)
示例#40
0
 def _on_download_readded(_):
     """
     Success callback
     """
     request.write(
         json.dumps({
             "modified":
             True,
             "infohash":
             download.get_def().get_infohash().encode('hex')
         }))
     request.finish()
示例#41
0
    def render_GET(self, request):
        """
        .. http:get:: /libtorrent/settings

        A GET request to this endpoint will return information about libtorrent.

            **Example request**:

                .. sourcecode:: none

                    curl -X GET http://localhost:8085/libtorrent/settings?hop=0

            **Example response**:

                .. sourcecode:: javascript

                    {
                        "hop": 0,
                        "settings": {
                            "urlseed_wait_retry": 30,
                            "enable_upnp": true,
                            ...
                            "send_socket_buffer_size": 0,
                            "lock_disk_cache": false,
                            "i2p_port": 0
                        }
                    }
        """
        hop = 0
        if 'hop' in request.args and request.args['hop']:
            hop = int(request.args['hop'][0])

        if hop not in self.session.lm.ltmgr.ltsessions:
            return json.dumps({'hop': hop, "settings": {}})

        lt_settings = self.session.lm.ltmgr.ltsessions[hop].get_settings()
        lt_settings['peer_fingerprint'] = lt_settings[
            'peer_fingerprint'].encode('hex')

        return json.dumps({'hop': hop, "settings": lt_settings})
示例#42
0
        def on_magnet(mlink=None):
            infohash = parse_magnetlink(mlink or uri)[1]
            if infohash is None:
                request.setResponseCode(http.BAD_REQUEST)
                return json.dumps({"error": "missing infohash"})

            self.session.lm.ltmgr.get_metainfo(
                mlink or uri,
                callback=metainfo_deferred.callback,
                timeout=20,
                timeout_callback=on_metainfo_timeout,
                notify=True)
            return NOT_DONE_YET
示例#43
0
 def on_search_results(search_results_tuple):
     search_results, total = search_results_tuple
     request.write(
         json.dumps({
             "uuid": search_uuid,
             "results": search_results,
             "first": sanitized["first"],
             "last": sanitized["last"],
             "sort_by": sanitized["sort_by"],
             "sort_asc": sanitized["sort_asc"],
             "total": total
         }))
     request.finish()
示例#44
0
    def render_POST(self, request):
        """
        .. http:get:: /market/orders/(string:order_number)/cancel

        A POST request to this endpoint will cancel a specific order.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/market/orders/3/cancel

            **Example response**:

            .. sourcecode:: javascript

                {
                    "cancelled": True
                }
        """
        market_community = self.get_market_community()
        order_id = OrderId(TraderId(market_community.mid),
                           OrderNumber(int(self.order_number)))
        order = market_community.order_manager.order_repository.find_by_id(
            order_id)

        if not order:
            request.setResponseCode(http.NOT_FOUND)
            return json.dumps({"error": "order not found"})

        if order.status != "open" and order.status != "unverified":
            request.setResponseCode(http.BAD_REQUEST)
            return json.dumps(
                {"error": "only open and unverified orders can be cancelled"})

        market_community.cancel_order(order_id)

        return json.dumps({"cancelled": True})
示例#45
0
    def render_GET(self, request):
        """
        .. http:get:: /multichain/statistics

        A GET request to this endpoint returns statistics about the multichain community

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/multichain/statistics

            **Example response**:

            .. sourcecode:: javascript

                {
                    "statistics":
                    {
                        "self_id": "TGliTmFDTFBLO...VGbxS406vrI=",
                        "latest_block_insert_time": "2016-08-04 12:01:53",
                        "self_total_blocks": 8537,
                        "latest_block_id": "Sv03SmkiuL+F4NWxHYdeB6PQeQa/p74EEVQoOVuSz+k=",
                        "latest_block_requester_id": "TGliTmFDTFBLO...nDwlVIk69tc=",
                        "latest_block_up_mb": "19",
                        "self_total_down_mb": 108904,
                        "latest_block_down_mb": "0",
                        "self_total_up_mb": 95138,
                        "latest_block_responder_id": "TGliTmFDTFBLO...VGbxS406vrI="
                    }
                }
        """
        mc_community = self.get_multichain_community()
        if not mc_community:
            request.setResponseCode(http.NOT_FOUND)
            return json.dumps({"error": "multichain community not found"})

        return json.dumps({'statistics': mc_community.get_statistics()})
    def test_set_settings(self):
        """
        Testing whether settings in the API can be successfully set
        """
        download = DownloadConfigInterface()
        download.get_share_mode = lambda: False
        self.session.get_downloads = lambda: [download]

        old_filter_setting = self.session.config.get_family_filter_enabled()

        def verify_response1(_):
            self.assertNotEqual(self.session.config.get_family_filter_enabled(), old_filter_setting)
            self.assertEqual(download.get_seeding_mode(), 'time')
            self.assertEqual(download.get_seeding_time(), 100)

        self.should_check_equality = False
        post_data = json.dumps({'general': {'family_filter': not old_filter_setting},
                                'libtorrent': {'utp': False, 'max_download_rate': 50},
                                'download_defaults': {'seeding_mode': 'time', 'seeding_time': 100}})
        yield self.do_request('settings', expected_code=200, request_type='POST', post_data=post_data, raw_data=True) \
            .addCallback(verify_response1)

        def verify_response2(_):
            self.assertEqual(download.get_seeding_mode(), 'ratio')
            self.assertEqual(download.get_seeding_ratio(), 3)

        post_data = json.dumps({'download_defaults': {'seeding_mode': 'ratio', 'seeding_ratio': 3}})
        yield self.do_request('settings', expected_code=200, request_type='POST', post_data=post_data, raw_data=True) \
            .addCallback(verify_response2)

        download.get_share_mode = lambda: True

        def verify_response3(_):
            self.assertNotEqual(download.get_seeding_mode(), 'never')

        post_data = json.dumps({'download_defaults': {'seeding_mode': 'never'}})
        yield self.do_request('settings', expected_code=200, request_type='POST', post_data=post_data, raw_data=True) \
            .addCallback(verify_response3)
示例#47
0
def return_handled_exception(request, exception):
    """
    :param request: the request that encountered the exception
    :param exception: the handled exception
    :return: JSON dictionary describing the exception
    """
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    return json.dumps({
        u"error": {
            u"handled": True,
            u"code": exception.__class__.__name__,
            u"message": exception.message
        }
    })
    def render_DELETE(self, request):
        """
        .. http:delete:: /channels/discovered/(string: channelid)/playlists/(int: playlistid)

        Remove a playlist with a specified playlist id.

            **Example request**:

            .. sourcecode:: none

                curl -X DELETE http://localhost:8085/channels/discovered/abcd/playlists/3

            **Example response**:

            .. sourcecode:: javascript

                {
                    "removed": True
                }

            :statuscode 404: if the specified channel (community) or playlist does not exist
        """
        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsPlaylistsEndpoint.return_404(request)

        playlist = self.channel_db_handler.getPlaylist(
            self.playlist_id, ['Playlists.dispersy_id', 'Playlists.id'])
        if playlist is None:
            return BaseChannelsEndpoint.return_404(
                request, message="this playlist cannot be found")

        channel_community = self.get_community_for_channel_id(channel_info[0])
        if channel_community is None:
            return BaseChannelsEndpoint.return_404(
                request,
                message="the community for the specific channel cannot be found"
            )

        # Remove all torrents from this playlist
        playlist_torrents = self.channel_db_handler.get_torrent_ids_from_playlist(
            playlist[1])
        channel_community.remove_playlist_torrents(
            playlist[0], [dispersy_id for dispersy_id, in playlist_torrents])

        # Remove the playlist itself
        channel_community.remove_playlists([playlist[0]])

        return json.dumps({"removed": True})
示例#49
0
    def render_GET(self, _):
        """
        .. http:get:: /channels/discovered

        A GET request to this endpoint returns all channels discovered in Tribler.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/channels/discovered

            **Example response**:

            .. sourcecode:: javascript

                {
                    "channels": [{
                        "id": 3,
                        "dispersy_cid": "da69aaad39ccf468aba2ab9177d5f8d8160135e6",
                        "name": "My fancy channel",
                        "description": "A description of this fancy channel",
                        "subscribed": False,
                        "votes": 23,
                        "torrents": 3,
                        "spam": 5,
                        "modified": 14598395,
                        "can_edit": True
                    }, ...]
                }
        """
        all_channels_db = self.channel_db_handler.getAllChannels()

        if self.session.config.get_chant_enabled():
            chant_channels = list(self.session.lm.mds.ChannelMetadata.select())
            for chant_channel in chant_channels:
                all_channels_db.append(
                    convert_channel_metadata_to_tuple(chant_channel))

        results_json = []
        for channel in all_channels_db:
            channel_json = convert_db_channel_to_json(channel)
            if self.session.config.get_family_filter_enabled() and \
                    self.session.lm.category.xxx_filter.isXXX(channel_json['name']):
                continue

            results_json.append(channel_json)

        return json.dumps({"channels": results_json})
示例#50
0
        def on_magnet(mlink=None):
            infohash = parse_magnetlink(mlink or uri)[1]
            if infohash is None:
                request.setResponseCode(http.BAD_REQUEST)
                return json.dumps({"error": "missing infohash"})

            if self.session.has_collected_torrent(infohash):
                try:
                    tdef = TorrentDef.load_from_memory(
                        self.session.get_collected_torrent(infohash))
                except ValueError as exc:
                    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
                    return json.dumps(
                        {"error": "invalid torrent file: %s" % str(exc)})
                on_got_metainfo(tdef.get_metainfo())
                return NOT_DONE_YET

            self.session.lm.ltmgr.get_metainfo(
                mlink or uri,
                callback=metainfo_deferred.callback,
                timeout=20,
                timeout_callback=on_metainfo_timeout,
                notify=True)
            return NOT_DONE_YET
    def render_GET(self, _):
        """
        .. http:get:: /channels/subscribed

        Returns all the channels the user is subscribed to.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/channels/subscribed

            **Example response**:

            .. sourcecode:: javascript

                {
                    "subscribed": [{
                        "id": 3,
                        "dispersy_cid": "da69aaad39ccf468aba2ab9177d5f8d8160135e6",
                        "name": "My fancy channel",
                        "description": "A description of this fancy channel",
                        "subscribed": True,
                        "votes": 23,
                        "torrents": 3,
                        "spam": 5,
                        "modified": 14598395,
                        "can_edit": True,
                    }, ...]
                }
        """
        subscribed_channels_db = self.channel_db_handler.getMySubscribedChannels(
            include_dispersy=True)
        results_json = [
            convert_db_channel_to_json(channel)
            for channel in subscribed_channels_db
        ]
        if self.session.config.get_chant_enabled():
            with db_session:
                channels_list = list(
                    self.session.lm.mds.ChannelMetadata.select(
                        lambda g: g.subscribed))
            results_json.extend([
                convert_chant_channel_to_json(channel)
                for channel in channels_list
            ])
        return json.dumps({"subscribed": results_json})
示例#52
0
    def on_got_metadata(self, metadata_data, rss_item=None):
        # save metadata
        thumb_hash = hashlib.sha1(metadata_data).digest()
        self.session.lm.rtorrent_handler.save_metadata(thumb_hash,
                                                       metadata_data)

        # create modification message for channel
        modifications = {
            u'metadata-json':
            json.dumps({
                u'title': rss_item['title'][:64],
                u'description': rss_item['description'][:768],
                u'thumb_hash': thumb_hash.encode('hex')
            })
        }
        self.channel_community.modifyTorrent(rss_item[u'channel_torrent_id'],
                                             modifications)
示例#53
0
    def render_GET(self, request):
        """
        .. http:get:: /market/orders

        A GET request to this endpoint will return all your orders in the market community.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/market/orders

            **Example response**:

            .. sourcecode:: javascript

                {
                    "orders": [{
                        "trader_id": "12c406358ba05e5883a75da3f009477e4ca699a9",
                        "timestamp": 1493906434.627721,
                        "assets" {
                            "first": {
                                "amount": 3,
                                "type": "BTC",
                            },
                            "second": {
                                "amount": 3,
                                "type": "MB",
                            }
                        }
                        "reserved_quantity": 0,
                        "is_ask": False,
                        "timeout": 3600,
                        "traded": 0,
                        "order_number": 1,
                        "completed_timestamp": null,
                        "cancelled": False,
                        "status": "open"
                    }]
                }
        """
        orders = self.get_market_community(
        ).order_manager.order_repository.find_all()
        return json.dumps(
            {"orders": [order.to_dictionary() for order in orders]})
    def test_unicode_chars(self):
        """
        Test setting watch_folder to a unicode path.
        """
        self.should_check_equality = False
        post_data_dict = {'watch_folder': {'directory': "".join([unichr(i) for i in range(256)])}}
        post_data = json.dumps(post_data_dict, ensure_ascii=False)

        def check_settings(settings):
            watch_folder = json.loads(settings)['settings']['watch_folder']['directory']
            self.assertEqual(watch_folder, post_data_dict['watch_folder']['directory'])

        def verify_response(_):
            getter_deferred = self.do_request('settings')
            return getter_deferred.addCallback(check_settings)

        return self.do_request('settings', expected_code=200, request_type='POST',
                               post_data=post_data.encode('latin_1'), raw_data=True).addCallback(verify_response)
示例#55
0
    def render_GET(self, request):
        """
        .. http:get:: /libtorrent/session

        A GET request to this endpoint will return information about libtorrent session.

            **Example request**:

                .. sourcecode:: none

                    curl -X GET http://localhost:8085/libtorrent/session?hop=0

            **Example response**:

                .. sourcecode:: javascript

                    {
                        "hop": 0,
                        "session": {
                            "peer.num_peers_end_game": 0,
                            "utp.utp_timeout": 2,
                            "dht.dht_put_out": 0,
                            ...
                            "peer.choked_piece_requests": 0,
                            "ses.num_incoming_allowed_fast": 0
                        }
                    }
        """
        def on_session_stats_alert_received(alert):
            request.write(json.dumps({'hop': hop, 'session': alert.values}))
            request.finish()

        hop = 0
        if 'hop' in request.args and request.args['hop']:
            hop = int(request.args['hop'][0])

        if hop not in self.session.lm.ltmgr.ltsessions or \
                not hasattr(self.session.lm.ltmgr.ltsessions[hop], "post_session_stats"):
            return json.dumps({'hop': hop, 'session': {}})

        self.session.lm.ltmgr.session_stats_callback = on_session_stats_alert_received
        self.session.lm.ltmgr.ltsessions[hop].post_session_stats()

        return NOT_DONE_YET
示例#56
0
    def render_GET(self, request):
        """
        .. http:get:: /market/asks

        A GET request to this endpoint will return all ask ticks in the order book of the market community.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/market/asks

            **Example response**:

            .. sourcecode:: javascript

                {
                    "asks": [{
                        "asset1": "BTC",
                        "asset2": "MB",
                        "ticks": [{
                            "trader_id": "12c406358ba05e5883a75da3f009477e4ca699a9",
                            "timeout": 3600,
                            "assets": {
                                "first": {
                                    "amount": 10,
                                    "type": "BTC"
                                },
                                "second": {
                                    "amount": 10,
                                    "type": "MB"
                                }
                            },
                            "traded": 5,
                            "timestamp": 1493905920.68573,
                            "order_number": 1}, ...]
                    }, ...]
                }
        """
        return json.dumps({
            "asks":
            self.get_market_community().order_book.asks.
            get_list_representation()
        })
示例#57
0
    def render_GET(self, request):
        """
        .. http:get:: /debug/open_sockets

        A GET request to this endpoint returns information about open sockets.

            **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/debug/openfiles

            **Example response**:

            .. sourcecode:: javascript

                {
                    "open_sockets": [{
                        "family": 2,
                        "status": "ESTABLISHED",
                        "laddr": "0.0.0.0:0",
                        "raddr": "0.0.0.0:0",
                        "type": 30
                    }, ...]
                }
        """
        my_process = psutil.Process()
        sockets = []
        for open_socket in my_process.connections():
            sockets.append({
                "family":
                open_socket.family,
                "status":
                open_socket.status,
                "laddr":
                ("%s:%d" % open_socket.laddr) if open_socket.laddr else "-",
                "raddr":
                ("%s:%d" % open_socket.raddr) if open_socket.raddr else "-",
                "type":
                open_socket.type
            })

        return json.dumps({"open_sockets": sockets})
示例#58
0
    def processingFailed(self, failure):
        self._logger.exception(failure)
        response = {
            u"error": {
                u"handled": False,
                u"code": failure.value.__class__.__name__,
                u"message": failure.value.message
            }
        }
        if self.site.displayTracebacks:
            response[u"error"][u"trace"] = format_tb(failure.getTracebackObject())

        body = json.dumps(response)
        self.setResponseCode(http.INTERNAL_SERVER_ERROR)
        self.setHeader(b'content-type', self.defaultContentType)
        self.setHeader(b'content-length', intToBytes(len(body)))
        self.write(body)
        self.finish()
        return failure
    def render_DELETE(self, request):
        """
        .. http:delete:: /channels/discovered/(string: channelid)/torrents/(string: torrent infohash)

        Remove a torrent with a given infohash from a given channel.

            **Example request**:

            .. sourcecode:: none

                curl -X DELETE http://localhost:8085/channels/discovered/abcdefg/torrents/
                97d2d8f5d37e56cfaeaae151d55f05b077074779

            **Example response**:

            .. sourcecode:: javascript

                {
                    "removed": True
                }

            :statuscode 404: if the channel is not found or if the torrent is not found in the specified channel
        """
        channel_info = self.get_channel_from_db(self.cid)
        if channel_info is None:
            return ChannelsTorrentsEndpoint.return_404(request)

        torrent_db_columns = ['Torrent.torrent_id', 'infohash', 'Torrent.name', 'length', 'Torrent.category',
                              'num_seeders', 'num_leechers', 'last_tracker_check', 'ChannelTorrents.dispersy_id']
        torrent_info = self.channel_db_handler.getTorrentFromChannelId(channel_info[0], self.path.decode('hex'),
                                                                       torrent_db_columns)

        if torrent_info is None:
            return BaseChannelsEndpoint.return_404(request, message=UNKNOWN_TORRENT_MSG)

        channel_community = self.get_community_for_channel_id(channel_info[0])
        if channel_community is None:
            return BaseChannelsEndpoint.return_404(request, message=UNKNOWN_COMMUNITY_MSG)

        channel_community.remove_torrents([torrent_info[8]])  # the 8th index is the dispersy id of the channel torrent

        return json.dumps({"removed": True})
    def render_PUT(self, request):
        """
        .. http:put:: /channels/subscribed/(string: channelid)

        Subscribe to a specific channel. Returns error 409 if you are already subscribed to this channel.

            **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/channels/subscribed/da69aaad39ccf468aba2ab9177d5f8d8160135e6

            **Example response**:

            .. sourcecode:: javascript

                {
                    "subscribed" : True
                }

            :statuscode 409: (conflict) if you are already subscribed to the specified channel.
        """
        request.setHeader('Content-Type', 'text/json')
        channel_info = self.get_channel_from_db(self.cid)

        if channel_info is not None and channel_info[7] == VOTE_SUBSCRIBE:
            request.setResponseCode(http.CONFLICT)
            return json.dumps({"error": ALREADY_SUBSCRIBED_RESPONSE_MSG})

        def on_vote_done(_):
            request.write(json.dumps({"subscribed": True}))
            request.finish()

        def on_vote_error(failure):
            request.processingFailed(failure)

        self.vote_for_channel(
            self.cid,
            VOTE_SUBSCRIBE).addCallback(on_vote_done).addErrback(on_vote_error)

        return NOT_DONE_YET