Package Tribler :: Package Core :: Module Session :: Class Session

Class Session

                   SessionConfig.SessionConfigInterface --+    
                                                          |    
APIImplementation.SessionRuntimeConfig.SessionRuntimeConfig --+
                                                              |
                                                             Session

A Session is a running instance of the Tribler Core and the Core's central class. It implements the SessionConfigInterface which can be used to change session parameters at runtime (for selected parameters). cf. libtorrent session
Instance Methods
 
__init__(self, scfg=None, ignore_singleton=False)
A Session object is created which is configured following a copy of the SessionStartupConfig scfg.
 
start_download(self, tdef, dcfg=None)
Creates a Download object and adds it to the session.
 
resume_download_from_file(self, filename)
Recreates Download from resume file
 
get_downloads(self)
Returns a copy of the list of Downloads.
 
remove_download(self, d, removecontent=False)
Stops the download and removes it from the session.
 
set_download_states_callback(self, usercallback, getpeerlist=False)
See Download.set_state_callback.
 
get_permid(self)
Returns the PermID of the Session, as determined by the SessionConfig.set_permid() parameter.
 
get_external_ip(self)
Returns the external IP address of this Session, i.e., by which it is reachable from the Internet.
 
get_current_startup_config_copy(self)
Returns a SessionStartupConfig that is a copy of the current runtime SessionConfig.
 
get_internal_tracker_url(self)
Returns the announce URL for the internal tracker.
 
get_internal_tracker_dir(self)
Returns the directory containing the torrents tracked by the internal tracker (and associated databases).
 
add_to_internal_tracker(self, tdef)
Add a torrent def to the list of torrents tracked by the internal tracker.
 
remove_from_internal_tracker(self, tdef)
Remove a torrent def from the list of torrents tracked by the internal tracker.
 
remove_from_internal_tracker_by_infohash(self, infohash)
Remove a torrent def from the list of torrents tracked by the internal tracker.
 
add_observer(self, func, subject, changeTypes=['update', 'insert', 'delete'], objectID=None)
Add an observer function function to the Session.
 
remove_observer(self, func)
Remove observer function.
 
open_dbhandler(self, subject)
Opens a connection to the specified database.
 
close_dbhandler(self, dbhandler)
Closes the given database connection
 
