예제 #1
1
	def get_torrent(self, ses, hash_info):
		'''
		Add hash_info to session, begin down load torrent
		'''

		self._insert_info_hash(hash_info)
		if self._is_download_meta == False:
			return 
		if (self._download_meta_params.has_key(hash_info) is True):
			print "info hash" + hash_info + "already downloading"
			return


		magnet='magnet:?xt=urn:btih:'+hash_info
		print "Add magnet ", magnet
		tempdir = tempfile.mkdtemp()
		params = {
			'save_path': tempdir,
			'duplicate_is_error': True,
			'storage_mode': lt.storage_mode_t(2),
			'paused': False,
			'auto_managed': True,
			'duplicate_is_error': True
		}

		lt.add_magnet_uri(ses, magnet, params)

		download_param = DownloadParam()
		download_param.start_time = time.time()
		download_param.download_dir= tempdir

		self._download_meta_params[hash_info] = download_param
예제 #2
1
def magnet2torrent(magnet):
    tempdir = tempfile.mkdtemp()
    ses = lt.session()
    params = {
        'save_path': tempdir,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True,
        'flag_merge_resume_trackers': True
    }
    handle = lt.add_magnet_uri(ses, magnet, params)

    print("Downloading Metadata (this may take a while)")
    while (not handle.has_metadata()):
        try:
            sleep(1)
        except KeyboardInterrupt:
            print("Aborting...")
            ses.pause()
            print("Cleanup dir " + tempdir)
            shutil.rmtree(tempdir)
            sys.exit(0)
    ses.pause()
    shutil.rmtree(tempdir)
    print("Done")
    
    torinfo = handle.get_torrent_info()
    torfile = lt.create_torrent(torinfo)
    torcontent = lt.bencode(torfile.generate())
    return torcontent
예제 #3
1
    def __add_magnet(self, uri, info_hash):
        self.l.log("TorrentAgent:adding magnet " + uri)

        if self.__check_dups(uri):
            self.l.log("TorrentAgent:skipping, already added " + uri)
            return 

        resume_data = self.__get_resume_data(info_hash)

        params = {"save_path":self.c["save_path"], "resume_data":resume_data, 
                  "storage_mode":self.c["storage_mode"],
                  "paused":self.c["start_as_paused"], 
                  "duplicate_is_error":self.c["dup_is_error"],
                  "auto_managed":self.c["auto_managed"]}
        
        try:
            h = LT.add_magnet_uri(self.session, uri, params)
        except:
            self.l.log("TorrentAgent:error adding magnet, malformed URI? " + uri, L.ERR)
            return

        try:
            fname = self.c["watch_path"] + "/" + str(h.info_hash()) + ".magnet"
            self.l.log("TorrentAgent:writing magnet restart file " + fname, L.DBG)
            f = open(fname, "wb")
            f.write(uri)
            f.close()
        except:
            self.l.log("TorrentAgent:error writing magnet restart file " + fname, L.ERR)

        self.__setup_handle(h)
        self.handle_by_name[uri] = (h, True)
예제 #4
0
def magnet2t(link, tfile):
    sess = lt.session()
    params = {
        "save_path": '/',
        "storage_mode": lt.storage_mode_t.storage_mode_sparse,
        "paused": True,
        "auto_managed": True,
        "duplicate_is_error": True
    }
    try:
        handle = lt.add_magnet_uri(sess, link, params)
        state_str = ['queued', 'checking', 'downloading metadata', 'downloading',
                 'finished', 'seeding', 'allocating']
        while (not handle.has_metadata()):
            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, state_str[s.state])
            time.sleep(5)
            print handle.has_metadata()

        torinfo = handle.get_torrent_info()
        torfile = lt.create_torrent(torinfo)

        t = open(tfile, "wb")
        t.write(lt.bencode(torfile.generate()))
        t.close()
        print '%s  generated!' % tfile
    except Exception, ex:
        print Exception, ":", ex
        return False
예제 #5
0
 def add_magnet(self, client, url, params):
     handle = lt.add_magnet_uri(self.session, url, params)
     ih = str(handle.info_hash())
     if ih in self.torrents:
         raise Exception('Duplicate torrent')
     self.torrents[ih] = client
     return handle
예제 #6
0
파일: bittorrent.py 프로젝트: NegatioN/BACk
    def generate_metadata(self, magnet):
        tempdir = tempfile.mkdtemp()
        ses = lt.session()
        handle = lt.add_magnet_uri(ses, magnet, generate_params(tempdir))

        print("Downloading Metadata of {}".format(magnet))
        while not handle.has_metadata():
            try:
                sleep(1)
            except KeyboardInterrupt:
                print("Aborting...")
                session.pause(ses)
                print("Cleanup dir " + tempdir)
                shutil.rmtree(tempdir)
                sys.exit(0)
        session.pause(ses)
        print("Done")
        torinfo = handle.get_torrent_info()
        info_entry = {
            "trackers": [t.url for t in torinfo.trackers()],
            "name": torinfo.name(),
            "link": magnet,
            "files": [f.path for f in torinfo.files()],
            "num_files": torinfo.num_files()
        }
        return info_entry
