def _init_session(self): dht_state = self._get_storage_value("dht_state") if dht_state: ses = lt.session(dht_state) else: ses = lt.session() ses.listen_on(settings.START_PORT, settings.END_PORT) self._session = ses
def create_session(self, hops=0): settings = lt.session_settings() if hops == 0: settings.user_agent = 'Tribler/' + version_id # Elric: Strip out the -rcX, -beta, -whatever tail on the version string. fingerprint = ['TL'] + map(int, version_id.split('-')[0].split('.')) + [0] # Workaround for libtorrent 0.16.3 segfault (see https://code.google.com/p/libtorrent/issues/detail?id=369) ltsession = lt.session(lt.fingerprint(*fingerprint), flags=1) enable_utp = self.trsession.get_libtorrent_utp() settings.enable_outgoing_utp = enable_utp settings.enable_incoming_utp = enable_utp pe_settings = lt.pe_settings() pe_settings.prefer_rc4 = True ltsession.set_pe_settings(pe_settings) else: settings.enable_outgoing_utp = True settings.enable_incoming_utp = True settings.enable_outgoing_tcp = False settings.enable_incoming_tcp = False settings.anonymous_mode = True # No PEX for anonymous sessions ltsession = lt.session(flags=0) ltsession.add_extension(lt.create_ut_metadata_plugin) ltsession.add_extension(lt.create_smart_ban_plugin) ltsession.set_settings(settings) ltsession.set_alert_mask(lt.alert.category_t.stats_notification | lt.alert.category_t.error_notification | lt.alert.category_t.status_notification | lt.alert.category_t.storage_notification | lt.alert.category_t.performance_warning | lt.alert.category_t.tracker_notification) # Load proxy settings if hops == 0: proxy_settings = self.trsession.get_libtorrent_proxy_settings() else: proxy_settings = list(self.trsession.get_anon_proxy_settings()) proxy_host, proxy_ports = proxy_settings[1] proxy_settings[1] = (proxy_host, proxy_ports[hops - 1]) self.set_proxy_settings(ltsession, *proxy_settings) # Set listen port & start the DHT if hops == 0: listen_port = self.trsession.get_listen_port() ltsession.listen_on(listen_port, listen_port + 10) if listen_port != ltsession.listen_port(): self.trsession.set_listen_port_runtime(ltsession.listen_port()) try: dht_state = open(os.path.join(self.trsession.get_state_dir(), DHTSTATE_FILENAME)).read() ltsession.start_dht(lt.bdecode(dht_state)) except Exception, exc: self._logger.info("could not restore dht state, got exception: %r. starting from scratch" % exc) ltsession.start_dht(None)
def setUp(self): # need to keep reference to session() to prevent GC picking it up self.session = session = libtorrent.session() session.listen_on(6881, 6882) torrent = libtorrent.bdecode(open(self.torrent, 'rb').read()) info = libtorrent.torrent_info(torrent) self.transfer = session.add_torrent(info, tempfile.gettempdir())
def get_subtitle(magnet, lang): print("Obtaining subtitle (experimental, might take a while)") lt_session = session() params = {"save_path": "/tmp"} handle = add_magnet_uri(lt_session, magnet, params) while (not handle.has_metadata()): sleep(.1) info = handle.get_torrent_info() files = info.files() biggest_file = ("", 0) for file_ in files: if file_.size > biggest_file[1]: biggest_file = [file_.path, file_.size] print("Guessing data") filepath = biggest_file[0] guess = guess_video_info(filepath, info = ['filename']) video = Video.fromguess(filepath, guess) video.size = biggest_file[1] print("Donwloading Subtitle") subtitle = download_best_subtitles([video], {Language(lang)}, single=True) if not len(subtitle): subtitle = None else: subtitle = get_subtitle_path(video.name) lt_session.remove_torrent(handle) return subtitle
def run(self): # New Session # fingerprint = lt.fingerprint("AZ", 3, 0, 5, 0) # settings = lt.session_settings() # settings.user_agent = "Azerus 3.0.5.0" # ses = lt.session(fingerprint) ses = lt.session() ses.listen_on(6881, 6891) self.torrentHandle = ses.add_torrent({ 'ti': self.info, 'save_path': self.output, }) self.torrentHandle.set_download_limit(10000) self.torrentHandle.set_upload_limit(self.uploadLimit) self.torrentHandle.set_sequential_download(True) # New Torrent torrentName = self.torrentHandle.name() self.Print('INITIALISATION') # Replace Tracker if self.replacePasskey: self.trHack() # Downloading if(not self.torrentHandle.is_seed()): self.Downloading() del ses # Stop if needed if self.toStop: return # Complete self.PrintStatus = True self.Print('COMPLETED') os.remove(self.torrentFile)
def _get_session(createIfNeeded=True): global _lt_sess if _lt_sess is None and createIfNeeded: _lt_sess = lt.session() _lt_sess.set_download_rate_limit(sickbeard.LIBTORRENT_MAX_DL_SPEED * 1024) _lt_sess.set_upload_rate_limit(sickbeard.LIBTORRENT_MAX_UL_SPEED * 1024) settings = lt.session_settings() settings.user_agent = 'sickbeard_bricky-%s/%s' % (version.SICKBEARD_VERSION.replace(' ', '-'), lt.version) settings.rate_limit_utp = True # seems this is rqd, otherwise uTP connections don't obey the rate limit settings.active_downloads = 8 settings.active_seeds = 12 settings.active_limit = 20 _lt_sess.listen_on(sickbeard.LIBTORRENT_PORT_MIN, sickbeard.LIBTORRENT_PORT_MAX) _lt_sess.set_settings(settings) _lt_sess.set_alert_mask(lt.alert.category_t.error_notification | #lt.alert.category_t.port_mapping_notification | lt.alert.category_t.storage_notification | #lt.alert.category_t.tracker_notification | lt.alert.category_t.status_notification | #lt.alert.category_t.port_mapping_notification | lt.alert.category_t.performance_warning ) try: state = {} # @todo: save/restore this _lt_sess.start_dht(state) _lt_sess.add_dht_router('router.bittorrent.com', 6881) _lt_sess.add_dht_router('router.utorrent.com', 6881) _lt_sess.add_dht_router('router.bitcomet.com', 6881) except Exception, ex: # just ignore any dht errors, this is just for bootstrapping logger.log(u'Exception starting dht: ' + str(ex), logger.WARNING)
def get_torrent_info_magnet(v1,v3,u,p_bar,tmp_dir): global handle,ses,info,cnt,cnt_limit,file_name,ui,progress,tmp_dir_folder ui = u progress = p_bar tmp_dir_folder = tmp_dir progress.setValue(0) progress.show() #print(v1,'------------hello----------info---') sett = lt.session_settings() sett.user_agent = 'qBittorrent v3.3.5' sett.always_send_user_agent = True fingerprint = lt.fingerprint('qB',3,3,5,0) ses = lt.session(fingerprint) ses.listen_on(40000, 50000) ses.set_settings(sett) handle = lt.add_magnet_uri(ses,v1,{'save_path':v3}) i = 0 while (not handle.has_metadata()): time.sleep(1) i = i+1 print('finding metadata') if i > 300: print('No Metadata Available') break info = handle.get_torrent_info() handle.set_sequential_download(True) print(handle.trackers()) return handle,ses,info
def __init__(self, path_to_store, args=None, state_file="~/.btclient_state", **kwargs): super(BTClient,self).__init__(path_to_store, args=args) self._torrent_params={'save_path':path_to_store, 'storage_mode':lt.storage_mode_t.storage_mode_sparse } self._state_file=os.path.expanduser(state_file) self._ses=lt.session() if os.path.exists(self._state_file): with open(self._state_file) as f: state=pickle.load(f) self._ses.load_state(state) #self._ses.set_alert_mask(lt.alert.category_t.progress_notification) if args: s=lt.session_settings() s.download_rate_limit=int(round(args.bt_download_limit*1024)) s.upload_rate_limit=int(round(args.bt_upload_limit*1024)) self._ses.set_settings(s) self._ses.listen_on(args.listen_port_min, args.listen_port_max) else: self._ses.listen_on(6881, 6891) self._start_services() self._th=None self._monitor.add_listener(self._check_ready) self._dispatcher=BTClient.Dispatcher(self) self._dispatcher.add_listener(self._update_ready_pieces) self._hash = None self._url=None if args and args.debug_log and args.trace: self.add_monitor_listener(self.debug_download_queue) self.add_dispatcher_listener(self.debug_alerts)
def __init__(self): '''Starts a bittorrent client''' log.info('Starting bittorrent client') # Settings self.session = lt.session() session_settings = lt.session_settings() session_settings.user_agent = '%s libtorrent/%d.%d' % (settings.SOFTWARE_USER_AGENT, lt.version_major, lt.version_minor) session_settings.active_downloads = settings.BITTORRENT_MAX_DOWNLOADS + settings.BITTORRENT_MAX_METADATA_DOWNLOADS session_settings.active_seeds = settings.BITTORRENT_MAX_SEEDS session_settings.active_limit = settings.BITTORRENT_MAX_DOWNLOADS + settings.BITTORRENT_MAX_SEEDS + settings.BITTORRENT_MAX_METADATA_DOWNLOADS self.session.set_settings(session_settings) # Start BT server ports = settings.BITTORRENT_PORTS self.session.listen_on(ports[0], ports[1]) # Start DHT server dht_data = get_cache('bt_dht_data') self.session.start_dht(dht_data) self.params = { 'save_path': settings.DOWNLOAD_DIR.encode('ascii'), # FIXME: support non-ascii characters 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True} self.handle_dict = {}
def downloadTorrent (torrent ): torrent="test.torrent" ses = lt.session() ses.listen_on(TORRENT_PORT1, TORRENT_PORT2) e = lt.bdecode(open(torrent, 'rb').read()) info = lt.torrent_info(e) params = { "save_path": '.', \ "storage_mode": lt.storage_mode_t.storage_mode_sparse, \ "ti": info } h = ses.add_torrent(params) s = h.status() while (not s.is_seeding): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating'] print( '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ s.num_peers, state_str[s.state])) time.sleep(1)
def test_alert(self): ses = lt.session({"alert_mask": lt.alert.category_t.all_categories}) shutil.copy(os.path.join("..", "..", "test", "test_torrents", "base.torrent"), ".") ti = lt.torrent_info("base.torrent") h = ses.add_torrent({"ti": ti, "save_path": "."}) time.sleep(1) ses.remove_torrent(h) ses.wait_for_alert(1000) # milliseconds alerts = ses.pop_alerts() for a in alerts: print(a.message()) st = h.status() print(st.next_announce) print(st.name) print(st.errc.message()) print(st.pieces) print(st.last_seen_complete) print(st.completed_time) print(st.progress) print(st.num_pieces) print(st.distributed_copies) print(st.paused) print(st.info_hash)
def download(clientType): if clientType == "server": dest = "" else: dest = expanduser("~") + "\Downloads" ses = lt.session() ses.listen_on(6881, 6901) #keep trying to bind to a port till set value torrentContent = lt.bdecode(open("t.torrent", 'rb').read()) info = lt.torrent_info(torrentContent) if clientType == "server": h = ses.add_torrent({'ti': info, 'save_path': dest, 'seed_mode': True}) else: h = ses.add_torrent({'ti': info, 'save_path': dest}) while (not h.is_seed()): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] #print '\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ # (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ # s.num_peers, state_str[s.state]), #sys.stdout.flush() if clientType != "server": progressSender(str(s.progress * 100)) time.sleep(1) if clientType != "server": print "Download completed" progressSender("Done") print "Seeding...\nCtrl+C to stop" while h.is_seed(): time.sleep(1) #keep process from getting garbage collected?
def test_scrape(self): ses = lt.session({"alert_mask": lt.alert.category_t.all_categories, "enable_dht": False}) ti = lt.torrent_info("url_seed_multi.torrent") h = ses.add_torrent({"ti": ti, "save_path": os.getcwd()}) # this is just to make sure this function can be called like this # from python h.scrape_tracker()
def test_read_resume_data(self): resume_data = lt.bencode( { "file-format": "libtorrent resume file", "info-hash": "abababababababababab", "name": "test", "save_path": ".", "peers": "\x01\x01\x01\x01\x00\x01\x02\x02\x02\x02\x00\x02", "file_priority": [0, 1, 1], } ) tp = lt.read_resume_data(resume_data) self.assertEqual(tp.name, "test") self.assertEqual(tp.info_hash, lt.sha1_hash("abababababababababab")) self.assertEqual(tp.file_priorities, [0, 1, 1]) self.assertEqual(tp.peers, [("1.1.1.1", 1), ("2.2.2.2", 2)]) ses = lt.session({"alert_mask": lt.alert.category_t.all_categories}) h = ses.add_torrent(tp) h.connect_peer(("3.3.3.3", 3)) for i in range(0, 10): alerts = ses.pop_alerts() for a in alerts: print(a.message()) time.sleep(0.1)
def magnetToTorrent(self, magnet): session = libtorrent.session() session.start_dht() session.add_dht_router("router.bittorrent.com", 6881) session.add_dht_router("router.utorrent.com", 6881) session.add_dht_router("router.bitcomet.com", 6881) session.listen_on(6881, 6891) session.set_alert_mask(libtorrent.alert.category_t.storage_notification) handle = libtorrent.add_magnet_uri(session, magnet, {'save_path': self.storageDirectory}) iterator = 0 progressBar = xbmcgui.DialogProgress() progressBar.create('Подождите', 'Идёт преобразование magnet-ссылки.') while not handle.has_metadata(): time.sleep(0.1) progressBar.update(iterator) iterator += 1 if iterator == 100: iterator = 0 if progressBar.iscanceled(): progressBar.update(0) progressBar.close() return progressBar.update(0) progressBar.close() torrent = libtorrent.create_torrent(handle.get_torrent_info()) torentFile = open(self.torrentFile, "wb") torentFile.write(libtorrent.bencode(torrent.generate())) torentFile.close() session.remove_torrent(handle)
def __init__(self, upload_limit=-1, download_limit=-1, status_mail=False): threading.Thread.__init__(self) if status_mail: self.status_mail = True try: email_config_file = open(EMAIL_CONFIG, "r") self.config = json.load(email_config_file) email_config_file.close() # check for necessary fields self.config["username"] self.config["password"] self.config["recipient"] log(green("Status mails successfully enabled")) except: log(yellow("Error while pasing email config, disabling status_mail")) self.status_mail = False self.files = dict() self.session = lt.session() self.session.listen_on(6881, 6891) self.torrent_dir = ".torrents" self.download_dir = "Downloads" self.do_things = True settings = self.session.settings() if upload_limit != -1: log(blue("Upload limit set to non-default value: " + str(upload_limit))) settings.upload_rate_limit = upload_limit if download_limit != -1: log(blue("Download limit set to non-default value: " + str(download_limit))) settings.download_rate_limit = download_limit self.session.set_settings(settings)
def test_cache_info(self): ses = lt.session({"alert_mask": lt.alert.category_t.all_categories, "enable_dht": False}) ti = lt.torrent_info("url_seed_multi.torrent") h = ses.add_torrent({"ti": ti, "save_path": os.getcwd()}) cs = ses.get_cache_info(h) self.assertEqual(cs.pieces, [])
def test_post_session_stats(self): s = lt.session({"alert_mask": lt.alert.category_t.stats_notification}) s.post_session_stats() a = s.wait_for_alert(1000) self.assertTrue(isinstance(a, lt.session_stats_alert)) self.assertTrue(isinstance(a.values, dict)) self.assertTrue(len(a.values) > 0)
def urlDown(self): leech_torrent = GetMagnetLink() links = leech_torrent.getKickass() for i in links: name = re.findall(self.name_regex, i) self.save_path += str(name[0]) print self.save_path ses = lt.session() ses.listen_on(6881, 6891) params = {'save_path': self.save_path, 'storage_mode': lt.storage_mode_t.storage_mode_sparse, 'url': i} handle = ses.add_torrent(params) while True: s = handle.status() print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, s.state) self.timex += 1 if self.timex > 43200: break if s.total_upload > 0 and s.total_download > 0: ratio = (s.total_upload / s.total_download) if handle.is_seed() and ratio >= self.seed_ratio: break print 'Share ratio: ', "{:.1f}".format(ratio) if handle.is_seed(): ses.remove_torrent(handle) break time.sleep(1) return True
def download_iso(self): if not self.magnet_link: LOG.error("magnet_link for newtest Fuel ISO not found. Aborted") return None session = lt.session() session.listen_on(6881, 6891) params = { 'save_path': self.path, 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True} handle = lt.add_magnet_uri(session, self.magnet_link, params) session.start_dht() while not handle.has_metadata(): time.sleep(1) filename = handle.get_torrent_info().files()[0].path LOG.debug('Got metadata, starting torrent download...') while handle.status().state != lt.torrent_status.seeding: status = handle.status() state_str = ['queued', 'checking', 'downloading metadata', 'downloading', 'finished', 'seeding', 'allocating'] LOG.info('{0:.2f}% complete (down: {1:.1f} kb/s up: {2:.1f} kB/s ' 'peers: {3:d}) {4:s} {5:d}.3' .format(status.progress * 100, status.download_rate / 1000, status.upload_rate / 1000, status.num_peers, state_str[status.state], status.total_download / 1000000)) time.sleep(5) LOG.info('Ready for deploy iso {0}'.format(filename)) return '/'.join([self.path, filename])
def download_torrent(magnet): tempdir = tempfile.mkdtemp() ses = libtorrent.session() params = { 'save_path': tempdir, 'duplicate_is_error': True, 'storage_mode': libtorrent.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } handle = libtorrent.add_magnet_uri(ses, magnet, params) _wait_for_metadata(handle) ses.pause() # Exract torrent file content torinfo = handle.get_torrent_info() # Cleanup ses.remove_torrent(handle) shutil.rmtree(tempdir) return libtorrent.create_torrent(torinfo), torinfo.name()
def ActionDNLDTorrent(logger, args): ses = lt.session() ses.listen_on(args["portStart"], args["portEnd"]) info = lt.torrent_info(args["torrentFile"]) h = ses.add_torrent({'ti': info, 'save_path': args["destPath"], 'storage_mode': (lt.storage_mode_t.storage_mode_allocate if args["allocateStorage"] else lt.storage_mode_t.storage_mode_sparse) }) logger.info("Starting [%s]" % h.name()) while (not h.is_seed()): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] print '\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ s.num_peers, state_str[s.state]), sys.stdout.flush() time.sleep(1) logger.info("Completed [%s]" % h.name())
def start(self, torrent_file, port=6881): if not os.path.isdir('log'): os.mkdir('log') self.ses = lt.session() self.ses.set_alert_mask(lt.alert.category_t.status_notification | 0x400) # lt.alert.category_t.dht_notification self.ses.listen_on(port, port) self.ses.start_dht() self.ses.add_dht_router("router.bittorrent.com", 6881) self.ses.add_dht_router("router.utorrent.com", 6881) self.ses.add_dht_router("router.bitcomet.com", 6881) e = lt.bdecode(open(torrent_file, 'rb').read()) info = lt.torrent_info(e) # info = lt.torrent_info(torrent_file) h = self.ses.add_torrent({'ti': info, 'save_path': './'}) while not h.is_seed(): alert = self.ses.pop_alert() while alert is not None: self.handle_alert(alert) alert = self.ses.pop_alert() time.sleep(0.1) self.ses.remove_torrent(h) while True: alert = self.ses.pop_alert() while alert is not None: self.handle_alert(alert) alert = self.ses.pop_alert() time.sleep(0.1)
def downloadtorrent(link): try: params = { 'save_path' : savePath, 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } #Inicia o Download ses = lt.session() ses.listen_on(6881, 6891) handle = lt.add_magnet_uri(ses, link, params) ses.start_dht() while (not handle.has_metadata()): time.sleep(1) while (handle.status().state != lt.torrent_status.seeding): s = handle.status() time.sleep(5) except: pass
def start(self): cherrypy.process.plugins.Monitor.start(self) self.bus.log('[Downloader] Starting session') self.session = libtorrent.session() self.session.set_alert_mask(libtorrent.alert.category_t.error_notification | libtorrent.alert.category_t.status_notification | libtorrent.alert.category_t.storage_notification) self.session.start_dht() self.session.start_lsd() self.session.start_upnp() self.session.start_natpmp() self.session.listen_on(self.torrent_config['port'], self.torrent_config['port']) # Session settings session_settings = self.session.settings() session_settings.announce_to_all_tiers = True session_settings.announce_to_all_trackers = True session_settings.connection_speed = 100 session_settings.peer_connect_timeout = 2 session_settings.rate_limit_ip_overhead = True session_settings.request_timeout = 5 session_settings.torrent_connect_boost = 100 if self.torrent_config['max_download_rate'] > 0: session_settings.download_rate_limit = self.torrent_config['max_download_rate'] * 1024 if self.torrent_config['max_upload_rate'] > 0: session_settings.upload_rate_limit = self.torrent_config['max_upload_rate'] * 1024 self.session.set_settings(session_settings) # Encryption settings encryption_settings = libtorrent.pe_settings() encryption_settings.out_enc_policy = libtorrent.enc_policy(libtorrent.enc_policy.forced) encryption_settings.in_enc_policy = libtorrent.enc_policy(libtorrent.enc_policy.forced) encryption_settings.allowed_enc_level = libtorrent.enc_level.both encryption_settings.prefer_rc4 = True self.session.set_pe_settings(encryption_settings)
def getTorrentContents (self, torrentFile): ses = lt.session() #ses.listen_on(6881, 6891) info = lt.torrent_info(torrentFile) files = [] shouldDownload = False for file in info.files(): if(self.extensionMatch(file.path)): shouldDownload=True files.append(file.path) if(shouldDownload): h = ses.add_torrent({'ti': info, 'save_path': './'}) h.set_upload_limit(self.maxUploadSpeed*1024) h.set_download_limit(self.maxDownloadSpeed*1024) while (not h.is_seed()): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] #print '\r %.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ # (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ # s.num_peers, state_str[s.state]), sys.stdout.flush() time.sleep(1) else: del info del ses return files
def multiDownload(self): self.ses = lt.session() self.ses.listen_on(6881, 6891) ses=self.ses; #pre add 3 torrents for i in range(3):self.addTorrent(self.link_torrent_list.pop(0)); while True: completedCount=0; torrentCount=0 for handle in self.handleList[:]: torrentCount+=1; s = handle.status() print 'Torrent No.%d = %.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % (torrentCount,s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000,s.num_peers, s.state) if s.total_upload > 0 and s.total_download > 0: ratio = (s.total_upload / s.total_download) print 'Share ratio: ', "{:.1f}".format(ratio) if handle.is_seed() and ratio >= self.seed_ratio: ses.remove_torrent(handle) self.handleList.remove(handle); completedCount+=1; print "Torrent No.%d is completed!"%(torrentCount); for i in range(completedCount): if len(self.link_torrent_list)>0: self.addTorrent(self.link_torrent_list.pop(0)); if len(self.handleList)==0 and len(self.link_torrent_list)==0:break;#all completed time.sleep(2)
def rebind(self): self.ses = lt.session() self.ses.set_alert_mask(lt.alert.category_t.progress_notification) self.ses.listen_on(6881, 6891) for torrent in self.torrents: torrent.session = self torrent.rebind()
def __init__(self): self.session = lt.session() self.session.listen_on(6881, 6891) self.session.set_alert_mask( lt.alert.category_t.error_notification | lt.alert.category_t.storage_notification | lt.alert.category_t.status_notification | lt.alert.category_t.progress_notification | lt.alert.category_t.performance_warning) self.torrents = {} self.limits_updated = False settings = lt.session_settings() # TODO: set upload ratio settings, rate limits, etc settings.user_agent = 'Downpour/%s libtorrent/%d.%d' % (VERSION, lt.version_major, lt.version_minor) # settings.share_ratio_limit = float(self.manager.get_setting('upload_ratio', 0)) self.session.set_settings(settings) # Update torrent status self.status_update = task.LoopingCall(self.status_update) self.status_update.start(2.0) # Process generated alerts self.alert_monitor = task.LoopingCall(self.process_alerts) self.alert_monitor.start(2.0) # Update rate / connection limits self.limit_update = task.LoopingCall(self.limit_update) self.limit_update.start(5.0)
def magnet2torrent(link, torrent_file): sess = lt.session() sess.add_dht_router('router.bittorrent.com', 6881) sess.add_dht_router('router.utorrent.com', 6881) sess.add_dht_router('router.bitcomet.com', 6881) sess.add_dht_router('dht.transmissionbt.com', 6881) sess.start_dht(); params = { "save_path": 'D:\\Desktop', #"storage_mode":lt.storage_mode_t.storage_mode_sparse, #"paused": True, #"auto_managed": True, "duplicate_is_error": True } handle = lt.add_magnet_uri(sess, link, params) # waiting for metadata while (not handle.has_metadata()): time.sleep(5) # create a torrent torinfo = handle.get_torrent_info() torfile = lt.create_torrent(torinfo) torcontent = lt.bencode(torfile.generate()) # save to file t = open(torrent_file, "wb") t.write(torcontent) t.close() return True
def seed(cls, torrent_path, save_path, seed_mode=True): ses = libtorrent.session() ses.listen_on(6881, 6891) h = ses.add_torrent({ 'ti': libtorrent.torrent_info(torrent_path), 'save_path': save_path, 'seed_mode': seed_mode, }) while True: s = h.status() state_str = ['queued', 'checking', 'downloading metadata', 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] print('\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state])) sys.stdout.flush() time.sleep(1)
def process(self, entry, destination_folder, scrape, timeout): import libtorrent magnet_uri = entry['url'] params = libtorrent.parse_magnet_uri(magnet_uri) session = libtorrent.session() lt_version = [int(v) for v in libtorrent.version.split('.')] if lt_version > [0,16,13,0]: # for some reason the info_hash needs to be bytes but it's a struct called sha1_hash params['info_hash'] = params['info_hash'].to_bytes() handle = libtorrent.add_magnet_uri(session, magnet_uri, params) log.debug('Acquiring torrent metadata for magnet %s', magnet_uri) handle.force_dht_announce() timeout_value = timeout while not handle.has_metadata(): time.sleep(0.1) timeout_value -= 0.1 if timeout_value <= 0: raise plugin.PluginError('Timed out after {} seconds trying to magnetize'.format(timeout)) log.debug('Metadata acquired') torrent_info = handle.get_torrent_info() torrent_file = libtorrent.create_torrent(torrent_info) torrent_path = pathscrub(os.path.join(destination_folder, torrent_info.name() + ".torrent")) with open(torrent_path, "wb") as f: f.write(libtorrent.bencode(torrent_file.generate())) log.debug('Torrent file wrote to %s', torrent_path) # Windows paths need an extra / prepended to them for url if not torrent_path.startswith('/'): torrent_path = '/' + torrent_path entry['url'] = torrent_path entry['file'] = torrent_path # make sure it's first in the list because of how download plugin works entry['urls'].insert(0, 'file://{}'.format(torrent_path)) entry['content_size'] = torrent_info.total_size() / 1024 / 1024 # Might as well get some more info while handle.status(0).num_complete < 0: time.sleep(0.1) timeout_value -= 0.1 if timeout_value <= 0: log.debug('Timed out after {} seconds trying to get peer info'.format(timeout)) return log.debug('Peer info acquired') torrent_status = handle.status(0) entry['torrent_seeds'] = torrent_status.num_complete entry['torrent_leeches'] = torrent_status.num_incomplete
def mag2torr(magnet): tempDir = tempfile.mkdtemp( ) #Directory to store temporary torrent metadata #For libtorrent use params = { 'save_path': tempDir, 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } #Creates a session and a handle, to download data from torrent network sessionT = lt.session() handle = lt.add_magnet_uri(sessionT, magnet, params) while (not handle.has_metadata()): #Wait for completion try: print("Downloading metadata...") sleep(1) except KeyboardInterrupt: print("Aborting...") sessionT.pause() sessionT.remove_torrent(handle) #shutil.rmtree(tempDir) sys.exit(0) sessionT.pause() print("Done") torrentInfo = handle.get_torrent_info() fileName = "m2t_" + torrentInfo.name() + ".torrent" print("Torrent name: " + torrentInfo.name()) #Builds torrent file from downloaded metadata torrentFile = lt.create_torrent(torrentInfo) with open(fileName, "wb") as op: #It is necessary to encode for matching torrent file standards op.write(lt.bencode(torrentFile.generate())) #Cleanup sessionT.remove_torrent(handle) shutil.rmtree(tempDir)
def __init__(self, listening_port=None, dht_routers=[], filelist_dir=None, download_dir=None): self.locks = LockManager() self.session = libtorrent.session() if listening_port: self.session.listen_on(listening_port, listening_port) else: rand = random.randrange(17000, 18000) self.session.listen_on(rand, rand + 10000) for router, port in dht_routers: self.session.add_dht_router(router, port) self.session.start_dht() self.filelist_dir = filelist_dir self.download_dir = download_dir
def getFilenameFromMagnet(magnet): session = libtorrent.session() session.listen_on(6881, 6891) params = { 'save_path': '/home/osmc/tmp', 'storage_mode': libtorrent.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } handle = libtorrent.add_magnet_uri(session, magnet, params) session.start_dht() while not handle.has_metadata(): time.sleep(1) torrentInfo = handle.get_torrent_info() #for x in range(torinfo.files().num_files()): return torrentInfo.files().file_path(0)
def torrent(magnet_link): ses = lt.session() params = { 'save_path': './', 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } handle = lt.add_magnet_uri(ses, magnet_link, params) while (not handle.has_metadata()): time.sleep(.1) info = handle.get_torrent_info() file = lt.create_torrent(info) res = {'name': info.name()} return jsonify(**res)
def test_torrent_handle(self): ses = lt.session({ 'alert_mask': lt.alert.category_t.all_categories, 'enable_dht': False }) ti = lt.torrent_info('url_seed_multi.torrent') h = ses.add_torrent({'ti': ti, 'save_path': os.getcwd()}) h.prioritize_files([0, 1]) self.assertEqual(h.file_priorities(), [0, 1]) h.prioritize_pieces([0]) self.assertEqual(h.piece_priorities(), [0]) # also test the overload that takes a list of piece->priority mappings h.prioritize_pieces([(0, 1)]) self.assertEqual(h.piece_priorities(), [1])
def download_torrent(torrent_source, save_location, output_file_name): #Start a session session = libtorrent.session({'listen_interfaces': '0.0.0.0:6881'}) #Check if we are dealing with a torrent file or a magnet link if torrent_source.endswith('.torrent'): #Parse torrent file parameters torrent_file = download_file(torrent_source) torrent_info = libtorrent.torrent_info(torrent_file) torrent_in_progress = session.add_torrent({ 'ti': torrent_info, 'save_path': save_location }) remove(torrent_file) else: #Parse magnet URI parameters torrent_info = libtorrent.parse_magnet_uri(torrent_source).get( 'info_hash') torrent_in_progress = session.add_torrent({ 'ti': torrent_info, 'save_path': save_location }) logging.info(f'Starting download: {torrent_in_progress.name()}.') while (not torrent_in_progress.is_seed()): status = torrent_in_progress.status() sleep(1) logging.info('{:.2f}% complete. (Speed: {:.1f} kB/s)'.format( status.progress * 100, status.download_rate / 1000)) alerts = session.pop_alerts() for a in alerts: if a.category() & libtorrent.alert.category_t.error_notification: logging.error(f'{str(a)}') #TODO test files with more than one . in the name output_file_name += str(path.splitext(str(torrent_in_progress.name()))[1]) rename(f'{save_location}/{torrent_in_progress.name()}', f'{save_location}/{output_file_name}') logging.info(f'{torrent_in_progress.name()} - Download complete.') #return output_file_name, torrent_in_progress.name() return f'{save_location}/{output_file_name}', f'{torrent_in_progress.name()}'
def _download_real_torrent(self, inner_identifier, username): downloaded_torrent_path = os.path.normpath( '{}\\hpradiotracker\\static\\hpradiotracker\\media\\'.format( os.getcwd())) downloaded_torrent_file = os.path.normpath('{}_{}.torrent'.format( inner_identifier, username)) downloaded_audio_file = os.path.normpath('{}_{}.mp3'.format( inner_identifier, username)) ses = lt.session() ses.listen_on(6881, 68911) info = lt.torrent_info( os.path.normpath(downloaded_torrent_path + '\\' + downloaded_torrent_file)) # filename, extension = os.path.splitext(info.name()) info.rename_file(0, str(downloaded_audio_file)) params = { 'ti': info, 'save_path': downloaded_torrent_path, 'storage_mode': lt.storage_mode_t(2), 'paused': False, 'auto_managed': True, 'duplicate_is_error': True } handler = ses.add_torrent(params) ses.start_dht() print('...downloading metadata...') while not handler.has_metadata(): time.sleep(1) print('...got metadata, starting torrent download...') while handler.status().state != lt.torrent_status.seeding: s = handler.status() # state_str = ['queued', 'checking', 'downloading metadata', # 'downloading', 'finished', 'seeding', 'allocating'] # print s.progress * 100, '% complete (down: ', s.download_rate / 1000, 'kb/s up: ', s.upload_rate / 1000, # ' kB/s peers: ', ,') ', state_str[s.state], ' ', s.total_download/1000000' print('File: ' + str(downloaded_audio_file) + ' ' + str(s.progress * 100) + '% ' + 'Download:' + str(s.download_rate / 1000) + ' Seeds:' + str(s.num_peers)) time.sleep(5) print('...done')
def test_post_dht_stats(self): s = lt.session({'alert_mask': lt.alert.category_t.stats_notification, 'enable_dht': False}) s.post_dht_stats() alerts = [] # first the stats headers log line. but not if logging is disabled while len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() a = alerts.pop(0) self.assertTrue(isinstance(a, lt.session_stats_header_alert)) print(a.message()) while len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() a = alerts.pop(0) self.assertTrue(isinstance(a, lt.dht_stats_alert)) self.assertTrue(isinstance(a.active_requests, list)) self.assertTrue(isinstance(a.routing_table, list))
def setUp(self) -> None: self.dir = tempfile.TemporaryDirectory() self.session = lt.session(lib.get_isolated_settings()) # Use 7-bit data to allow testing deprecated path self.dummy = TDUMMY_7BIT atp = self.dummy.atp() atp.save_path = self.dir.name self.handle = self.session.add_torrent(atp) self.file_path = pathlib.Path(self.dir.name) / os.fsdecode( self.dummy.files[0].path) # add_piece() does not work in the checking_* states for _ in lib.loop_until_timeout(5, msg="checking"): if self.handle.status().state not in ( lt.torrent_status.checking_files, lt.torrent_status.checking_resume_data, ): break
def test_post_session_stats(self): s = lt.session({'alert_mask': lt.alert.category_t.stats_notification, 'enable_dht': False}) s.post_session_stats() alerts = [] # first the stats headers log line. but not if logging is disabled if 'log_alert' in [i[0] for i in inspect.getmembers(lt)]: s.wait_for_alert(1000) alerts = s.pop_alerts() a = alerts.pop(0) self.assertTrue(isinstance(a, lt.log_alert)) # then the actual stats values if len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() a = alerts.pop(0) self.assertTrue(isinstance(a, lt.session_stats_alert)) self.assertTrue(isinstance(a.values, dict)) self.assertTrue(len(a.values) > 0)
def create_session(self): begin_port = self._port for port in range(begin_port, begin_port + self._session_num): session = lt.session() #session.set_alert_mask(lt.alert.category_t.status_notification | lt.alert.category_t.stats_notification | lt.alert.category_t.progress_notification | lt.alert.category_t.tracker_notification | lt.alert.category_t.dht_notification | lt.alert.category_t.progress_notification | lt.alert.category_t.error_notification) session.set_alert_mask(lt.alert.category_t.all_categories) session.listen_on(port, port + 10) for router in DHT_ROUTER_NODES: session.add_dht_router(router[0], router[1]) # session.set_download_rate_limit(_download_rate_limit) # session.set_upload_rate_limit(_upload_rate_limit) # session.set_alert_queue_size_limit(_alert_queue_size) #session.set_max_connections(_max_connections) #session.set_max_half_open_connections(_max_half_open_connections) session.start_dht() session.start_upnp() self._sessions.append(session) return self._sessions
def download_metadata(address, binhash, metadata_queue, timeout=40): metadata = None start_time = time.time() try: session = lt.session() r = random.randrange(10000, 50000) session.listen_on(r, r + 10) session.add_dht_router('router.bittorrent.com', 6881) session.add_dht_router('router.utorrent.com', 6881) session.add_dht_router('dht.transmission.com', 6881) session.add_dht_router('127.0.0.1', 6881) session.start_dht() metadata = fetch_torrent(session, binhash.encode('hex'), timeout) session = None except: traceback.print_exc() finally: metadata_queue.put((binhash, address, metadata, 'lt', start_time))
def test_pop_alerts(self): ses = lt.session({'alert_mask': lt.alert.category_t.all_categories, 'enable_dht': False}) ses.async_add_torrent({"ti": lt.torrent_info("base.torrent"), "save_path": "."}) # this will cause an error (because of duplicate torrents) and the # torrent_info object created here will be deleted once the alert goes out # of scope. When that happens, it will decrement the python object, to allow # it to release the object. # we're trying to catch the error described in this post, with regards to # torrent_info. # https://mail.python.org/pipermail/cplusplus-sig/2007-June/012130.html ses.async_add_torrent({"ti": lt.torrent_info("base.torrent"), "save_path": "."}) time.sleep(1) for i in range(0, 10): alerts = ses.pop_alerts() for a in alerts: print(a.message()) time.sleep(0.1)
def test_iterable_files(self): # this detects whether libtorrent was built with deprecated APIs # the file_strage object is only iterable for backwards compatibility if not hasattr(lt, 'version'): return ses = lt.session({'alert_mask': lt.alert.category_t.all_categories, 'enable_dht': False}) ti = lt.torrent_info('url_seed_multi.torrent'); files = ti.files() idx = 0 expected = ['bar.txt', 'var.txt'] for f in files: print(f.path) self.assertEqual(os.path.split(f.path)[1], expected[idx]) self.assertEqual(os.path.split(os.path.split(f.path)[0]), ('temp', 'foo')) idx += 1
def test_connect_and_get_info(self) -> None: # Create a peer, to ensure get_peer_info returns something seed = lt.session(lib.get_isolated_settings()) seed.apply_settings({"close_redundant_connections": False}) with tempfile.TemporaryDirectory() as seed_dir: atp = self.torrent.atp() atp.save_path = seed_dir seed.add_torrent(atp) self.session.apply_settings({"close_redundant_connections": False}) self.handle.connect_peer(("127.0.0.1", seed.listen_port())) for _ in lib.loop_until_timeout(5, msg="heck"): if self.handle.get_peer_info(): break peer_info = self.handle.get_peer_info()[0] self.assertEqual(peer_info.ip, ("127.0.0.1", seed.listen_port()))
def __init__(self , magnet_url): if not re.match('^magnet\:\?xt\=urn\:btih\:.*' , magnet_url): print 'It is not a vailed magnet link' exit() else: self.current_dir = os.path.dirname(os.path.realpath(__file__)) self.magnet_url = magnet_url #start libtorrent session self.session = libtorrent.session() self.session.add_extension('ut_metadata') self.session.add_extension('ut_pex_plugin') self.session.add_dht_router('router.utorrent.com', 6881) self.session.add_dht_router('router.bittorrent.com', 6881) self.session.add_dht_router('dht.transmissionbt.com', 6881) self.session.add_dht_router('router.bitcomet.com', 6881) self.session.add_dht_router('dht.aelitis.com', 6881) self.session.start_dht()
def main(uri): session = lt.session() load_state('client.state', session) tune_session(session) session.listen_on(28155, 28155) session.add_dht_router("router.utorrent.com", 6881) session.add_dht_router("router.bittorrent.com", 6881) session.add_dht_router("dht.transmissionbt.com", 6881) session.add_dht_router("dht.aelitis.com", 6881) session.start_dht() #session.start_lsd() session.start_natpmp() session.start_upnp() magnet = 'magnet:?xt=urn:btih:%s' % (uri,) h = lt.add_magnet_uri(session, magnet, {'save_path': './download', 'storage_mode': lt.storage_mode_t.storage_mode_allocate, 'paused': False, 'auto_managed': False, 'duplicate_is_error': False }) def show_alerts(): alerts = session.pop_alerts() for alert in alerts: print('Alert: %s: %s' % (alert.what(), alert.message())) while (not h.is_seed()): s = h.status() print('State: %.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s dht_announce:%s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ s.num_peers, s.state, s.announcing_to_dht)) show_alerts() time.sleep(1) show_alerts() save_state('client.state', session) print('Download complete: %s' % (h.name(),))
def create_torrent(message_digest): #Create torrent name = str(message_digest) + ".torrent" fs = lt.file_storage() lt.add_files(fs, path) t = lt.create_torrent(fs) trackerList = [ 'udp://tracker.coppersurfer.tk:6969', 'udp://tracker.opentrackr.org:1337/announce', 'udp://torrent.gresille.org:80/announce', 'udp://9.rarbg.me:2710/announce', 'udp://p4p.arenabg.com:1337', 'udp://tracker.internetwarriors.net:1337' ] for tracker in trackerList: t.add_tracker(tracker, 0) t.set_creator('libtorrent %s' % lt.version) t.set_comment("Test") lt.set_piece_hashes(t, ".") torrent = t.generate() f = open(name, "wb") f.write(lt.bencode(torrent)) f.close() #Seed torrent ses = lt.session() ses.listen_on(6881, 6891) h = ses.add_torrent({ 'ti': lt.torrent_info(name), 'save_path': '.', 'seed_mode': True }) print("Total size: " + str(h.status().total_wanted)) print("Name: " + h.name()) while h.is_seed(): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] print('\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state])) sys.stdout.flush() time.sleep(1)
def download_bt(magnet, movie_path, task_id): print "download" try: bt_path = magnet2torrent(magnet=magnet) ses = lt.session() ses.listen_on(6881, 6891) e = lt.bdecode(open(bt_path, 'rb').read()) info = lt.torrent_info(e) params = { 'save_path': movie_path, \ 'storage_mode': lt.storage_mode_t.storage_mode_sparse, \ 'ti': info } h = ses.add_torrent(params) s = h.status() movie = db.Movie.query.filter_by(magnet=magnet).first() movie.name = info.name() db.db.session.commit() download = db.Download(taskid=task_id, name=info.name(), progress=0, speed=0, peer_nums=0) while (not s.is_seeding): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating'] print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ s.num_peers, s.state) download.speed = '%.1f' % (s.download_rate/1000) download.progress = '%.2f' % (s.progress * 100) download.peer_nums = s.num_peers cache.set(task_id, download) time.sleep(1) movie.status = 1 db.db.session.commit() except Exception as e: print e.message raise e
def test_parse_dict_sha256_broken(self) -> None: uri = ( f"magnet:?xt=urn:btmh:1220{self.info_hash_sha256}&" "dn=test.txt&" "tr=http://example.com/tr&" "ws=http://example.com/ws&" "so=0-2,4&" "x.pe=0.1.2.3:4567&" "dht=1.2.3.4:5678" ) params = lt.parse_magnet_uri_dict(uri) self.assertEqual( params, { "dht_nodes": [("1.2.3.4", 5678)], "file_priorities": [4, 4, 4, 0, 4], "flags": lt.add_torrent_params_flags_t.default_flags, "info_hash": bytes.fromhex(self.info_hash_sha256)[:20], "info_hashes": bytes.fromhex(self.info_hash_sha256), "name": "test.txt", "peers": [("0.1.2.3", 4567)], "save_path": "", "storage_mode": lt.storage_mode_t.storage_mode_sparse, "trackers": ["http://example.com/tr"], "url": "", "url_seeds": "http://example.com/ws", }, ) # The dict is intended to be usable as argument to session.add_torrent() session = lt.session(lib.get_isolated_settings()) with tempfile.TemporaryDirectory() as path: params["save_path"] = path handle = session.add_torrent(params) self.assertEqual( str(handle.info_hashes().v2), # type: ignore self.info_hash_sha256, ) self.assertEqual(handle.name(), "test.txt") self.assertEqual( [t["url"] for t in handle.trackers()], ["http://example.com/tr"] ) self.assertEqual(handle.url_seeds(), ["http://example.com/ws"]) self.assertEqual(handle.file_priorities(), [4, 4, 4, 0, 4])
def run(self): if self.session is None: self.session = lt.session() self.session.set_alert_mask(lt.alert.category_t.all_categories) #self.session.set_dht_settings() for i in self._subsystems: getattr(self.session, "start_%s" % i)() for i in self._extensions: self.session.add_extension(getattr(lt, "create_%s_plugin" % i)) settings = lt.session_settings() settings.use_parole_mode = True settings.prioritize_partial_pieces = True settings.prefer_udp_trackers = True settings.user_agent = '%s/%s libtorrent/%d.%d' % ( self.appname, self.appversion, lt.version_major, lt.version_minor) # settings.share_ratio_limit = float(self.manager.get_setting('upload_ratio', 0)) settings.use_dht_as_fallback = False # Use DHT for tracker torrent too settings.ignore_resume_timestamps = True # Allow resume settings.announce_to_all_trackers = True # Announce to all trackers by tier settings.announce_to_all_tiers = True # like uTorrent self.session.set_settings(settings) self.config.on("max_downspeed", lambda k, v: self._set_max_downspeed(v)) self.config.on("max_upspeed", lambda k, v: self._set_max_upspeed(v)) self.config.on("max_active_downloads", lambda k, v: self._set_max_active_downloads(v)) self.config.on("max_connections", lambda k, v: self._set_max_connections(v)) self.config.on("max_half_open_connections", lambda k, v: self._set_max_half_open_connections(v)) self.config.on("port_%s_0" % self.name, lambda k, v: self.set_port(0, v)) self.torrent_resume_data = [] self.num_flushes = 0 self.set_port(0, self._port)
def download(uri,ruta): ses = lt.session() ses.listen_on(6881, 6891) info = lt.torrent_info(uri) h = ses.add_torrent({'ti': info, 'save_path': ruta}) print 'starting', h.name() while (not h.is_seed()): s = h.status() state_str = ['queued', 'checking', 'downloading metadata', \ 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] print '\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \ (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \ s.num_peers, state_str[s.state]),\ sys.stdout.flush() time.sleep(1) print h.name(), 'complete' return h.name()
def __init__(self, name, task_queue, concurrent=10, timeout=40): super(torrentClientMetaCrawler, self).__init__() self.setDaemon(True) self.save_path = '/tmp/torrentDownloader/' + name + '/' self.setName(name) self.session = lt.session() self.timeout = timeout # self.pool = gevent.pool.Pool(concurrent) self.concurrent = concurrent r = random.randrange(20000, 30000) self.session.listen_on(r, r + 10) self.session.add_dht_router('router.bittorrent.com', 6881) self.session.add_dht_router('router.utorrent.com', 6881) self.session.add_dht_router('dht.transmission.com', 6881) self.session.start_dht() self.handles = [] self.task_queue = task_queue self.on_meta_fetched = None self.on_crawled_failed = None
def test_add_torrent_info_hash(self): s = lt.session(settings) h = s.add_torrent({ 'info_hash': b'a' * 20, 'info_hashes': b'a' * 32, 'save_path': '.' }) time.sleep(1) alerts = s.pop_alerts() while len(alerts) > 0: a = alerts.pop(0) print(a) self.assertTrue(h.is_valid()) self.assertEqual( h.status().info_hashes, lt.info_hash_t(lt.sha1_hash(b'a' * 20), lt.sha256_hash(b'a' * 32)))
def __init__(self, cache_path): super(TorrentController, self).__init__() settings = libtorrent.session_settings() settings.user_agent = 'torrent_browser/' + libtorrent.version settings.use_dht_as_fallback = False settings.volatile_read_cache = False ses = libtorrent.session() ses.set_download_rate_limit(0) ses.set_upload_rate_limit(0) ses.listen_on(6881, 6891) ses.set_alert_mask(0xfffffff) ses.set_settings(settings) #start local source discovery ses.start_lsd() #start distributed hash table ses.start_dht() #start router port forwarding ses.start_upnp() ses.start_natpmp() #add bootstrapping nodes ses.add_dht_router("router.bittorrent.com", 6881) ses.add_dht_router("router.utorrent.com", 6881) ses.add_dht_router("router.bitcomet.com", 6881) self.session = ses self.downloads = list() self.alive = True self.cache_path = cache_path print("(I) Cache directory: {}".format(cache_path)) if not os.path.exists(self.cache_path): os.makedirs(self.cache_path) self.timer = QTimer() self.timer.timeout.connect(self.sendUpdates) self.timer.start(500)
def test_post_dht_stats(self): s = lt.session({ 'alert_mask': lt.alert.category_t.stats_notification, 'enable_dht': False }) s.post_dht_stats() alerts = [] cnt = 0 while len(alerts) == 0: s.wait_for_alert(1000) alerts = s.pop_alerts() cnt += 1 if cnt > 60: print('no dht_stats_alert in 1 minute!') sys.exit(1) a = alerts.pop(0) self.assertTrue(isinstance(a, lt.dht_stats_alert)) self.assertTrue(isinstance(a.active_requests, list)) self.assertTrue(isinstance(a.routing_table, list))
def magnet2torrent_worker(magnet): logger.info('magnet2torrent: start [%s]', magnet) session = libtorrent.session() params = libtorrent.parse_magnet_uri(magnet) # bug: TypeError: No registered converter was able to produce a C++ # rvalue of type bytes from this Python object of type sha1_hash params.update({'info_hash': params['info_hash'].to_bytes()}) handle = session.add_torrent(params) if not handle.is_valid(): logger.error('magnet2torrent: invalid handle') time_lim = time.time() + 3 * 60 while not handle.has_metadata(): time.sleep(0.1) if time.time() > time_lim: logger.info( 'magnet2torrent: the waiting time of metadata has expired') break session.pause() try: torinfo = handle.get_torrent_info() if not torinfo: raise ValueError('magnet2torrent: failed getting torrent info') torfile = libtorrent.create_torrent(torinfo) except Exception: logger.exception('magnet2torrent: failed creating torrent file') return try: torrent_content = libtorrent.bencode(torfile.generate()) if torrent_content: logger.info('magnet2torrent: done [%s]', magnet) return torinfo.name() + '.torrent', torrent_content else: logger.error('magnet2torrent: empty torrent content body [%s]', magnet) except Exception: logger.exception('magnet2torrent: torrent generating problem [%s]', magnet)
def run_seeder(cls): ses = lt.session() ses.listen_on(2000, 3000) # not so fast ses.set_upload_rate_limit(500) ses.start_dht() ses.start_lsd() ses.start_upnp() ses.start_natpmp() info = lt.torrent_info(TORRENT_PATH) h = ses.add_torrent({'ti': info, 'save_path': settings.TEST_DIR}) h.super_seeding(True) cls.h = h cls.info = info cls.seeder = ses