set_overlay_request_policy(self, reqpol)
Set a function which defines which overlay requests (e.g.
 
load_checkpoint(self, initialdlstatus=None)
Restart Downloads from checkpoint, if any.
 
checkpoint(self)
Saves the internal session state to the Session's state dir.
 
shutdown(self, checkpoint=True, gracetime=2.0, hacksessconfcheckpoint=True)
Checkpoints the session and closes it, stopping the download engine.
 
get_downloads_pstate_dir(self)
Returns the directory in which to checkpoint the Downloads in this Session.
 
query_connected_peers(self, query, usercallback, max_peers_to_query=None)
Ask all Tribler peers we're currently connected to resolve the specified query and return the hits.
 
download_torrentfile_from_peer(self, permid, infohash, usercallback)
Ask the designated peer to send us the torrentfile for the torrent identified by the passed infohash.
 
checkpoint_shutdown(self, stop, checkpoint, gracetime, hacksessconfcheckpoint)
Checkpoints the Session and optionally shuts down the Session.
 
save_pstate_sessconfig(self)
Save the runtime SessionConfig to disk
 
get_internal_tracker_torrentfilename(self, infohash)
Return the absolute pathname of the torrent file used by the internal tracker.
 
get_nat_type(self, callback=None)
Return the type of Network Address Translator (NAT) detected.
 
send_friendship_message(self, permid, mtype, approved=None)
Send friendship msg to the specified peer ...
 
set_friendship_callback(self, usercallback)
When a new friendship request is received the given callback function is called with as first parameter the requester's permid and as second parameter a dictionary of request arguments: callback(requester_permid,params) The callback is called by a popup thread which can be used indefinitely (within reason) by the higher level code.

Inherited from APIImplementation.SessionRuntimeConfig.SessionRuntimeConfig: get_autoclose_check_interval, get_autoclose_timeout, get_bartercast, get_bind_to_addresses, get_buddycast, get_buddycast_collecting_solution, get_buddycast_interval, get_buddycast_max_peers, get_dialback, get_dialback_active, get_dialback_trust_superpeers, get_download_help, get_download_help_dir, get_install_dir, get_internal_tracker, get_listen_port, get_mainline_dht, get_megacache, get_mugshot, get_nat_detect, get_nickname, get_overlay, get_overlay_log, get_overlay_max_message_length, get_peer_icon_path, get_permid_keypair_filename, get_pingback_servers, get_puncturing_coordinators, get_puncturing_private_port, get_rquery, get_socnet, get_start_recommender, get_state_dir, get_stop_collecting_threshold, get_stun_servers, get_superpeer, get_superpeer_file, get_torrent_checking, get_torrent_checking_period, get_torrent_collecting, get_torrent_collecting_dir, get_torrent_collecting_max_torrents, get_torrent_collecting_rate, get_tracker_aggregate_forward, get_tracker_aggregator, get_tracker_allow_get, get_tracker_allowed_controls, get_tracker_allowed_dir, get_tracker_allowed_ips, get_tracker_allowed_list, get_tracker_banned_ips, get_tracker_dfile, get_tracker_dfile_format, get_tracker_favicon, get_tracker_hupmonitor, get_tracker_infopage_redirect, get_tracker_ip, get_tracker_keep_dead, get_tracker_log_nat_checks, get_tracker_logfile, get_tracker_min_time_between_cache_refreshes, get_tracker_min_time_between_log_flushes, get_tracker_multitracker_allowed, get_tracker_multitracker_enabled, get_tracker_multitracker_http_timeout, get_tracker_multitracker_maxpeers, get_tracker_multitracker_reannounce_interval, get_tracker_nat_check, get_tracker_only_local_override_ip, get_tracker_parse_dir_interval, get_tracker_reannounce_interval, get_tracker_response_size, get_tracker_save_dfile_interval, get_tracker_scrape_allowed, get_tracker_show_infopage, get_tracker_show_names, get_tracker_socket_timeout, get_tracker_timeout_check_interval, get_tracker_timeout_downloaders_interval, get_upnp_mode, get_video_analyser_path, get_videoplayerpath, olthread_set_start_recommender, olthread_set_stop_collecting_threshold, olthread_set_torrent_collecting_max_torrents, olthread_set_torrent_collecting_rate, set_autoclose_check_interval, set_autoclose_timeout, set_bartercast, set_bind_to_addresses, set_buddycast, set_buddycast_collecting_solution, set_buddycast_interval, set_buddycast_max_peers, set_dialback, set_dialback_active, set_dialback_trust_superpeers, set_download_help, set_download_help_dir, set_install_dir, set_internal_tracker, set_listen_port, set_mainline_dht, set_megacache, set_mugshot, set_nat_detect, set_nickname, set_overlay, set_overlay_log, set_overlay_max_message_length, set_peer_icon_path, set_permid_keypair_filename, set_pingback_servers, set_puncturing_coordinators, set_puncturing_private_port, set_rquery, set_socnet, set_start_recommender, set_state_dir, set_stop_collecting_threshold, set_stun_servers, set_superpeer, set_superpeer_file, set_torrent_checking, set_torrent_checking_period, set_torrent_collecting, set_torrent_collecting_dir, set_torrent_collecting_max_torrents, set_torrent_collecting_rate, set_tracker_aggregate_forward, set_tracker_aggregator, set_tracker_allow_get, set_tracker_allowed_controls, set_tracker_allowed_dir, set_tracker_allowed_ips, set_tracker_allowed_list, set_tracker_banned_ips, set_tracker_dfile, set_tracker_dfile_format, set_tracker_favicon, set_tracker_hupmonitor, set_tracker_infopage_redirect, set_tracker_ip, set_tracker_keep_dead, set_tracker_log_nat_checks, set_tracker_logfile, set_tracker_min_time_between_cache_refreshes, set_tracker_min_time_between_log_flushes, set_tracker_multitracker_allowed, set_tracker_multitracker_enabled, set_tracker_multitracker_http_timeout, set_tracker_multitracker_maxpeers, set_tracker_multitracker_reannounce_interval, set_tracker_nat_check, set_tracker_only_local_override_ip, set_tracker_parse_dir_interval, set_tracker_reannounce_interval, set_tracker_response_size, set_tracker_save_dfile_interval, set_tracker_scrape_allowed, set_tracker_show_infopage, set_tracker_show_names, set_tracker_socket_timeout, set_tracker_timeout_check_interval, set_tracker_timeout_downloaders_interval, set_upnp_mode, set_videoplayerpath

Inherited from SessionConfig.SessionConfigInterface: get_coopdlconfig, get_crawler, get_ip_for_tracker, get_remote_query, get_social_networking, set_coopdlconfig, set_crawler, set_internal_tracker_url, set_ip_for_tracker, set_remote_query, set_social_networking, set_video_analyser_path

Static Methods
 
get_instance(*args, **kw)
Returns the Session singleton if it exists or otherwise creates it first, in which case you need to pass the constructor params.
 
get_default_state_dir(homedirpostfix='.Tribler')
Returns the factory default directory for storing session state on the current platform (Win32,Mac,Unix).
 
get_default_config_filename(state_dir)
Return the name of the file where a session config is saved by default.
Method Details

__init__(self, scfg=None, ignore_singleton=False)
(Constructor)

 
A Session object is created which is configured following a copy of the SessionStartupConfig scfg. (copy constructor used internally)
Parameters:
  • scfg - SessionStartupConfig object or None, in which case we look for a saved session in the default location (state dir). If we can't find it, we create a new SessionStartupConfig() object to serve as startup config. Next, the config is saved in the directory indicated by its 'state_dir' attribute. In the current implementation only a single session instance can exist at a time in a process. The ignore_singleton flag is used for testing.
Overrides: SessionConfig.SessionConfigInterface.__init__

get_instance(*args, **kw)
Static Method

 
Returns the Session singleton if it exists or otherwise creates it first, in which case you need to pass the constructor params.
Returns:
Session.

get_default_state_dir(homedirpostfix='.Tribler')
Static Method

 
Returns the factory default directory for storing session state on the current platform (Win32,Mac,Unix).
Returns:
An absolute path name.

start_download(self, tdef, dcfg=None)

 
Creates a Download object and adds it to the session. The passed TorrentDef and DownloadStartupConfig are copied into the new Download object. The Download is then started and checkpointed. If a checkpointed version of the Download is found, that is restarted overriding the saved DownloadStartupConfig is "dcfg" is not None.
Parameters:
  • tdef - A finalized TorrentDef
  • dcfg - DownloadStartupConfig or None, in which case a new DownloadStartupConfig() is created with its default settings and the result becomes the runtime config of this Download.
Returns:
Download

resume_download_from_file(self, filename)

 
Recreates Download from resume file
Returns:
a Download object. Note: this cannot be made into a method of Download, as the Download needs to be bound to a session, it cannot exist independently.

get_downloads(self)

 
Returns a copy of the list of Downloads.
Returns:
A list of Download objects.

remove_download(self, d, removecontent=False)

 
Stops the download and removes it from the session.
Parameters:
  • d - The Download to remove
  • removecontent - Whether to delete the already downloaded content from disk.

set_download_states_callback(self, usercallback, getpeerlist=False)

 
See Download.set_state_callback. Calls usercallback with a list of DownloadStates, one for each Download in the Session as first argument. The usercallback must return a tuple (when,getpeerlist) that indicates when to reinvoke the callback again (as a number of seconds from now, or < 0.0 if not at all) and whether to also include the details of the connected peers in the DownloadStates on that next call. The callback will be called by a popup thread which can be used indefinitely (within reason) by the higher level code.
Parameters:
  • usercallback - A function adhering to the above spec.

get_permid(self)

 
Returns the PermID of the Session, as determined by the SessionConfig.set_permid() parameter. A PermID is a public key
Returns:
The PermID encoded in a string in DER format.

get_external_ip(self)

 
Returns the external IP address of this Session, i.e., by which it is reachable from the Internet. This address is determined via various mechanisms such as the UPnP protocol, our dialback mechanism, and an inspection of the local network configuration.
Returns:
A string.

get_current_startup_config_copy(self)

 
Returns a SessionStartupConfig that is a copy of the current runtime SessionConfig.
Returns:
SessionStartupConfig

get_internal_tracker_url(self)

 
Returns the announce URL for the internal tracker.
Returns:
URL
Overrides: SessionConfig.SessionConfigInterface.get_internal_tracker_url

get_internal_tracker_dir(self)

 
Returns the directory containing the torrents tracked by the internal tracker (and associated databases).
Returns:
An absolute path.

add_to_internal_tracker(self, tdef)

 
Add a torrent def to the list of torrents tracked by the internal tracker. Use this method to use the Session as a standalone tracker.
Parameters:
  • tdef - A finalized TorrentDef.

remove_from_internal_tracker(self, tdef)

 
Remove a torrent def from the list of torrents tracked by the internal tracker. Use this method to use the Session as a standalone tracker.
Parameters:
  • tdef - A finalized TorrentDef.

remove_from_internal_tracker_by_infohash(self, infohash)

 
Remove a torrent def from the list of torrents tracked by the internal tracker. Use this method to use the Session as a standalone tracker.
Parameters:
  • infohash - Identifier of the torrent def to remove.

add_observer(self, func, subject, changeTypes=['update', 'insert', 'delete'], objectID=None)

 
Add an observer function function to the Session. The observer function will be called when one of the specified events (changeTypes) occurs on the specified subject. The function will be called by a popup thread which can be used indefinitely (within reason) by the higher level code.
Parameters:
  • func - The observer function. It should accept as its first argument the subject, as second argument the changeType, as third argument an objectID (e.g. the primary key in the observed database) and an optional list of arguments.
  • subject - The subject to observe, one of NTFY_* subjects (see simpledefs).
  • changeTypes - The list of events to be notified of one of NTFY_* events.
  • objectID - The specific object in the subject to monitor (e.g. a specific primary key in a database to monitor for updates.) TODO: Jelle will add per-subject/event description here ;o)