예제 #7
0
    def download_iso(self):
        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()

        LOG.debug('Downloading metadata for build {0}'.format(
            self.stable_iso_build))
        while not handle.has_metadata():
            time.sleep(1)
        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.debug('{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.debug('Ready for deploy iso {0}'.format(self.stable_iso_build))
예제 #8
0
def get_subtitle(magnet, lang):
    print("Explorando torrent")
    lt_session = session()
    lt_session.listen_on(6881, 6891)
    params = {"save_path": "/tmp"}
    handle = add_magnet_uri(lt_session, magnet, params)
    lt_session.start_dht()
    print "esperando"
    while (not handle.has_metadata()):
        sleep(.1)
    print "esperando"
    info = handle.get_torrent_info()
    print "esperando", info
    files = info.files()

    biggest_file = ("", 0)

    for file_ in files:
        if file_.size > biggest_file[1]:
            biggest_file = [file_.path, file_.size]

    print("Adivinando data")
    filepath = biggest_file[0]
    guess = guess_video_info(filepath, info=['filename'])
    video = Video.fromguess(filepath, guess)
    video.size = biggest_file[1]
    print("Bajando el subtitulo para lang = " + lang)
    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
예제 #9
0
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()
예제 #10
0
	def downloadMagnet(self,magnetlink,location=''):
		try:
			savepath = self.TORRENT_DIR
			if len(location)>0:
				savepath = os.path.join(savepath, location)
				if not os.path.exists(savepath):
					os.makedirs(savepath)
					self.logger.info("Created directory "+str(savepath))
			params = { 'save_path': savepath}
			handle = lt.add_magnet_uri(self.ses, magnetlink, params)

			self.logger.info( 'downloading metadata...')
			while (not handle.has_metadata()): time.sleep(1)
			self.logger.info( 'got metadata, starting torrent download...')
			while (handle.status().state != lt.torrent_status.seeding):
				try:
					percentComplete = int(handle.status().progress*100)
				except:
					percentComplete = handle.status().progress*100
				self.logger.info("DL " + handle.name()+ " ["+ str(handle.status().download_rate/1000)+"kb/s : "+str(handle.status().upload_rate/1000)+"kb/s.] [" + str(percentComplete)+"%]" + " [S:"+str(handle.status().num_seeds)+ " P:"+str(handle.status().num_peers)+"]" )
				# self.logger.info("Tracker: "+ handle.status().current_tracker )
				time.sleep(10)
			self.logger.info( "[Complete] Download complete of "+handle.name())
			self.logCompletedDownload(handle.name())
			try:
				self.logger.info("Removing torrent: "+str(handle.name()))
				self.ses.remove_torrent(handle)
			except Exception as ee:
				self.logger.error(traceback.format_exc())
		except Exception as e:
			self.logger.error(traceback.format_exc())
예제 #11
0
	def StartSession(self):
		self.params = {
			'save_path': '.',
			'storage_mode': lt.storage_mode_t(2),
			'paused': True,
			'auto_managed': True,
			'duplicate_is_error': True
			}

		self.tmr_pauseTorrent = wx.Timer(self, -1)
		self.Bind(wx.EVT_TIMER, self.PauseTorrent, self.tmr_pauseTorrent)
		self.tmr_pauseTorrent.Start(milliseconds=100, oneShot=False)

		if os.path.exists(self.path):
			decodedTorrent = lt.bdecode(open(self.path, 'rb').read())
			self.torrentInfo = lt.torrent_info(decodedTorrent)
			self.params.update({'ti': self.torrentInfo})
			self.torrent = self.parent.ses.add_torrent(self.params)
			self.loaded = True
			self.ggb_metadata.Hide()
			self.lbl_metadata.Hide()
			self.GetTorrentData()
		else:
			self.torrent = lt.add_magnet_uri(self.parent.ses, self.path, self.params)
			self.ggb_metadata.Pulse()
			self.btn_ok.Disable()

			self.timeoutCounter = 0
			self.tmr_metadata = wx.Timer(self, -1)
			self.Bind(wx.EVT_TIMER, self.GetMetadata, self.tmr_metadata)
			self.tmr_metadata.Start(milliseconds=100, oneShot=False)
예제 #12
0
def generate_torrent_from_magnet(url):
    try:
        session = libtorrent.session()
        tempdir = tempfile.mkdtemp()
        params = {
            'save_path': tempdir,
            'storage_mode': libtorrent.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }
        handle = libtorrent.add_magnet_uri(session, url, params)
        while (not handle.has_metadata()):
            time.sleep(.1)

        session.pause()
        torinfo = handle.get_torrent_info()

        fs = libtorrent.file_storage()
        for file in torinfo.files():
            fs.add_file(file)
        torfile = libtorrent.create_torrent(fs)
        torfile.set_comment(torinfo.comment())
        torfile.set_creator(torinfo.creator())
        torrent_data = libtorrent.bencode(torfile.generate())
        session.remove_torrent(handle)
        return torrent_data
    except:
        torrent_data = None

    if handle and session:
        session.remove_torrent(handle)

    return torrent_data
예제 #13
0
def get_subtitle(magnet, lang):
    print("Explorando torrent")
    lt_session = session()
    lt_session.listen_on(6881, 6891)
    params = {"save_path": "/tmp"}
    handle = add_magnet_uri(lt_session, magnet, params)
    lt_session.start_dht()
    print "esperando"
    while (not handle.has_metadata()):
        sleep(.1)
    print "esperando"
    info = handle.get_torrent_info()
    print "esperando", info
    files = info.files()

    biggest_file = ("", 0)

    for file_ in files:
        if file_.size > biggest_file[1]:
            biggest_file = [file_.path, file_.size]

    print("Adivinando data")
    filepath = biggest_file[0]
    guess = guess_video_info(filepath, info = ['filename'])
    video = Video.fromguess(filepath, guess)
    video.size = biggest_file[1]
    print("Bajando el subtitulo para lang = " + lang)
    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
예제 #14
0
def main():
	
	count = 0
	
	ses = lt.session()
	
	params = { 'save_path': PATH}
	
	print "Introduce el magnet :"
	link = raw_input()
	handle = lt.add_magnet_uri(ses, link, params)
	handle.set_sequential_download(True)
	salida = 0
	print 'Descargando metadatos'
	while (not handle.has_metadata()): time.sleep(1)
	print 'Cargando'
	print "0%"
	while (handle.status().state != lt.torrent_status.seeding):
		porcen_ini = handle.status().progress
		time.sleep(1)
		if handle.status().progress*100 > porcen_ini*100:
			salida = handle.status().progress*100
			print ("%.2f %%" % salida)
		if salida >= 5 and count < 1: #buffer
			hilo =  threading.Thread(target = abrevideo)
			hilo.start()
			count += 1
		
	os.system("rm -rf "+PATH)
	return 0
예제 #15
0
파일: download.py 프로젝트: rmasad/Caldo
  def run(self):
    params = {'save_path': './'}
    handle = libtorrent.add_magnet_uri(self.session, str(self.torrent.magnet_link), params)

    while (not handle.has_metadata()): time.sleep(1)
    
    total_download = 0
    total_upload = 0
    
    while True:
      status = handle.status()

      self.speed_download = (status.total_download - total_download)/1
      self.speed_upload = (status.total_upload - total_upload)/1

      total_download = status.total_download
      total_upload = status.total_upload

      torrent = TorrentDownload()
      torrent.ID = self.torrent.ID
      torrent.magnet_link = self.torrent.magnet_link
      torrent.name = self.torrent.name
      torrent.size = status.total_wanted
      torrent.seed = [None, None] # [int, int]
      torrent.leech = [None, None] # [int, int]
      torrent.state = status.state
      torrent.downloaded = total_download
      torrent.uploaded = total_upload
      torrent.downspeed = self.speed_download
      torrent.upspeed = self.speed_upload

      self.emit(SIGNAL('update(PyQt_PyObject)'), torrent)
      time.sleep(1)
예제 #16
0
파일: app.py 프로젝트: miguelvps/magnets
def index():
    if request.args.has_key("magnet"):
        magnet = url_unquote(request.args["magnet"]).encode(request.charset)
        magnet_xt = url_decode(magnet[magnet.index("?") + 1 :])["xt"]
        torrent = cache.get(magnet_xt)
        if not torrent:
            try:
                handle = lt.add_magnet_uri(
                    ses,
                    magnet,
                    {"save_path": "./invalid", "paused": False, "auto_managed": False, "duplicate_is_error": False},
                )
                while not handle.has_metadata():
                    time.sleep(0.01)
                handle.pause()
                info = handle.get_torrent_info()
                torrent = create_torrent(info)
                cache.set(magnet_xt, torrent)
                ses.remove_torrent(handle, lt.options_t.delete_files)
            except:
                torrent = cache.get(magnet_xt)
        response = Response(response=torrent[1], mimetype="application/x-bittorrent")
        response.headers.add("Content-Disposition", "attachment", filename=torrent[0])
        return response
    return render_template("index.html")
예제 #17
0
파일: change.py 프로젝트: MidSmer/mWebApp
def magnet2torrent(link):

    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": "/tmp/tor",
        # "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 True:
        if not handle.has_metadata():
            time.sleep(6)
        else:
            break

    sess.pause()

    # create a torrent
    torinfo = handle.get_torrent_info()
    torfile = lt.create_torrent(torinfo)
    torcontent = lt.bencode(torfile.generate())
    torname = torinfo.name()
    sess.remove_torrent(handle, 1)

    return {"status": 200, "name": torname, "data": torcontent}
예제 #18
0
def construct_handler(ses, torrent, destination):
    """ helper for handling magnet link, http links and torrent files"""
    tinfo = None
    params = {
        'save_path': destination,
        'storage_mode': lt.storage_mode_t(2),
        'auto_managed': True,
    }
    # if case if ULR was provided download it to file
    # TODO: add nice REGXP URL validator, the 'http' can be a folder name
    if torrent.startswith('http'):
        torrent_body = requests.get(torrent)
        torrent = os.path.join(location_context, 'torrent_file')
        tmp_torrent = torrent + '.tmp'
        with open(tmp_torrent, 'wb') as dist:
            dist.write(torrent_body.text.encode('utf-8'))
        os.rename(tmp_torrent, torrent)

    # check if file contain magnet link
    # XXX: shitty magnet support from file
    torrent_data = open(torrent).read().strip(" \n\t")
    if torrent_data.startswith("magnet:"):
        torrent_handler = lt.add_magnet_uri(ses, torrent_data, params)
    else:
        tinfo = lt.torrent_info(torrent)
        params['ti'] = tinfo
        torrent_handler = ses.add_torrent(params)
    # waiting for metadata to be downloaded
    while (not torrent_handler.has_metadata()):
        time.sleep(0.1)
    return torrent_handler
예제 #19
0
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
예제 #20
0
파일: main.py 프로젝트: Zsfzy/dht-
async def infohash_to_torrent(infohash):
    ses = lt.session()
    ses.add_dht_router('router.bittorrent.com', 6881)
    ses.add_dht_router('router.utorrent.com', 6881)
    ses.add_dht_router('dht.transmissionbt.com', 6881)
    ses.start_dht()

    params = {
        'save_path': runPath + '/torrent',
        'storage_mode': lt.storage_mode_t(2),
        # 'storage_mode': lt.storage_mode_t.storage_mode_sparse,
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    handle = lt.add_magnet_uri(ses, 'magnet:?xt=urn:btih:' + infohash, params)

    while (not handle.has_metadata()):
        time.sleep(1)
        # print('下载中')
    ses.pause()
    print('完成')
    torinfo = handle.get_torrent_info()
    torfile = lt.create_torrent(torinfo)

    output = op.abspath(torinfo.name() + ".torrent")
예제 #21
0
 def __init__(self, magnet_link, params, ports):
     params_ = {
         'save_path': '.',
         'auto_managed': True,
         'paused': False,
         'port': 6881,
         'ratio': 0,
         'max_download_rate': -1,
         'max_upload_rate': -1,
         'storage_mode': lt.storage_mode_t.storage_mode_sparse
     }
     #: I know it's not nice to add trackers like this...
     magnet_link += "&tr=udp://tracker.openbittorrent.com:80"
     params_.update(params)
     self.session = lt.session()
     self.session.set_severity_level(lt.alert.severity_levels.critical)
     self.session.listen_on(*ports)
     self.session.start_lsd()
     self.session.start_upnp()
     self.session.start_natpmp()
     self.session.start_dht()
     self.session.add_dht_router("router.bittorrent.com", 6881)
     self.session.add_dht_router("router.utorrent.com", 6881)
     self.session.add_dht_router("router.bitcomet.com", 6881)
     self.handle = lt.add_magnet_uri(self.session, magnet_link, params_)
예제 #22
0
파일: change.py 프로젝트: MidSmer/mWebApp
def magnet2torrent(link):

    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": '/tmp/tor',
        # "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 True:
        if (not handle.has_metadata()):
            time.sleep(6)
        else:
            break

    sess.pause()

    # create a torrent
    torinfo = handle.get_torrent_info()
    torfile = lt.create_torrent(torinfo)
    torcontent = lt.bencode(torfile.generate())
    torname = torinfo.name()
    sess.remove_torrent(handle, 1)

    return {'status': 200, 'name': torname, 'data': torcontent}
예제 #23
0
def downloadCinema(linkManget):

    # CREDITOS => https://gist.github.com/samukasmk/940ca5d5abd9019e8b1af77c819e4ca9
    folder = "/torrent"
    pathFIle = os.getcwd() + folder
    ses = lt.session()
    ses.listen_on(6881, 6891)
    params = {
        'save_path': pathFIle,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    link = linkManget
    handle = lt.add_magnet_uri(ses, link, params)
    ses.start_dht()

    print('downloading metadata...')
    while (not handle.has_metadata()):
        time.sleep(1)
    print('got metadata, starting torrent download...')
    while (handle.status().state != lt.torrent_status.seeding):
        s = handle.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(5)
예제 #24
0
    def add_torrent(self):
        self.logger.debug("Adding torrent hash {0}".format(self.info_hash))
        info = lt.torrent_info(lt.big_number(self.info_hash.decode('hex')))
        # Add OpenBitTorrent trackers
        info.add_tracker('udp://tracker.openbittorrent.com:80', 0)
        info.add_tracker('udp://tracker.publicbt.com:80', 0)
        info.add_tracker('udp://tracker.ccc.de:80', 0)
        info.add_tracker('udp://tracker.istole.it:80', 0)
        self.logger.info("Adding hash {0} to session".format(self.info_hash))
        #        self.handle = self.libtorrent_session.add_torrent(info, './')
        self.handle = lt.add_magnet_uri(self.libtorrent_session, str(self.magnet),
            {'save_path': '/tmp',
             'storage_mode': lt.storage_mode_t.storage_mode_sparse,
             'paused':True
            })

        #wait for the download to start
        while not self.handle.status().state == self.handle.status().downloading:
            time.sleep(1)
        self.logger.debug("{0} changed state to  downloading".format(self.info_hash))


        #set all file prio to 0

        self.handle.prioritize_files([0 for i in self.handle.file_priorities()])

        #        for i in range(0, self.handle.get_torrent_info().num_pieces()):
        #            self.handle.piece_priority(i, 0)

        self.logger.debug("Done setting priority 0 for hash {0}".format(self.info_hash))
예제 #25
0
파일: transformor.py 프로젝트: GDHYZY/btool
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
예제 #26
0
def crawl(magnet_link):

  print magnet_link

  h = lt.add_magnet_uri(ses, magnet_link, params)

  timeout_counter = 0

  while (not h.has_metadata()):
    #print "Sleeping..."
    time.sleep(1)

    # Kill this torrent when the timeout reaches 3minutes
    timeout_counter += 1

    if timeout_counter == 180:
      with open("failed_magnets.txt", "a") as fail:
        fail.write(magnet_link + '\n')

      return


  if h.has_metadata():
    #print "Got the metadata"

    torinfo = h.get_torrent_info()

    torfile = lt.create_torrent( torinfo )

    name = (magnet_link.split("magnet:?xt=urn:btih:")[1][:40]).upper()

    with open( name + ".torrent", "wb" ) as f:
      f.write(lt.bencode(torfile.generate()))

  return
예제 #27
0
    def download_module(self, module):
        """
        Download module

        :param module: module
        :type module: Module
        :return: None
        """
        modules_directory = os.path.join(self.working_directory, MODULES_DIR)

        params = {'save_path': modules_directory}
        torrent = "magnet:?xt=urn:btih:{0}&dn={1}".format(
            module.id.content_hash, module.name)
        h = lt.add_magnet_uri(self.ses, torrent, params)

        self._logger.debug("transport: checking torrent (%s)", h.name())

        while not h.has_metadata():
            time.sleep(.1)

        self._logger.debug("transport: metadata complete for torrent (%s)",
                           module.id.content_hash)

        torrent_info = h.get_torrent_info()
        h = self.ses.add_torrent({
            'ti': torrent_info,
            'save_path': modules_directory,
            'seed_mode': True
        })
예제 #28
0
 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)
예제 #29
0
def fetch_torrent(session, ih, timeout):
    name = ih.upper()
    url = 'magnet:?xt=urn:btih:%s' % (name, )
    data = ''
    params = {
        'save_path': '/tmp/downloads/',
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': False,
        'duplicate_is_error': True
    }
    try:
        handle = lt.add_magnet_uri(session, url, params)
    except:
        return None
    status = session.status()
    #print 'downloading metadata:', url
    handle.set_sequential_download(1)
    meta = None
    down_time = time.time()
    down_path = None
    for i in xrange(0, timeout):
        if handle.has_metadata():
            info = handle.get_torrent_info()
            down_path = '/tmp/downloads/%s' % info.name()
            #print 'status', 'p', status.num_peers, 'g', status.dht_global_nodes, 'ts', status.dht_torrents, 'u', status.total_upload, 'd', status.total_download
            meta = info.metadata()
            break
        time.sleep(1)
    if down_path and os.path.exists(down_path):
        os.system('rm -rf "%s"' % down_path)
    session.remove_torrent(handle)
    return meta
예제 #30
0
def exp1():
    ses = lt.session()
    ses.listen_on(6881, 6891)
    down_dir = '//home//qqq//download'
    if os.path.exists(down_dir):
        shutil.rmtree(down_dir)
    os.makedirs(down_dir)

    params = {
        'save_path': '//home//www//download',
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    link = "magnet:?xt=urn:btih:6e5bbd0399a401c1316760ed13bcc76712467d5a&dn=%E7%97%85%E6%AF%92%E5%85%A5%E4%BE%B5.Pandemic.2016.720p.WEB-DL.DD5.1.H264.Chs%2BEng-homefei"
    handle = lt.add_magnet_uri(ses, link, params)
    ses.start_dht()

    print 'downloading metadata...'
    while (not handle.has_metadata()):
        print 'sleep 3 secs...'
        time.sleep(3)
    print 'got metadata, starting torrent download...'
    while (handle.status().state != lt.torrent_status.seeding):
        s = handle.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 %.3' % \
              (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
               s.num_peers, state_str[s.state], s.total_download / 1000000)
        time.sleep(5)
예제 #31
0
파일: PoshD.py 프로젝트: helloitu/PoshD
def downloadtorrent(""):
    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 construct_handler(ses, torrent, destination):
    """ helper for handling magnet link, http links and torrent files"""
    tinfo = None
    params = {
        'save_path': destination,
        'storage_mode': lt.storage_mode_t(2),
        'auto_managed': True,
    }
    # if case if ULR was provided download it to file
    # TODO: add nice REGXP URL validator, the 'http' can be a folder name
    if torrent.startswith('http'):
        torrent_body = requests.get(torrent)
        torrent = os.path.join(location_context, 'torrent_file')
        tmp_torrent = torrent+'.tmp'
        with open(tmp_torrent, 'wb') as dist:
            dist.write(torrent_body.text.encode('utf-8'))
        os.rename(tmp_torrent, torrent)

    # check if file contain magnet link
    # XXX: shitty magnet support from file
    torrent_data = open(torrent).read().strip(" \n\t")
    if torrent_data.startswith("magnet:"):
        torrent_handler = lt.add_magnet_uri(ses, torrent_data, params)
    else:
        tinfo = lt.torrent_info(torrent)
        params['ti'] = tinfo
        torrent_handler = ses.add_torrent(params)
    # waiting for metadata to be downloaded
    while (not torrent_handler.has_metadata()):
        time.sleep(0.1)
    return torrent_handler
예제 #33
0
 def magnet_to_torrent(self, magnet_uri, destination_folder, timeout):
     import libtorrent
     params = libtorrent.parse_magnet_uri(magnet_uri)
     session = libtorrent.session()
     # for some reason the info_hash needs to be bytes but it's a struct called sha1_hash
     params['info_hash'] = bytes(params['info_hash'])
     handle = libtorrent.add_magnet_uri(session, magnet_uri, params)
     log.debug('Acquiring torrent metadata for magnet %s', magnet_uri)
     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)
     return torrent_path
예제 #34
0
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()
    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 {0}'.format(i))
        if i > 300:
            print('No Metadata Available: {0}s'.format(i))
            break
    info = handle.get_torrent_info()

    handle.set_sequential_download(True)
    print(handle.trackers())

    return handle, ses, info
예제 #35
0
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
예제 #36
0
def mag2tor(mag_link):
    sess = libtorrent.session()
    prms = {
        'save_path':os.path.abspath(os.path.curdir),
        # 'storage_mode':libtorrent.storage_mode_t(2),
        'paused':False,
        'auto_managed':False,
        'upload_mode':True,
    }
    torr = libtorrent.add_magnet_uri(sess, mag_link, prms)
    dots = 0
    # sys.stdout.write('%s: ' % mag_link)
    while not torr.has_metadata():
        dots += 1
        sys.stdout.write('.')
        sys.stdout.flush()
        time.sleep(1)
    if (dots): sys.stdout.write('\n')
    sess.pause()
    tinf = torr.get_torrent_info()
    f = open(tinf.name() + '.torrent', 'wb')
    f.write(libtorrent.bencode(
        libtorrent.create_torrent(tinf).generate()))
    f.close()
    sess.remove_torrent(torr)
예제 #37
0
def fetch_torrent(session, ih, timeout):
    name = ih.upper()
    url = 'magnet:?xt=urn:btih:%s' % (name,)
    data = ''
    params = {
        'save_path': '/tmp/downloads/',
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': False,
        'duplicate_is_error': True}
    try:
        handle = lt.add_magnet_uri(session, url, params)
    except:
        return None
    status = session.status()
    #print 'downloading metadata:', url
    handle.set_sequential_download(1)
    meta = None
    down_time = time.time()
    down_path = None
    for i in xrange(0, timeout):
        if handle.has_metadata():
            info = handle.get_torrent_info()
            down_path = '/tmp/downloads/%s' % info.name()
            #print 'status', 'p', status.num_peers, 'g', status.dht_global_nodes, 'ts', status.dht_torrents, 'u', status.total_upload, 'd', status.total_download
            meta = info.metadata()
            break
        time.sleep(1)
    if down_path and os.path.exists(down_path):
        os.system('rm -rf "%s"' % down_path)
    session.remove_torrent(handle)
    return meta
예제 #38
0
    def torrentInfo(self, donotload=False):
        if not self.session:
            raise Exception("Need session first")
        # URL:
        # http://piratebaytorrents.info/5579280/Big_Buck_Bunny_(1080p).ogv.5579280.TPB.torrent
        if not donotload and len(self.location)>4 and self.location[0:4] == 'http':
            # Create tmp torrent file in the tmp dir
            dest = self.tmpdir + '/' + hashlib.md5(self.location).hexdigest() + '.torrent'
            urllib.urlretrieve(self.location, dest)
            # Set the location to this file
            self.location = dest
        # Magnet: 
        # magnet:?xt=urn:btih:e541adf64e5d10c0827579447948aefba651e4f4&dn=Big+Buck+Bunny+%281080p%29.ogv&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337
        if len(self.location)>6 and self.location[0:6] == 'magnet':
            if donotload and not self.torrent_handle:
                print >> sys.stderr, "NOT Loading"
                return None

            if not self.torrent_handle or not hasattr(self,"magnet"):
                self.magnet = lt.add_magnet_uri(self.session, self.location, self.torrent_params)
                print >> sys.stderr, 'Downloading metadata...'
                while (not self.magnet.has_metadata()): time.sleep(1)
                self.torrent_handle = self.magnet
            # Return info
            return self.magnet.get_torrent_info()
        elif self.location:
            try:
                return lt.torrent_info(self.location)
            except:
                pass
        return None
예제 #39
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
예제 #40
0
 def convertManget(self, magnet):
     sess = lt.session()
     sess.listen_on(6881, 6891)
     prms = {
         'save_path': '/',
         'paused': False,
         'auto_managed': False,
         'upload_mode': True
     }
     torr = lt.add_magnet_uri(sess, magnet, prms)
     dots = 0
     sess.start_dht()
     while not torr.has_metadata():
         dots += 1
         sys.stdout.write('.')
         sys.stdout.flush()
         time.sleep(1)
     if (dots): sys.stdout.write('\n')
     sess.pause()
     tinf = torr.get_torrent_info()
     fname = tinf.name() + '.torrent'
     f = open(fname, 'wb')
     f.write(lt.bencode(lt.create_torrent(tinf).generate()))
     f.close()
     sess.remove_torrent(torr)
     return fname
예제 #41
0
    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])
