desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'During the initialization of the REST API, we only start the event sockets and the state endpoint. We enable the other endpoints when Tribler has completed the starting procedure.'
def __init__(self, session):
resource.Resource.__init__(self) self.session = session self.events_endpoint = EventsEndpoint(self.session) self.state_endpoint = StateEndpoint(self.session) self.shutdown_endpoint = ShutdownEndpoint(self.session) self.putChild('events', self.events_endpoint) self.putChild('state', self.stat...
'This method is only called when Tribler has started. It enables the other endpoints that are dependent on a fully started Tribler.'
def start_endpoints(self):
child_handler_dict = {'search': SearchEndpoint, 'channels': ChannelsEndpoint, 'mychannel': MyChannelEndpoint, 'settings': SettingsEndpoint, 'downloads': DownloadsEndpoint, 'createtorrent': CreateTorrentEndpoint, 'torrents': TorrentsEndpoint, 'debug': DebugEndpoint, 'shutdown': ShutdownEndpoint, 'trustchain': Trustc...
'Search for the tunnel community in the dispersy communities.'
def get_tunnel_community(self):
for community in self.session.get_dispersy_instance().get_communities(): if isinstance(community, TunnelCommunity): return community return None
'.. 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", ...
def render_GET(self, request):
tunnel_community = self.get_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...
'.. http:get:: /settings A GET request to this endpoint returns all the session settings that can be found in Tribler. Please note that a port with a value of -1 means that the port is randomly assigned at startup. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/settings **Example response**...
def render_GET(self, request):
return json.dumps({'settings': self.session.config.config})
'.. http:post:: /settings A POST request to this endpoint will update Tribler settings. A JSON-dictionary should be passed as body contents. **Example request**: .. sourcecode:: none curl -X POST http://localhost:8085/settings --data "{" **Example response**: .. sourcecode:: javascript "modified": True'
def render_POST(self, request):
settings_dict = json.loads(request.content.read()) self.parse_settings_dict(settings_dict) self.session.config.write() return json.dumps({'modified': True})
'Set a specific Tribler setting. Throw a ValueError if this setting is not available.'
def parse_setting(self, section, option, value):
if ((section in self.session.config.config) and (option in self.session.config.config[section])): self.session.config.config[section][option] = value else: raise ValueError(('Section %s with option %s does not exist' % (section, option))) if ((section == 'libtorrent') an...
'Parse the settings dictionary.'
def parse_settings_dict(self, settings_dict, depth=1, root_key=None):
for (key, value) in settings_dict.iteritems(): if isinstance(value, dict): self.parse_settings_dict(value, depth=(depth + 1), root_key=key) else: self.parse_setting(root_key, key, value)
'.. 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": "12c406358ba...
def render_GET(self, request):
transactions = self.get_market_community().transaction_manager.find_all() return json.dumps({'transactions': [transaction.to_dictionary() for transaction in transactions]})
'.. http:get:: /market/transactions/(string:trader_id)/(string:transaction_number)/payments A GET request to this endpoint will return all payments tied to a specific transaction. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/market/transactions/ 12c406358ba05e5883a75da3f009477e4ca699a9/3/...
def render_GET(self, request):
transaction_id = TransactionId(TraderId(self.transaction_trader_id), TransactionNumber(int(self.transaction_number))) transaction = self.get_market_community().transaction_manager.find_by_id(transaction_id) if (not transaction): request.setResponseCode(http.NOT_FOUND) return json.dumps({'err...
'Create an ask/bid from the provided parameters in a request. This method returns a tuple with the price, quantity and timeout of the ask/bid.'
@staticmethod def create_ask_bid_from_params(parameters):
timeout = 3600.0 if has_param(parameters, 'timeout'): timeout = float(get_param(parameters, 'timeout')) price = float(get_param(parameters, 'price')) quantity = int(get_param(parameters, 'quantity')) price_type = get_param(parameters, 'price_type') quantity_type = get_param(parameters, '...
'.. 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": [{ "price_type": "BTC", "quantity_type": "MC", ...
def render_GET(self, request):
return json.dumps({'asks': self.get_market_community().order_book.asks.get_list_representation()})
'.. 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 "price=10&quantity=10&price_type=BTC&quantity_type=MC" **Example response**: .. sourcecode:: javascript "created": True'
def render_PUT(self, request):
parameters = http.parse_qs(request.content.read(), 1) if ((not has_param(parameters, 'price')) or (not has_param(parameters, 'quantity'))): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'price or quantity parameter missing'}) if ((not has_param(parameters,...
'.. http:get:: /market/bids A GET request to this endpoint will return all bid ticks in the order book of the market community. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/market/bids **Example response**: .. sourcecode:: javascript "bids": [{ "price_type": "BTC", "quantity_type": "MC", ...
def render_GET(self, request):
return json.dumps({'bids': self.get_market_community().order_book.bids.get_list_representation()})
'.. http:put:: /market/bids A request to this endpoint will create a new bid order. **Example request**: .. sourcecode:: none curl -X PUT http://localhost:8085/market/bids --data "price=10&quantity=10&price_type=BTC&quantity_type=MC" **Example response**: .. sourcecode:: javascript "created": True'
def render_PUT(self, request):
parameters = http.parse_qs(request.content.read(), 1) if ((not has_param(parameters, 'price')) or (not has_param(parameters, 'quantity'))): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'price or quantity parameter missing'}) if ((not has_param(parameters,...
'.. 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...
def render_GET(self, request):
orders = self.get_market_community().order_manager.order_repository.find_all() return json.dumps({'orders': [order.to_dictionary() for order in orders]})
'.. 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'
def render_POST(self, request):
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({'...
'.. http:get:: /search?q=(string:query) A GET request to this endpoint will create a search. Results are returned over the events endpoint, one by one. First, the results available in the local database will be pushed. After that, incoming Dispersy results are pushed. The query to this endpoint is passed using the url,...
def render_GET(self, request):
if ('q' not in request.args): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'query parameter missing'}) self.events_endpoint.start_new_query() query = unicode(request.args['q'][0], 'utf-8') keywords = split_into_keywords(query) results_local_channels = s...
'.. 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...
def render_GET(self, request):
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) return json.dumps(...
'.. http:get:: /torrentinfo A GET request to this endpoint will return information from a torrent found at a provided URI. This URI can either represent a file location, a magnet link or a HTTP(S) url. - torrent: the URI of the torrent file that should be downloaded. This parameter is required. **Example request**: .. ...
def render_GET(self, request):
metainfo_deferred = Deferred() def on_got_metainfo(metainfo): if (not isinstance(metainfo, dict)): self._logger.warning('Received metainfo is not a dictionary') request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write(json.dumps({'error': 'inva...
'Returns a 404 response code if your channel has not been created.'
@staticmethod def return_404(request, message='this download does not exist'):
request.setResponseCode(http.NOT_FOUND) return json.dumps({'error': message})
'Create a download configuration based on some given parameters. Possible parameters are: - anon_hops: the number of hops for the anonymous download. 0 hops is equivalent to a plain download - safe_seeding: whether the seeding of the download should be anonymous or not (0 = off, 1 = on) - destination: the destination p...
@staticmethod def create_dconfig_from_params(parameters):
download_config = DownloadStartupConfig() anon_hops = 0 if (('anon_hops' in parameters) and (len(parameters['anon_hops']) > 0)): if parameters['anon_hops'][0].isdigit(): anon_hops = int(parameters['anon_hops'][0]) safe_seeding = False if (('safe_seeding' in parameters) and (len(p...
'.. http:get:: /downloads?get_peers=(boolean: get_peers)&get_pieces=(boolean: get_pieces) A GET request to this endpoint returns all downloads in Tribler, both active and inactive. The progress is a number ranging from 0 to 1, indicating the progress of the specific state (downloading, checking etc). The download speed...
def render_GET(self, request):
get_peers = False if (('get_peers' in request.args) and (len(request.args['get_peers']) > 0) and (request.args['get_peers'][0] == '1')): get_peers = True get_pieces = False if (('get_pieces' in request.args) and (len(request.args['get_pieces']) > 0) and (request.args['get_pieces'][0] == '1')): ...
'.. http:put:: /downloads A PUT request to this endpoint will start a download from a provided URI. This URI can either represent a file location, a magnet link or a HTTP(S) url. - anon_hops: the number of hops for the anonymous download. 0 hops is equivalent to a plain download - safe_seeding: whether the seeding of t...
def render_PUT(self, request):
parameters = http.parse_qs(request.content.read(), 1) if (('uri' not in parameters) or (len(parameters['uri']) == 0)): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'uri parameter missing'}) (download_config, error) = DownloadsEndpoint.create_dconfig_from_params...
'.. http:delete:: /downloads/(string: infohash) A DELETE request to this endpoint removes a specific download from Tribler. You can specify whether you only want to remove the download or the download and the downloaded data using the remove_data parameter. **Example request**: .. sourcecode:: none curl -X DELETE http:...
def render_DELETE(self, request):
parameters = http.parse_qs(request.content.read(), 1) if (('remove_data' not in parameters) or (len(parameters['remove_data']) == 0)): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'remove_data parameter missing'}) download = self.session.get_download(self.infoh...
'.. http:patch:: /download/(string: infohash) A PATCH request to this endpoint will update a download in Tribler. A state parameter can be passed to modify the state of the download. Valid states are "resume" (to resume a stopped/paused download), "stop" (to stop a running download) and "recheck" (to force a recheck of...
def render_PATCH(self, request):
download = self.session.get_download(self.infohash) if (not download): return DownloadSpecificEndpoint.return_404(request) parameters = http.parse_qs(request.content.read(), 1) if ((len(parameters) > 1) and ('anon_hops' in parameters)): request.setResponseCode(http.BAD_REQUEST) r...
'.. http:get:: /download/(string: infohash)/torrent A GET request to this endpoint returns the .torrent file associated with the specified download. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/downloads/4344503b7e797ebf31582327a5baae35b11bda01/torrent **Example response**: The contents o...
def render_GET(self, request):
download = self.session.get_download(self.infohash) if (not download): return DownloadExportTorrentEndpoint.return_404(request) request.setHeader('content-type', 'application/x-bittorrent') request.setHeader('Content-Disposition', ('attachment; filename=%s.torrent' % self.infohash.encode('hex...
'.. http:get:: /torrents/random?limit=(int: max nr of torrents) A GET request to this endpoint returns random (channel) torrents. You can optionally specify a limit parameter to limit the maximum number of results. By default, this is 10. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/torre...
def render_GET(self, request):
limit_torrents = 10 if (('limit' in request.args) and (len(request.args['limit']) > 0)): limit_torrents = int(request.args['limit'][0]) if (limit_torrents <= 0): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'the limit parameter must be...
'.. http:get:: /torrents/(string: torrent infohash)/tracker Fetch all trackers of a specific torrent. **Example request**: .. sourcecode:: none curl http://localhost:8085/torrents/97d2d8f5d37e56cfaeaae151d55f05b077074779/trackers **Example response**: .. sourcecode:: javascript "trackers": [ "http://mytracker.com:80/an...
def render_GET(self, request):
torrent_info = self.torrent_db.getTorrent(self.infohash.decode('hex'), ['C.torrent_id', 'num_seeders']) if (torrent_info is None): request.setResponseCode(http.NOT_FOUND) return json.dumps({'error': 'torrent not found in database'}) trackers = self.torrent_db.getTrackerListByInfo...
'.. http:get:: /torrents/(string: torrent infohash)/health Fetch the swarm health of a specific torrent. You can optionally specify the timeout to be used in the connections to the trackers. This is by default 20 seconds. By default, we will not check the health of a torrent again if it was recently checked. You can fo...
def render_GET(self, request):
timeout = 20 if ('timeout' in request.args): timeout = int(request.args['timeout'][0]) refresh = False if (('refresh' in request.args) and (len(request.args['refresh']) > 0) and (request.args['refresh'][0] == '1')): refresh = True torrent_db_columns = ['C.torrent_id', 'num_seeders', ...
'Search for the trustchain community in the dispersy communities.'
def get_trustchain_community(self):
for community in self.session.get_dispersy_instance().get_communities(): if isinstance(community, TriblerChainCommunity): return community return None
'.. http:get:: /trustchain/statistics A GET request to this endpoint returns statistics about the trustchain community **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/trustchain/statistics **Example response**: Note: latest_block does not exist if there is no data .. sourcecode:: javascript ...
def render_GET(self, request):
mc_community = self.get_trustchain_community() if (not mc_community): request.setResponseCode(http.NOT_FOUND) return json.dumps({'error': 'trustchain community not found'}) return json.dumps({'statistics': mc_community.get_statistics()})
'.. http:get:: /trustchain/blocks/TGliTmFDTFBLOVGbxS406vrI=?limit=(int: max nr of returned blocks) A GET request to this endpoint returns all blocks of a specific identity, both that were signed and responded by him. You can optionally limit the amount of blocks returned, this will only return some of the most recent b...
def render_GET(self, request):
mc_community = self.get_trustchain_community() if (not mc_community): request.setResponseCode(http.NOT_FOUND) return json.dumps({'error': 'trustchain community not found'}) limit_blocks = 100 if ('limit' in request.args): try: limit_blocks = int(request.args[...
'.. http:get:: /state A GET request to this endpoint returns the current state of the Tribler core. There are three states: - STARTING: The core of Tribler is starting - UPGRADING: The upgrader is active - STARTED: The Tribler core has started **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/...
def render_GET(self, request):
return json.dumps({'state': self.tribler_state, 'last_exception': self.last_exception})
'.. http:post:: /createtorrent?download=(boolean: download) Create a torrent from local files and return it in base64 encoding. Description and trackers list are optional. This endpoint returns a 500 HTTP response if a source file does not exist. You can optionally pass a flag to start downloading the created torrent. ...
def render_POST(self, request):
parameters = http.parse_qs(request.content.read(), 1) params = {} if (('files[]' in parameters) and (len(parameters['files[]']) > 0)): file_path_list = [unicode(f, 'utf-8') for f in parameters['files[]']] else: request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error':...
'Write data over the event socket if it\'s open.'
def write_data(self, message):
try: message_str = json.dumps(message) except UnicodeDecodeError: 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]
'Returns the channel search results over the events endpoint.'
def on_search_results_channels(self, subject, changetype, objectID, results):
query = ' '.join(results['keywords']) for channel in results['result_list']: channel_json = convert_db_channel_to_json(channel, include_rel_score=True) if (self.session.config.get_family_filter_enabled() and self.session.lm.category.xxx_filter.isXXX(channel_json['name'])): continu...
'Returns the torrent search results over the events endpoint.'
def on_search_results_torrents(self, subject, changetype, objectID, results):
query = ' '.join(results['keywords']) for torrent in results['result_list']: torrent_json = convert_search_torrent_to_json(torrent) if (self.session.config.get_family_filter_enabled() and (torrent_json['category'] == 'xxx')): continue if (('infohash' in torrent_json) and (...
'.. http:get:: /events A GET request to this endpoint will open the event connection. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/events'
def render_GET(self, request):
def on_request_finished(_): self.events_requests.remove(request) self.events_requests.append(request) request.notifyFinish().addCallbacks(on_request_finished, on_request_finished) request.write((json.dumps({'type': 'events_start', 'event': {'tribler_started': self.session.lm.initComplete, 'versi...
'.. http:get:: /statistics/tribler A GET request to this endpoint returns general statistics in Tribler. The size of the Tribler database is in bytes. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/statistics/tribler **Example response**: .. sourcecode:: javascript "tribler_statistics": { "...
def render_GET(self, request):
return json.dumps({'tribler_statistics': self.session.get_tribler_statistics()})
'.. http:get:: /statistics/dispersy A GET request to this endpoint returns general statistics in Dispersy. The returned runtime is the amount of seconds that Dispersy is active. The total uploaded and total downloaded statistics are in bytes. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/s...
def render_GET(self, request):
return json.dumps({'dispersy_statistics': self.session.get_dispersy_statistics()})
'.. http:get:: /statistics/communities A GET request to this endpoint returns general statistics of active Dispersy communities. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/statistics/communities **Example response**: .. sourcecode:: javascript "community_statistics": [{ "identifier": "4...
def render_GET(self, request):
return json.dumps({'community_statistics': self.session.get_community_statistics()})
'Returns a 404 response code if your channel has not been created.'
@staticmethod def return_404(request, message=UNKNOWN_CHANNEL_RESPONSE_MSG):
request.setResponseCode(http.NOT_FOUND) return json.dumps({'error': message})
'Returns a 401 response code if you are not authorized to perform a specific request.'
@staticmethod def return_401(request, message=UNAUTHORIZED_RESPONSE_MSG):
request.setResponseCode(http.UNAUTHORIZED) return json.dumps({'error': message})
'Returns information about the channel from the database. Returns None if the channel with given cid does not exist.'
def get_channel_from_db(self, cid):
channels_list = self.channel_db_handler.getChannelsByCID([cid]) return (channels_list[0] if (len(channels_list) > 0) else None)
'Returns the Channel object associated with a channel that is used to manage rss feeds.'
def get_my_channel_object(self):
my_channel_id = self.channel_db_handler.getMyChannelId() return self.session.lm.channel_manager.get_my_channel(my_channel_id)
'Make a vote in the channel specified by the cid. Returns a deferred that fires when the vote is done.'
def vote_for_channel(self, cid, vote):
for community in self.session.get_dispersy_instance().get_communities(): if isinstance(community, AllChannelCommunity): return community.disp_create_votecast(cid, vote, int(time.time()))
'Returns a Dispersy community from the given channel id. The Community object can be used to delete/add torrents or modify playlists in a specific channel.'
def get_community_for_channel_id(self, channel_id):
dispersy_cid = str(self.channel_db_handler.getDispersyCIDFromChannelId(channel_id)) try: return self.session.get_dispersy_instance().get_community(dispersy_cid) except CommunityNotFoundException: return None
'.. http:get:: /channels/popular?limit=(int:max nr of channels) A GET request to this endpoint will return the most popular discovered channels in Tribler. You can optionally pass a limit parameter to limit the number of results. **Example request**: .. sourcecode:: none curl -X GET http://localhost:8085/channels/popul...
def render_GET(self, request):
limit_channels = 10 if (('limit' in request.args) and (len(request.args['limit']) > 0)): limit_channels = int(request.args['limit'][0]) if (limit_channels <= 0): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'the limit parameter must be...
'.. 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": "da69aaad39ccf468aba2ab9...
def render_GET(self, _):
all_channels_db = self.channel_db_handler.getAllChannels() 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'])): ...
'.. http:put:: /channels/discovered Create your own new channel. The passed mode and descriptions are optional. Valid modes include: \'open\', \'semi-open\' or \'closed\'. By default, the mode of the new channel is \'closed\'. **Example request**: .. sourcecode:: none curl -X PUT http://localhost:8085/channels/discover...
def render_PUT(self, request):
parameters = http.parse_qs(request.content.read(), 1) if (('name' not in parameters) or (len(parameters['name']) == 0) or (len(parameters['name'][0]) == 0)): request.setResponseCode(http.BAD_REQUEST) return json.dumps({'error': 'channel name cannot be empty'}) if (('description' ...
'.. 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"...
def render_GET(self, request):
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]}})
'.. http:get:: /channels/discovered/(string: channelid)/playlists Returns the playlists in your channel. Returns error 404 if you have not created a channel. - disable_filter: whether the family filter should be disabled for this request (1 = disabled) **Example request**: .. sourcecode:: none curl -X GET http://localh...
def render_GET(self, request):
channel = self.get_channel_from_db(self.cid) if (channel is None): return ChannelsPlaylistsEndpoint.return_404(request) playlists = [] req_columns = ['Playlists.id', 'Playlists.name', 'Playlists.description'] req_columns_torrents = ['Torrent.torrent_id', 'infohash', 'Torrent.name', 'length',...
'.. 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 playlis...
def render_PUT(self, request):
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['descriptio...
'.. 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 :sta...
def render_DELETE(self, request):
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...
'.. 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 te...
def render_POST(self, request):
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['descriptio...
'.. 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...
def render_PUT(self, request):
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...
'.. 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**:...
def render_DELETE(self, request):
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(requ...
'.. 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": { "...
def render_GET(self, request):
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': {'iden...
'.. http:post:: /mychannel Modify the name and/or the description of your channel. This endpoint returns a 404 HTTP response if you have not created a channel (yet). **Example request**: .. sourcecode:: none curl -X POST http://localhost:8085/mychannel --data "name=My fancy playlist&description=This playlist contains s...
def render_POST(self, request):
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}) channel_community = self.get_community_for_channel_id(my_channel_id) if (channel_community is None): ...
'Returns a tuple of (channel_obj, error). Callers of this method should check whether the channel_obj is None and if so, return the error.'
def get_my_channel_obj_or_error(self, request):
channel_info = self.get_channel_from_db(self.cid) if (channel_info is None): return (None, BaseChannelsRssFeedsEndpoint.return_404(request)) if (channel_info[0] != self.channel_db_handler.getMyChannelId()): return (None, BaseChannelsRssFeedsEndpoint.return_401(request)) channel_obj = sel...
'.. 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",'
def render_GET(self, request):
(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})
'.. http:post:: /channels/discovered/(string: channelid)/recheckfeeds Rechecks all rss feeds in your channel. Returns error 404 if you channel does not exist. **Example request**: .. sourcecode:: none curl -X POST http://localhost:8085/channels/discovered/recheckrssfeeds **Example response**: .. sourcecode:: javascript...
def render_POST(self, request):
(channel_obj, error) = self.get_my_channel_obj_or_error(request) if (channel_obj is None): return error channel_obj.refresh_all_feeds() return json.dumps({'rechecked': True})
'.. 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/channe...
def render_PUT(self, request):
(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'}) chann...
'.. 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...
def render_DELETE(self, request):
(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 fe...
'.. http:get:: /channels/discovered/(string: channelid)/torrents A GET request to this endpoint returns all discovered torrents in a specific channel. The size of the torrent is in number of bytes. The last_tracker_check value will be 0 if we did not check the tracker state of the torrent yet. Optionally, we can disabl...
def render_GET(self, request):
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...
'.. http:put:: /channels/discovered/(string: channelid)/torrents Add a torrent file to your own channel. Returns error 500 if something is wrong with the torrent file and DuplicateTorrentFileError if already added to your channel. The torrent data is passed as base-64 encoded string. The description is optional. **Exam...
def render_PUT(self, request):
channel = self.get_channel_from_db(self.cid) if (channel is None): return ChannelsTorrentsEndpoint.return_404(request) parameters = http.parse_qs(request.content.read(), 1) if (('torrent' not in parameters) or (len(parameters['torrent']) == 0)): request.setResponseCode(http.BAD_REQUEST) ...
'.. http:put:: /channels/discovered/(string: channelid)/torrents/http%3A%2F%2Ftest.com%2Ftest.torrent Add a torrent by magnet or url to your channel. Returns error 500 if something is wrong with the torrent file and DuplicateTorrentFileError if already added to your channel (except with magnet links). **Example request...
def render_PUT(self, request):
channel = self.get_channel_from_db(self.cid) if (channel is None): return BaseChannelsEndpoint.return_404(request) parameters = http.parse_qs(request.content.read(), 1) if (('description' not in parameters) or (len(parameters['description']) == 0)): extra_info = {} else: extr...
'.. 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 **Exam...
def render_DELETE(self, request):
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...
'.. 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", "...
def render_GET(self, _):
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] return json.dumps({'subscribed': results_json})
'.. 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**: .. sour...
def render_PUT(self, request):
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(...
'.. http:delete:: /channels/subscribed/(string: channelid) Unsubscribe from a specific channel. Returns error 404 if you are not subscribed to this channel. **Example request**: .. sourcecode:: none curl -X DELETE http://localhost:8085/channels/subscribed/da69aaad39ccf468aba2ab9177d5f8d8160135e6 **Example response**: ....
def render_DELETE(self, request):
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) if (channel_info[7] != VOTE_SUBSCRIBE): return ChannelsModifySubscriptionEndpoint.return_404(request, ...
'Starts the HTTP API with the listen port as specified in the session configuration.'
def start(self):
self.root_endpoint = RootEndpoint(self.session) site = server.Site(resource=self.root_endpoint) site.requestFactory = RESTRequest self.site = reactor.listenTCP(self.session.config.get_http_api_port(), site, interface='127.0.0.1')
'Stop the HTTP API and return a deferred that fires when the server has shut down.'
def stop(self):
return maybeDeferred(self.site.stopListening)
'Sets the _infohash_list to None and returns a deferred that has succeeded. :return: A deferred that succeeds immediately.'
@inlineCallbacks def cleanup(self):
(yield self.wait_for_deferred_tasks()) self.cancel_all_pending_tasks() self._infohash_list = None
'Checks if we still can add requests to this session. :return: True or False.'
def can_add_request(self):
etree_condition = ('etree' not in self.tracker_url) return ((not self._is_initiated) and (len(self._infohash_list) < MAX_TRACKER_MULTI_SCRAPE) and etree_condition)
'Adds a infohash into this session. :param infohash: The infohash to be added.'
def add_infohash(self, infohash):
assert (not self._is_initiated), u'Must not add request to an initiated session.' assert (not self.has_infohash(infohash)), u'Must not add duplicate requests' self._infohash_list.append(infohash)
'Does some work when a connection has been established.'
@abstractmethod def connect_to_tracker(self):
pass
'Number of retries before a session is marked as failed.'
@abstractproperty def max_retries(self):
pass
'Interval between retries.'
@abstractproperty def retry_interval(self):
pass
'Returns the max amount of retries allowed for this session. :return: The maximum amount of retries.'
def max_retries(self):
return HTTP_TRACKER_MAX_RETRIES
'Returns the interval one has to wait before retrying to connect. :return: The interval before retrying.'
def retry_interval(self):
return HTTP_TRACKER_RECHECK_INTERVAL
'Handles the case of an error during the request. :param failure: The failure object that is thrown by a deferred.'
def on_error(self, failure):
self._logger.info('Error when querying http tracker: %s %s', str(failure), self.tracker_url) self.failed(msg=failure.getErrorMessage())
':param _: The deferred which we ignore. This function handles the scenario of the session prematurely being cleaned up, most likely due to a shutdown. This function only should be called by the result_deferred.'
def _on_cancel(self, a):
self._logger.info('The result deferred of this HTTP tracker session is being cancelled due to a session cleanup. HTTP url: %s', self.tracker_url)
'This method handles everything that needs to be done when one step in the session has failed and thus no data can be obtained.'
def failed(self, msg=None):
self._is_failed = True if self.result_deferred: result_msg = ('HTTP tracker failed for url %s' % self._tracker_url) if msg: result_msg += (' (error: %s)' % unicode(msg, errors='replace')) self.result_deferred.errback(ValueError(result_msg))
'This function handles the response body of a HTTP tracker, parsing the results.'
def _process_scrape_response(self, body):
if (body is None): self.failed(msg='no response body') return response_dict = bdecode(body) if (response_dict is None): self.failed(msg='no valid response') return response_list = [] unprocessed_infohash_list = self._infohash_list[:] if (('files' in re...
'Cleans the session by cancelling all deferreds and closing sockets. :return: A deferred that fires once the cleanup is done.'
@inlineCallbacks def cleanup(self):
(yield self._connection_pool.closeCachedConnections()) (yield super(HttpTrackerSession, self).cleanup()) self.request = None self.result_deferred = None
'This method handles everything that needs to be done when something during the UDP scraping went wrong.'
def on_error(self):
self.udpsession.failed()
'Stops the UDP scraper and closes the socket. :return: A deferred that fires once it has closed the connection.'
def stop(self):
self._logger.info('Shutting down scraper which was connected to ip %s, port %s', self.ip_address, self.port) if self.timeout_call.active(): self.timeout_call.cancel() if (self.transport and self.numPorts and self.transport.connected): return maybeDeferred(self.t...
'This function is called when the scraper is initialized. Initiates the connection with the tracker.'
def startProtocol(self):
self.transport.connect(self.ip_address, self.port) self._logger.info('UDP health scraper connected to host %s port %d', self.ip_address, self.port) self.udpsession.on_start()
'This function can be called to send serialized data to the tracker. :param data: The serialized data to be send.'
def write_data(self, data):
self.transport.write(data)
'This function dispatches data received from a UDP tracker. If it\'s the first response, it will dispatch the data to the handle_connection_response function of the UDP session. All subsequent data will be send to the _handle_response function of the UDP session. :param data: The data received from the UDP tracker.'
def datagramReceived(self, data, (_host, _port)):
if self.expect_connection_response: if self.timeout_call.active(): self.timeout_call.cancel() self.udpsession.handle_connection_response(data) self.expect_connection_response = False else: self.udpsession.handle_response(data)
'Handles the case of a connection being refused by a tracker.'
def connectionRefused(self):
self._logger.info('UDP Scraper could not connect to %s %s', self.ip_address, self.port) self.on_error()
'Handles the case when resolving an ip address fails. :param failure: The failure object thrown by the deferred.'
def on_error(self, failure):
self._logger.info('Error when querying UDP tracker: %s %s', str(failure), self.tracker_url) self.failed(msg=failure.getErrorMessage())
':param _: The deferred which we ignore. This function handles the scenario of the session prematurely being cleaned up, most likely due to a shutdown. This function only should be called by the result_deferred.'
def _on_cancel(self, _):
self._logger.info('The result deferred of this UDP tracker session is being cancelled due to a session cleanup. UDP url: %s', self.tracker_url)
'Called when a hostname has been resolved to an ip address. Constructs a scraper and opens a UDP port to listen on. Removes an old scraper if present. :param ip_address: The ip address that matches the hostname of the tracker_url. :param start_scraper: Whether we should start the scraper immediately.'
def on_ip_address_resolved(self, ip_address, start_scraper=True):
self.ip_address = ip_address self.scraper = UDPScraper(self, self.ip_address, self.port, self.timeout) if start_scraper: reactor.listenUDP(0, self.scraper)
'This method handles everything that needs to be done when one step in the session has failed and thus no data can be obtained.'
def failed(self, msg=None):
self._is_failed = True if self.scraper: self.scraper.stop() self.scraper = None if self.result_deferred: result_msg = ('UDP tracker failed for url %s' % self._tracker_url) if msg: result_msg += (' (error: %s)' % unicode(msg, errors='replace'))...
'Generates a unique transaction id and stores this in the _active_session_dict set.'
def generate_transaction_id(self):
while True: transaction_id = random.randint(0, MAX_INT32) if (transaction_id not in UdpTrackerSession._active_session_dict.items()): UdpTrackerSession._active_session_dict[self] = transaction_id self._transaction_id = transaction_id break
'Removes an session and its corresponding id from the _active_session_dict set. :param session: The session that needs to be removed from the set.'
@staticmethod def remove_transaction_id(session):
if (session in UdpTrackerSession._active_session_dict): del UdpTrackerSession._active_session_dict[session]
'Cleans the session by cancelling all deferreds and closing sockets. :return: A deferred that fires once the cleanup is done.'
@inlineCallbacks def cleanup(self):
(yield super(UdpTrackerSession, self).cleanup()) UdpTrackerSession.remove_transaction_id(self) self.ip_resolve_deferred = None self.result_deferred = None if self.scraper: self.clean_defer_list.append(self.scraper.stop()) self.scraper = None res = (yield DeferredList(self.clean_d...