remove_observer(self, func)

 
Remove observer function. No more callbacks will be made.
Parameters:
  • func - The observer function to remove.

open_dbhandler(self, subject)

 
Opens a connection to the specified database. Only the thread calling this method may use this connection. The connection must be closed with close_dbhandler() when this thread exits.
Parameters:
  • subject - The database to open. Must be one of the subjects specified here.
Returns:
A reference to a DBHandler class for the specified subject or None when the Session was not started with megacaches enabled.
 NTFY_PEERS -> PeerDBHandler
NTFY_TORRENTS -> TorrentDBHandler
NTFY_PREFERENCES -> PreferenceDBHandler
NTFY_SUPERPEERS -> SuperpeerDBHandler
NTFY_FRIENDS -> FriendsDBHandler
NTFY_MYPREFERENCES -> MyPreferenceDBHandler
NTFY_BARTERCAST -> BartercastDBHandler

set_overlay_request_policy(self, reqpol)

 
Set a function which defines which overlay requests (e.g. dl_helper, rquery msg) will be answered or will be denied. The function will be called by a network thread and must return as soon as possible to prevent performance problems.
Parameters:
  • reqpol - is a Tribler.Core.RequestPolicy.AbstractRequestPolicy object.

load_checkpoint(self, initialdlstatus=None)

 
Restart Downloads from checkpoint, if any. This method allows the API user to manage restoring downloads. E.g. a video player that wants to start the torrent the user clicked on first, and only then restart any sleeping torrents (e.g. seeding). The optional initialdlstatus parameter can be set to DLSTATUS_STOPPED to restore all the Downloads in DLSTATUS_STOPPED state.