예제 #42
0
def magnetWorker(link, path):
    params = {
        'save_path': path,
        'paused': False,
        'auto_managed': False,
    }
    handle = lt.add_magnet_uri(session, link, params)
예제 #43
0
def torrent():
    ses = lt.session()
    ses.listen_on(6881, 6891)
    params = {
        'save_path': SAVEPATH,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    link = "magnet:?xt=urn:btih:" + HASH + TRAKERS
    print(link)
    handle = lt.add_magnet_uri(ses, link, params)
    ses.start_dht()

    print('downloading metadata...')
    while (not handle.has_metadata()):
        time.sleep(1)
        print("#", end='')
    print('got metadata, starting torrent download...')
    while (handle.status().state != lt.torrent_status.seeding):
        s = handle.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 %.3' % \
        #		(s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
        #		s.num_peers, state_str[s.state], s.total_download/1000000)
        print(s.progress * 100, end="\r")
        time.sleep(5)
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
예제 #45
0
 def fetch_torrent(self, ih):
     if ih in downloading:
         return None
     downloading.add(ih)
     name = ih.upper()
     url = 'magnet:?xt=urn:btih:%s' % (name,)
     data = ''
     params = {
         'save_path': '/tmp/downloads/',
         'storage_mode': lt.storage_mode_t(2),
         'paused': False,
         'auto_managed': False,
         'duplicate_is_error': True}
     try:
         handle = lt.add_magnet_uri(self.ses, url, params)
     except:
         downloading.remove(ih)
         return None
     status = self.ses.status()
     #print 'downloading metadata:', url
     handle.set_sequential_download(1)
     down_time = time.time()
     for i in xrange(0, 60):
         if handle.has_metadata():
             info = handle.get_torrent_info()
             print '\n', time.ctime(), (time.time()-down_time), 's, got', url, info.name()
             #print 'status', 'p', status.num_peers, 'g', status.dht_global_nodes, 'ts', status.dht_torrents, 'u', status.total_upload, 'd', status.total_download
             meta = info.metadata()
             self.ses.remove_torrent(handle)
             downloading.remove(ih)
             return meta
         time.sleep(1)
     downloading.remove(ih)
     self.ses.remove_torrent(handle)
     return None
예제 #46
0
def fetch_torrent(ses, info_hash):
    print "+" * 60
    info_hash = info_hash.upper()
    url = "magnet:?xt=urn:btih:%s" % (info_hash,)
    print "url:", url
    params = {
        "save_path": "downloads",
        "storage_mode": lt.storage_mode_t(2),
        "paused": False,
        "auto_managed": False,
        "duplicate_is_error": True,
    }
    handle = lt.add_magnet_uri(ses, url, params)
    status = ses.status()
    handle.set_sequential_download(1)
    down_time = time.time()
    if handle.has_metadata():
        info = handle.get_torrent_info()
        print "\n", time.ctime(), (time.time() - down_time), "s, got", url, info.name()
        print "status", "p", status.num_peers, "g", status.dht_global_nodes, "ts", status.dht_torrents, "u", status.total_upload, "d", status.total_download
        meta = info.metadata()
        print meta
        return meta
    else:
        print "no metadata"
    ses.remove_torrent(handle)
    print "+" * 60, "\n"
예제 #47
0
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
예제 #48
0
def get_peers_count_from_magnet(magnet):
    tempdir = tempfile.mkdtemp()

    session = lt.session()

    params = {
        'save_path': tempdir,
        'storage_mode': lt.storage_mode_t(2),
        'auto_managed': True,
        'file_priorities': [0] * 5
    }

    handle = lt.add_magnet_uri(session, magnet, params)

    print("Downloading Metadata (this may take a while)")
    while not handle.has_metadata():
        print("Waiting ... ")
        time.sleep(1)

    print("Metadata downloaded")

    peers = set()
    start = time.time()

    while not handle.is_seed() and time.time() - start < 5:
        p = handle.get_peer_info()
        for i in p:
            peers.add(i.ip)

    print(peers)
    session.remove_torrent(handle)
    shutil.rmtree(tempdir)

    return len(peers)
예제 #49
0
 def fetch_torrent(self, ih):
     if ih in downloading:
         return None
     downloading.add(ih)
     name = ih.upper()
     url = 'magnet:?xt=urn:btih:%s' % (name,)
     data = ''
     params = {
         'save_path': '/tmp/downloads/',
         'storage_mode': lt.storage_mode_t(2),
         'paused': False,
         'auto_managed': False,
         'duplicate_is_error': True}
     try:
         handle = lt.add_magnet_uri(self.ses, url, params)
     except:
         downloading.remove(ih)
         return None
     status = self.ses.status()
     #print 'downloading metadata:', url
     handle.set_sequential_download(1)
     down_time = time.time()
     for i in xrange(0, 60):
         if handle.has_metadata():
             info = handle.get_torrent_info()
             print '\n', time.ctime(), (time.time()-down_time), 's, got', url, info.name()
             meta = info.metadata()
             self.ses.remove_torrent(handle)
             downloading.remove(ih)
             return meta
         time.sleep(1)
     downloading.remove(ih)
     self.ses.remove_torrent(handle)
     return None
def main():

    ses = lt.session()
    ses.listen_on(6881, 6891)
    params = {
        'save_path': '/tmp',
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    link = "magnet:?xt=urn:btih:37e77490bc4f285dbfa837514715a20bd405a502&dn=Spider-Man+Far+from+Home+%282019%29+%5BWEBRip%5D+%5B1080p%5D+English&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969"
    handle = lt.add_magnet_uri(ses, link, params)
    ses.start_dht()

    print('downloading metadata...')
    while (not handle.has_metadata()):
        time.sleep(1)
    print('got metadata, starting torrent download...')

    timeout = time.time() + cfg.p2pdownload_timer  # 10 secs from now

    while (handle.status().state != lt.torrent_status.seeding):
        s = handle.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]))
        if time.time() > timeout:
            break
        time.sleep(2)
예제 #51
0
def magnet2t(link, tfile):
    sess = lt.session()
    params = {
        "save_path": './tfile/',
        "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)
    state_str = [
        'queued', 'checking', 'downloading metadata', 'downloading',
        'finished', 'seeding', 'allocating'
    ]
    while (not handle.has_metadata()):
        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, state_str[s.state])
        time.sleep(5)
        print handle.has_metadata()

    torinfo = handle.get_torrent_info()
    torfile = lt.create_torrent(torinfo)

    t = open(tfile, "wb")
    t.write(lt.bencode(torfile.generate()))
    t.close()
    print '%s  generated!' % tfile
예제 #52
0
	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)
예제 #53
0
def download_torrent(torrent, directory):
    session = libtorrent.session()
    session.listen_on(6881, 6891)

    params = {
        "save_path": directory,
        "storage_mode": libtorrent.storage_mode_t(2),
        "paused": False,
        "auto_managed": True,
        "duplicate_is_error": True
    }
    magnet = torrent.magnet
    handle = libtorrent.add_magnet_uri(session, magnet, params)
    session.start_dht()

    print("Downloading metadata...")
    while (not handle.has_metadata()):
        time.sleep(1)

    print("Starting torrent download...")

    while (handle.status().state != libtorrent.torrent_status.seeding):
        s = handle.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(5)

    print("Torrent downloaded")