shutdown(self, checkpoint=True, gracetime=2.0, hacksessconfcheckpoint=True)

 
Checkpoints the session and closes it, stopping the download engine.
Parameters:
  • checkpoint - Whether to checkpoint the Session state on shutdown.
  • gracetime - Time to allow for graceful shutdown + signoff (seconds).

query_connected_peers(self, query, usercallback, max_peers_to_query=None)

 
Ask all Tribler peers we're currently connected to resolve the specified query and return the hits. For each peer that returns hits the usercallback method is called with first parameter the permid of the peer, as second parameter the query string and as third parameter a dictionary of hits. The number of times the usercallback method will be called is undefined. The callback will be called by a popup thread which can be used indefinitely (within reason) by the higher level code. At the moment we support one type of query, which is a query for torrent files that match a set of keywords. The format of the query string is "SIMPLE kw1 kw2 kw3". In the future we plan to support full SQL queries. For SIMPLE queries the dictionary of hits consists of (infohash,torrentrecord) pairs. The torrentrecord is a dictionary that contains the following keys:
* 'content_name': The 'name' field of the torrent.
* 'length': The total size of the content in the torrent.
* 'leecher': The currently known number of downloaders.
* 'seeder': The currently known number of seeders.
* 'category': A list of category strings the torrent was classified into
  by the remote peer.