예제 #54
0
def fetch_torrent(session, ih, timeout):
    name = ih.upper()
    url = 'magnet:?xt=urn:btih:%s' % (name, )
    params = {
        'save_path': '/tmp/downloads/',
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': False,
        'duplicate_is_error': True
    }
    try:
        handle = lt.add_magnet_uri(session, url, params)
    except Exception:
        return None
    handle.set_sequential_download(1)
    meta = None
    down_path = None
    for i in range(0, timeout):
        if handle.has_metadata():
            info = handle.get_torrent_info()
            down_path = '/tmp/downloads/%s' % info.name()
            meta = info.metadata()
            break
        time.sleep(1)
    if down_path and os.path.exists(down_path):
        os.system('rm -rf "%s"' % down_path)
    session.remove_torrent(handle)
    return meta
예제 #55
0
파일: main.py 프로젝트: todokku/torrentit
async def get_torrent_handle(log, torrent):
    th = None
    wait_metatada_timeout = 60
    if isinstance(torrent, str):
        if torrent.startswith('magnet'):
            log.info('Downloading metadata...')
            th = lt.add_magnet_uri(session, torrent, {'save_path': './'})
            time_elasped = 0
            while (not th.has_metadata()):
                await asyncio.sleep(3)
                time_elasped += 3
                log.debug('Wait metadata, time elapsed = {}s'.format(
                    str(time_elasped)))
                if time_elasped >= wait_metatada_timeout:
                    session.remove_torrent(th)
                    log.info('Magnet link resolve timeout')
                    raise NoMetadataError
            log.info('Got metadata, starting torrent download...')
        else:
            raise Exception('String not a magnet link')

    elif isinstance(torrent, bytes):
        bd = lt.bdecode(torrent)
        info = lt.torrent_info(bd)
        th = session.add_torrent({'ti': info, 'save_path': '.'})
    else:
        log.error('Torrent handler creating failed, not valid torrent: ',
                  torrent)
        raise Exception("Not valid torrent")

    th.calc_prioritized_piece_count()
    th.prepare_pieces_priority()
    return th
예제 #56
0
def start_download(save_path, magnet_link):
    ses = lt.session()
    ses.listen_on(6881, 6891)
    params = {
        'save_path': save_path,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    link = magnet_link
    handle = lt.add_magnet_uri(ses, link, params)
    ses.start_dht()
    print('downloading metadata...')
    while (not handle.has_metadata()):
        time.sleep(1)
    print('got metadata, starting torrent download...')
    while (handle.status().state != lt.torrent_status.seeding):
        s = handle.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(5)
예제 #57
0
 def __init__(self, magnet_link, params, ports):
     params_ = {
         'save_path': '.',
         'auto_managed': True,
         'paused': False,
         'port': 6881,
         'ratio': 0,
         'max_download_rate': -1,
         'max_upload_rate': -1,
         'storage_mode': lt.storage_mode_t.storage_mode_sparse
     }
     #: I know it's not nice to add trackers like this...
     magnet_link += "&tr=udp://tracker.openbittorrent.com:80"
     params_.update(params)
     self.session = lt.session()
     self.session.set_severity_level(lt.alert.severity_levels.critical)
     self.session.listen_on(*ports)
     self.session.start_lsd()
     self.session.start_upnp()
     self.session.start_natpmp()
     self.session.start_dht()
     self.session.add_dht_router("router.bittorrent.com", 6881)
     self.session.add_dht_router("router.utorrent.com", 6881)
     self.session.add_dht_router("router.bitcomet.com", 6881)
     self.handle = lt.add_magnet_uri(self.session, magnet_link, params_)
예제 #58
0
파일: torrent.py 프로젝트: zhliji2/Deque
 def add_from_ml(self, link):
     params = {
         'save_path': 'queue/',
         'storage_mode': lt.storage_mode_t(1)
     }
     handle = lt.add_magnet_uri(self.ses, link, params)
     self.prepare_handle(handle)
     return handle