Parameters:
  • query - A Unicode query string adhering to the above spec.
  • usercallback - A function adhering to the above spec.

download_torrentfile_from_peer(self, permid, infohash, usercallback)

 
Ask the designated peer to send us the torrentfile for the torrent identified by the passed infohash. If the torrent is succesfully received, the usercallback method is called with the infohash as first and the contents of the torrentfile (bencoded dict) as second parameter. If the torrent could not be obtained, the callback is not called. The torrent will have been added to the TorrentDBHandler (if enabled) at the time of the call.
Parameters:
  • permid - The PermID of the peer to query.
  • infohash - The infohash of the torrent.
  • usercallback - A function adhering to the above spec.

checkpoint_shutdown(self, stop, checkpoint, gracetime, hacksessconfcheckpoint)

 
Checkpoints the Session and optionally shuts down the Session.
Parameters:
  • stop - Whether to shutdown the Session as well.
  • checkpoint - Whether to checkpoint at all, or just to stop.
  • gracetime - Time to allow for graceful shutdown + signoff (seconds).

get_default_config_filename(state_dir)
Static Method

 
Return the name of the file where a session config is saved by default.
Returns:
A filename

get_internal_tracker_torrentfilename(self, infohash)

 
Return the absolute pathname of the torrent file used by the internal tracker.
Returns:
A filename

get_nat_type(self, callback=None)

 
Return the type of Network Address Translator (NAT) detected. When a callback parameter is supplied it will always be called. When the NAT-type is already known the callback will be made instantly. Otherwise, the callback will be made when the NAT discovery has finished. The callback will be called by a popup thread which can be used indefinitely (within reason) by the higher level code. Return values: "Blocked" "Open Internet" "Restricted Cone Firewall" "Port Restricted Cone Firewall" "Full Cone NAT" "Restricted Cone NAT" "Port Restricted Cone NAT" "Symmetric NAT" "Unknown NAT/Firewall"
Parameters:
  • callback - Optional callback used to notify the NAT type
Returns:
String

send_friendship_message(self, permid, mtype, approved=None)

 
Send friendship msg to the specified peer F_REQUEST_MSG: F_RESPONSE_MSG:
Parameters:
  • approved - Whether you want him as friend or not.

set_friendship_callback(self, usercallback)

 
When a new friendship request is received the given callback function is called with as first parameter the requester's permid and as second parameter a dictionary of request arguments: callback(requester_permid,params) The callback is called by a popup thread which can be used indefinitely (within reason) by the higher level code.
Parameters:
  • usercallback - A callback function adhering to the above spec.