Пример #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
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
Пример #4
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
Пример #5
0
def download():
    ses = lt.session()
    ses.listen_on(6881, 6891)
    params = {
        'save_path': 'Downloads',
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True}
    num = input("Enter the number of the file you want to download : ")
    f = open('list.txt','r')
    filelist = []
    filelist = f.read()
    filelist = filelist.split()
    link = filelist[num-1]
    print("Now downloading {0}...".format(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)
Пример #6
0
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
Пример #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 download_torrent(self, link, title):
        params = {
            'auto_managed': True,
            'duplicate_is_error': True,
            'paused': False,
            'save_path': self.__save_path,
            'sequential_download': False,
            'seed_mode': False,
            'storage_mode': lt.storage_mode_t(2),
            'url': link
        }

        handle = self.__session.add_torrent(params)
        s = handle.status()
        self.__session.start_dht()

        while(not handle.has_metadata()):
            s = handle.status()
            time.sleep(1)

        print(s.state)
        while(not s.is_seeding and (s.state != 'checking_files')):
            s = handle.status()
            res = [s.state, title, s.progress*100]
            print(
                  'State: {0} ' 'Title: {1} Progresso: {2:.1f}%'.format(res[0],
                                                                        res[1],
                                                                        res[2])
                )
            time.sleep(0.5)
            os.system('cls' if os.name == 'nt' else 'clear')
Пример #9
0
def fetch_magnet(magnet_uri):	
	tempdir = tempfile.mkdtemp()
	logger.debug("Fetching magnet to '%s'" % tempdir)
	params = {
		"save_path" : tempdir,
		"duplicate_is_error" : True,
		"paused" : False,
		"auto_managed" : True,
		"url" : magnet_uri,
		"storage_mode" : lt.storage_mode_t(2)
	}
	handle = ses.add_torrent(params)
	def cleanup():
		ses.remove_torrent(handle)
		shutil.rmtree(tempdir)
	while not handle.has_metadata():
		try :			
			time.sleep(1)			
		except NameError as e:
			logger.debug("Exception!! %s" % str(e))
			cleanup()
			return		
	logger.debug("Magnet %s fetched!" % magnet_uri)
	torrent_data = lt.create_torrent(handle.get_torrent_info()).generate()	
	add_from_torrent_info(handle.get_torrent_info(), lt.bencode(torrent_data))
	cleanup()
Пример #10
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
Пример #11
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")
Пример #12
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
Пример #13
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)
Пример #14
0
def fetch_magnet(magnet_uri):
    tempdir = tempfile.mkdtemp()
    logger.debug("Fetching magnet to '%s'" % tempdir)
    params = {
        "save_path": tempdir,
        "duplicate_is_error": True,
        "paused": False,
        "auto_managed": True,
        "url": magnet_uri,
        "storage_mode": lt.storage_mode_t(2)
    }
    handle = ses.add_torrent(params)

    def cleanup():
        ses.remove_torrent(handle)
        shutil.rmtree(tempdir)

    while not handle.has_metadata():
        try:
            time.sleep(1)
        except NameError as e:
            logger.debug("Exception!! %s" % str(e))
            cleanup()
            return
    logger.debug("Magnet %s fetched!" % magnet_uri)
    torrent_data = lt.create_torrent(handle.get_torrent_info()).generate()
    add_from_torrent_info(handle.get_torrent_info(), lt.bencode(torrent_data))
    cleanup()
Пример #15
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
Пример #16
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")
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
Пример #18
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"
Пример #19
0
    def __init__(self, magnet, output_name=None):
        """init function.

        check for validity of the input.

        Raises:
            ValueError: if input is not valid this error will be raise
        """
        if (output_name and not pt.isdir(output_name) and
                not pt.isdir(pt.dirname(pt.abspath(output_name)))):
            raise ValueError("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
        self.output_name = output_name

        self.tempdir = tempfile.mkdtemp()
        self.ses = lt.session()

        params = {
            'url': magnet,
            'save_path': self.tempdir,
            'storage_mode': lt.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': False
        }
        self.handle = self.ses.add_torrent(params)
Пример #20
0
 def ltretry(self, irc, msg, args, tids):
     """Adds the torrent into libtorrent to try getting metadata"""
     if not hasattr(self, 'ltses'):
         irc.error('no libtorrent session')
         return
     with closing(getdb()) as db, closing(db.cursor()) as cur:
         tids = tids.split()
         for tid in tids:
             if not re.match('^([0-9]+|[0-9]+-[0-9]+)$', tid):
                 irc.error('invalid id %s' % tid)
                 continue
             if '-' in tid:
                 start,stop = map(int, tid.split('-'))
             else:
                 start = stop = int(tid)
             for i in xrange(start, stop+1):
                 cur.execute('SELECT Name, info_hash FROM torrents WHERE ID = %s', (i,))
                 result = cur.fetchone()
                 if not result:
                     irc.error('%s doesnt exist, skipping' % i)
                     continue
                 name, infohash = result
                 print repr(name)
                 params = {'ti': None,
                         'name': name.encode('utf-8'),
                         'flags': 516, # upload_mode and update_subscribe
                         'trackers': ['%s/%s/announce' % (tracker_url, bot_passkey)],
                         'info_hash': str(infohash),
                         'save_path': 'tmp/',
                         'storage_mode': lt.storage_mode_t(2)}
                 self.ltses.add_torrent(params)
                 irc.reply('Added %s' % name, prefixNick=False)
     irc.replySuccess()
Пример #21
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
Пример #22
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)
Пример #23
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)
Пример #24
0
    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 = {}
Пример #25
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])
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)
Пример #27
0
    def __init__(self, magnet, output_name=None):
        """init function.

        check for validity of the input.

        Raises:
            ValueError: if input is not valid this error will be raise
        """
        if (output_name and not pt.isdir(output_name)
                and not pt.isdir(pt.dirname(pt.abspath(output_name)))):
            raise ValueError("Invalid output folder: " +
                             pt.dirname(pt.abspath(output_name)))
        self.output_name = output_name

        self.tempdir = tempfile.mkdtemp()
        self.ses = lt.session()

        params = {
            'url': magnet,
            'save_path': self.tempdir,
            'storage_mode': lt.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': False
        }
        self.handle = self.ses.add_torrent(params)
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
Пример #29
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
Пример #30
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()
Пример #31
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)
Пример #32
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)
Пример #33
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)
Пример #34
0
def magnet2torrent(magnet, output_name=None):
    if output_name and \
            not pt.isdir(output_name) and \
            not pt.isdir(pt.dirname(pt.abspath(output_name))):
        print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
        print("")
        sys.exit(0)

    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
    }
    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()
    print("Done")

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

    output = pt.abspath("Scripts/" + torinfo.name() + ".torrent")
    f2 = open("Scripts/magnet-name.txt", 'w')
    f2.write(torinfo.name() + ".torrent")
    f2.close()

    if output_name:
        if pt.isdir(output_name):
            output = pt.abspath(
                pt.join(output_name,
                        torinfo.name() + ".torrent"))
        elif pt.isdir(pt.dirname(pt.abspath(output_name))):
            output = pt.abspath(output_name)

    print("Saving torrent file here : " + output + " ...")
    torcontent = lt.bencode(torfile.generate())
    location = output
    f = open(location, "wb")
    f.write(lt.bencode(torfile.generate()))
    f.close()
    print("Saved! Cleaning up dir: " + tempdir)
    ses.remove_torrent(handle)
    shutil.rmtree(tempdir)

    return output
Пример #35
0
def generate_params(save_path):
    return {
        'save_path': save_path,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
Пример #36
0
 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
Пример #37
0
def magnet2torrent(magnet, output_name=None):
    if output_name and \
        not pt.isdir(output_name) and \
        not pt.isdir(pt.dirname(pt.abspath(output_name))):
        print "Invalid output folder: " + pt.dirname(pt.abspath(output_name))
        print ""
        return

    tempdir = tempfile.mkdtemp()
    ses = lt.session()
    params = {
        'save_path': tempdir,
        'duplicate_is_error': True,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    handle = lt.add_magnet_uri(ses, magnet, params)
    print "Downloading Metadata (this may take a while)"
    while (not handle.has_metadata()):
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            print "Abrorting..."
            ses.pause()
            print "Cleanup dir " + tempdir
            shutil.rmtree(tempdir)
            return
    print "done"

    torinfo = handle.get_torrent_info()

    output = pt.abspath(torinfo.name() + ".torrent")

    if output_name:
        if pt.isdir(output_name):
            output = pt.abspath(
                pt.join(output_name,
                        torinfo.name() + ".torrent"))
        elif pt.isdir(pt.dirname(pt.abspath(output_name))) == True:
            output = pt.abspath(output_name)
    print 'saving torrent file here : ' + output + " ..."

    fs = lt.file_storage()
    for file in torinfo.files():
        fs.add_file(file)
    torfile = lt.create_torrent(fs)
    torfile.set_comment(torinfo.comment())
    torfile.set_creator(torinfo.creator())

    torcontent = lt.bencode(torfile.generate())
    f = open(output, "wb")
    f.write(lt.bencode(torfile.generate()))
    f.close()
    print 'Saved! Cleaning up dir: ' + tempdir
    shutil.rmtree(tempdir)
    return output
Пример #38
0
 def add_from_file(self, filename):
     params = {
         'save_path': 'queue/',
         'storage_mode': lt.storage_mode_t(1),
         'ti': lt.torrent_info(filename)
     }
     handle = self.ses.add_torrent(params)
     self.prepare_handle(handle)
     return handle
Пример #39
0
def magnet2torrent(magnet, output_name = None):
  if output_name and \
      not pt.isdir(output_name) and \
      not pt.isdir(pt.dirname(pt.abspath(output_name))):
    print "Invalid output folder: " + pt.dirname(pt.abspath(output_name))
    print ""
    return

  tempdir = tempfile.mkdtemp()
  ses = lt.session()
  params = {
    'save_path': tempdir,
    'duplicate_is_error': True,
    'storage_mode': lt.storage_mode_t(2),
    'paused': False,
    'auto_managed': True,
    'duplicate_is_error': True
  }
  handle = lt.add_magnet_uri(ses, magnet, params)
  print "Downloading Metadata (this may take a while)"
  while (not handle.has_metadata()):
    try:
      time.sleep(1)
    except KeyboardInterrupt:
      print "Abrorting..."
      ses.pause()
      print "Cleanup dir " + tempdir
      shutil.rmtree(tempdir)
      return
  print "done"

  torinfo = handle.get_torrent_info()

  output = pt.abspath(torinfo.name() + ".torrent" )

  if output_name:
    if pt.isdir(output_name):
      output = pt.abspath(pt.join(output_name, torinfo.name() + ".torrent"))
    elif pt.isdir(pt.dirname(pt.abspath(output_name))) == True:
      output = pt.abspath(output_name)
  print 'saving torrent file here : ' + output + " ..."

  fs = lt.file_storage()
  for file in torinfo.files():
    fs.add_file(file)
  torfile = lt.create_torrent(fs)
  torfile.set_comment(torinfo.comment())
  torfile.set_creator(torinfo.creator())

  torcontent = lt.bencode(torfile.generate())
  f = open(output, "wb")
  f.write(lt.bencode(torfile.generate()))
  f.close()
  print 'Saved! Cleaning up dir: ' + tempdir
  shutil.rmtree(tempdir)
  return output
Пример #40
0
def magnetinfo(magnet):

    tempdir = tempfile.mkdtemp()
    ses = lt.session()
    #ses.listen_on(60000, 65000)

    params = {
        'save_path': tempdir,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }
    handle = lt.add_magnet_uri(ses, magnet, params)

    print("Downloading Metadata: " + magnet + " (this may take a while)")
    timeout = 20
    while (not handle.has_metadata()):
        try:
            sleep(1)
            timeout = timeout - 1
            if timeout <= 0:
                print(
                    "Oops ... it happens. Can not get the information. Aborting (timeout)."
                )
                ses.pause()
                ses.remove_torrent(handle)
                sleep(3)
                print("Cleanup dir " + tempdir)
                shutil.rmtree(tempdir)
                sys.exit(2)

        except KeyboardInterrupt:
            print("Aborting...")
            ses.pause()
            ses.remove_torrent(handle)
            sleep(3)
            print("Cleanup dir " + tempdir)
            shutil.rmtree(tempdir)
            sys.exit(0)

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

    print("File_size: " + str(torinfo.total_size()))
    print("File_name: " + torinfo.name())
    print("File_comment: " + torinfo.comment())

    ses.remove_torrent(handle)
    sleep(3)
    print("Cleanup dir " + tempdir)
    shutil.rmtree(tempdir)
    print("Done")

    return
Пример #41
0
def magnet2torrent(magnet, output_name=None):
    if output_name and \
            not pt.isdir(output_name) and \
            not pt.isdir(pt.dirname(pt.abspath(output_name))):
        print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
        print("")
        sys.exit(0)

    tempdir = tempfile.mkdtemp()
    ses = lt.session()
    params = {
        'save_path': tempdir,
        'duplicate_is_error': True,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': 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()
    print("Done")

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

    output = pt.abspath(torinfo.name() + ".torrent")

    if output_name:
        if pt.isdir(output_name):
            output = pt.abspath(pt.join(
                output_name, torinfo.name() + ".torrent"))
        elif pt.isdir(pt.dirname(pt.abspath(output_name))):
            output = pt.abspath(output_name)

    print("Saving torrent file here : " + output + " ...")
    torcontent = lt.bencode(torfile.generate())
    f = open(output, "wb")
    f.write(lt.bencode(torfile.generate()))
    f.close()
    print("Saved! Cleaning up dir: " + tempdir)
    ses.remove_torrent(handle)
    shutil.rmtree(tempdir)

    return output
Пример #42
0
    def __init__(self, data=None, magnet=None, options=None):
        self.options = options or dict()

        self.alerts = dict()

        self._id_event = Event()
        self.save_lock = RLock()
        self.edit_lock = RLock()

        if config.compact_allocation:
            self.options['storage_mode'] = lt.storage_mode_t(2)
        else:
            self.options['storage_mode'] = lt.storage_mode_t(1)

        self.options["paused"] = True
        self.options["auto_managed"] = False
        self.options["duplicate_is_error"] = True

        if data or magnet:
            self._init(data, magnet)
Пример #43
0
    def __init__(self, data=None, magnet=None, options=None):
        self.options = options or dict()

        self.alerts = dict()

        self._id_event = Event()
        self.save_lock = RLock()
        self.edit_lock = RLock()

        if config.compact_allocation:
            self.options['storage_mode'] = lt.storage_mode_t(2)
        else:
            self.options['storage_mode'] = lt.storage_mode_t(1)

        self.options["paused"] = True
        self.options["auto_managed"] = False
        self.options["duplicate_is_error"] = True

        if data or magnet:
            self._init(data, magnet)
Пример #44
0
def torrent(magnet, showTitle, tempDir, libBaseDir):
    ses = lt.session()
    ses.listen_on(6881, 6891)
    filer.checkFolder(tempDir)
    print "Downloading " + showTitle
    params = {
        'save_path': tempDir,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }

    handle = lt.add_magnet_uri(ses, magnet, params)
    ses.start_dht()
    print 'downloading metadata...'
    while (not handle.has_metadata()):
        time.sleep(1)
    print 'got metadata, starting torrent download...'
    # download the torrent
    percent = 0
    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)

        if percent < s.progress * 100:
            print str(percent) + " %   " + "Speed: " + str(
                s.download_rate / 1000)
            percent += 1
        #print s.progress * 100
        time.sleep(5)
    print "100%"
    print 'torrent downloaded, seeding to 3x...'
    # seed the torrent
    status = handle.status()
    timeStartSeed = time.time()
    while (3 * status.total_download > status.total_upload):
        status = handle.status()
        print str(float(status.total_upload) / (
            3 * status.total_download)) + "% seeded     Current Speed: " + str(
                status.upload_rate / 1000) + "kb/s up"
        time.sleep(10)
        if time.time(
        ) - timeStartSeed > 10:  # seed time, make a command line argument in future? 10 seconds for testing
            break
    print "finished uploading"
    # return filepath of new item
    return updateLibrary(handle.get_torrent_info(), showTitle, tempDir,
                         libBaseDir)
Пример #45
0
    def run(self):
        for m in self.db["magnets"]:
            self.hashes.append(
                lt.add_magnet_uri(self.s, m["magnet"], {
                    "save_path": "./data",
                    'storage_mode': lt.storage_mode_t(2)
                }))

        while len(self.hashes) > 0:
            for h in self.hashes:
                if h.has_metadata():
                    print(h.get_torrent_info())
            sleep(2)
Пример #46
0
    def download(self, link, handler):
        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(self.ses, link, params)
        self.ses.start_dht()
        threading.Thread(target=self._download,
                         args=(link, handle, handler)).start()
Пример #47
0
def magnet2torrent(magnet, output_dir):
    """
    Convert magnet link to Torrent file.

    Code from Daniel Folkes: https://github.com/danfolkes/Magnet2Torrent

    Args:
        magnet(str): The magnet link.
        output_dir(str): The path to write the Torrent file.

    Returns:
        str: The downloaded Torrent's filename.

    """
    global logger

    tempdir = tempfile.mkdtemp()
    session = lt.session()
    params = {
        "save_path": tempdir,
        "storage_mode": lt.storage_mode_t(2),
        "paused": False,
        "auto_managed": True,
        "duplicate_is_error": True,
    }
    handle = lt.add_magnet_uri(session, magnet, params)

    logger.debug("Downloading Metadata...")
    while not handle.has_metadata():
        try:
            sleep(1)
        except KeyboardInterrupt:
            logger.debug("Aborting...")
            session.pause()
            logger.debug("Cleanup dir %s", tempdir)
            shutil.rmtree(tempdir)
            sys.exit(0)
    session.pause()

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

    filename = torinfo.name() + ".torrent"
    output = os.path.join(output_dir, filename)
    with open(output, "wb") as f:
        f.write(lt.bencode(torfile.generate()))
    logger.debug("Saved! Cleaning up dir: %s", tempdir)
    session.remove_torrent(handle)
    shutil.rmtree(tempdir)

    return filename
Пример #48
0
    def bind_session(self, session):
        """
        Creates torrent handler based on source_type
        """
        add_data = {}
        if self.source_type == "TORRENT":
            add_data['ti'] = lt.torrent_info(self.source)
        elif self.source_type == "MAGNET":
            add_data['url'] = self.source
        add_data['save_path'] = self._get_download_dir()
        add_data['storage_mode'] = lt.storage_mode_t(1)
        self.torrent_handler = session.add_torrent(add_data)

        self._prioritize_to_none()
Пример #49
0
    def bind_session(self, session):
        """
        Creates torrent handler based on source_type
        """
        add_data = {}
        if self.source_type == "TORRENT":
            add_data['ti'] = lt.torrent_info(self.source)
        elif self.source_type == "MAGNET":
            add_data['url'] = self.source
        add_data['save_path'] = self._get_download_dir()
        add_data['storage_mode'] = lt.storage_mode_t(1)
        self.torrent_handler = session.add_torrent(add_data)

        self._prioritize_to_none()
Пример #50
0
    def magnet2torrent(self, magnet, output_name=None):
        print(magnet)
        magnet = "magnet:?xt=urn:btih:EC632808A787708B1605821F8945AD107CA862B4&dn=[2016.03.14]人在囧途之港囧[2015年中国大陆(BD)][喜剧](帝国出品)"
        "http://reflektor.karmorra.info/torrent/EC632808A787708B1605821F8945AD107CA862B4.torrent"


        if output_name and \
                not pt.isdir(output_name) and \
                not pt.isdir(pt.dirname(pt.abspath(output_name))):
            print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
            print("")
            sys.exit(0)
        tempdir = tempfile.mkdtemp()
        ses = lt.session()
        params = {
            'save_path': tempdir,
            'storage_mode': lt.storage_mode_t(2),
        }
        handle = lt.add_magnet_uri(ses, magnet, params)
        print("Downloading Metadata (this may take a while)")
        while (not handle.has_metadata()):
            try:
                time.sleep(1)
            except KeyboardInterrupt:
                print("Aborting...")
                ses.pause()
                print("Cleanup dir " + tempdir)
                shutil.rmtree(tempdir)
                sys.exit(0)
        ses.pause()
        print("Done")
        torinfo = handle.get_torrent_info()
        torfile = lt.create_torrent(torinfo)
        output = pt.abspath(torinfo.name() + ".torrent")
        if output_name:
            if pt.isdir(output_name):
                output = pt.abspath(pt.join(
                    output_name, torinfo.name() + ".torrent"))
            elif pt.isdir(pt.dirname(pt.abspath(output_name))):
                output = pt.abspath(output_name)
        print("Saving torrent file here : " + output + " ...")
        torcontent = lt.bencode(torfile.generate())
        f = open(output, "wb")
        f.write(lt.bencode(torfile.generate()))
        f.close()
        print("Saved! Cleaning up dir: " + tempdir)
        ses.remove_torrent(handle)
        shutil.rmtree(tempdir)
        return output
Пример #51
0
    def download_and_parse_torrent(self, session, info_hash):
        info_hash = info_hash.upper()
        magnet_uri = 'magnet:?xt=urn:btih:%s' % info_hash

        try:
            parameters = {
                'auto_managed' : True,
                'duplicate_is_error' : True,
                'paused' : False,
                'save_path' : self.workspace,
                'storage_mode' : libtorrent.storage_mode_t(2)
            }
            handle = libtorrent.add_magnet_uri(session, magnet_uri, parameters)

        except:
            return None

        s = session.status()

        handle.set_sequential_download(1)
        torrent_content = None

        downloaded_torrent_path = None
        print 'Trying to download' + magnet_uri
        for i in xrange(0, self.timeout):
            if handle.has_metadata():
                print 'Download started ...'
                info = handle.get_torrent_info()
                torrent_file = libtorrent.create_torrent(info)
                downloaded_torrent_path = self.workspace + info.name()
                with open(downloaded_torrent_path, "wb") as f:
                    f.write(libtorrent.bencode(torrent_file.generate()))
                torrent_content = info.metadata()
                print 'Download finished and saved it to %s' % downloaded_torrent_path
                break
            print 'Retrying in 1 second'
            time.sleep(1)


        if downloaded_torrent_path and os.path.exists(downloaded_torrent_path):
            os.system('mv "%s" "%s"' % (downloaded_torrent_path, downloaded_torrent_path + '.parsed'))
        session.remove_torrent(handle)

        torrent_info = self.parse_torrent_content(torrent_content)

        if torrent_info:
            torrent_info['magnet_uri'] = magnet_uri

        return json.dumps(torrent_info, ensure_ascii=False)
Пример #52
0
    def read_magnet_torrent(self, magnet_uri):
        """Read the torrent_info from a given magnet torrent"""
        params = {
            'save_path': '.',
            'storage_mode': lt.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }

        handle = lt.add_magnet_uri(lt.session(), magnet_uri, params)
        while (not handle.has_metadata()):
           time.sleep(.1)
        info = handle.get_torrent_info()
        return info
Пример #53
0
    def read_magnet_torrent(self, magnet_uri):
        """Read the torrent_info from a given magnet torrent"""
        params = {
            'save_path': '.',
            'storage_mode': lt.storage_mode_t(2),
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        }

        handle = lt.add_magnet_uri(lt.session(), magnet_uri, params)
        while (not handle.has_metadata()):
            time.sleep(.1)
        info = handle.get_torrent_info()
        return info
Пример #54
0
 def startMagnet(self, torrent):
     if ( not os.path.isfile(torrent.filename) ): return None
     f = open(torrent.filename)
     magnet = f.read()
     f.close()
     parms = {
         'url': magnet,
         'save_path': torrent.save_to,
         'duplicate_is_error': True,
         'storage_mode': lt.storage_mode_t(2),
         'paused': False,
         'auto_managed': True,
         'duplicate_is_error': True
     }
     return lt.add_magnet_uri(self.torrent_engine, magnet, parms)
Пример #55
0
 def __init__(self):
     print 'Connect to Firebase...'
     self.db = firebase.Firebase(BASE_URL)
     self.db.uniquify()
     self.set_data()
     print 'Create session...'
     self.create_session()
     self.params = {
             'save_path': SAVE_PATH,
             'storage_mode': lt.storage_mode_t(2),
             'paused': False,
             'auto_managed': True,
             'duplicate_is_error': True
             }
     create_dirs(DIRS.values() + FINAL_DIRS.values())
     self.add_torrents(self.undownloaded)
Пример #56
0
def torrent(magnet, showTitle, tempDir, libBaseDir):
    ses = lt.session()
    ses.listen_on(6881, 6891)
    filer.checkFolder(tempDir)
    print "Downloading " + showTitle
    params = {
        'save_path': tempDir,
        'storage_mode': lt.storage_mode_t(2),
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True}
    
    handle = lt.add_magnet_uri(ses, magnet, params)
    ses.start_dht()
    print 'downloading metadata...'
    while (not handle.has_metadata()):
        time.sleep(1)
    print 'got metadata, starting torrent download...'
    # download the torrent
    percent = 0
    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)
        
        if percent < s.progress * 100:
            print str(percent) + " %   " + "Speed: " + str(s.download_rate / 1000 )  
            percent+=1
        #print s.progress * 100
        time.sleep(5)
    print "100%"
    print 'torrent downloaded, seeding to 3x...'
    # seed the torrent
    status = handle.status()
    timeStartSeed = time.time()
    while( 3 * status.total_download > status.total_upload ):
        status = handle.status()
        print str( float(status.total_upload) / (3 * status.total_download )) + "% seeded     Current Speed: " + str(status.upload_rate/1000)+"kb/s up"
        time.sleep(10)
        if time.time() - timeStartSeed > 10:  # seed time, make a command line argument in future? 10 seconds for testing
            break
    print "finished uploading"
    # return filepath of new item
    return updateLibrary(handle.get_torrent_info(), showTitle, tempDir ,libBaseDir) 
Пример #57
0
    def ul(self, irc, msg, args, infohash, cat, scene, name):
        """<infohash> <category name> <1/true if scene else 0/false> <torrent name> - Upload torrent to tracker"""

        if msg.args[0] != chan:
            irc.error('Must ul in %s!' % chan)
            return

        if not is_infohash(infohash):
            irc.error('Invalid infohash')
            return

        infohash = unhexlify(infohash.lower())

        catid = cat_ids[cat]

        with closing(getdb()) as db, closing(db.cursor()) as cur:
            user = self._getuser(irc, msg, db, cur)
            if user is None:
                return
            if user['Enabled'] != '1':
                irc.error('Your tracker account isnt enabled :(')
                return

            cur.execute('SELECT ID FROM torrents WHERE info_hash = %s', (infohash,)) 
            if cur.fetchone():
                irc.error('That torrent already exists!')
                return

            scene = '1' if scene else '0'

            cur.execute('''INSERT INTO torrents (UserId, Name, CategoryID, Scene, info_hash, Size, Time, FreeTorrent)
                        VALUES (%s,%s,%s,%s,%s,%s,%s,%s)''',
                        (user['ID'], name, catid, scene, infohash, 1, sqltime(), 0))
            db.commit()
            self._tracker.update_tracker('add_torrent', {'id': cur.lastrowid, 'info_hash': quote(infohash), 'freetorrent': 0})
            irc.reply('NEW ID %s :: %s :: \x0304%s\x03 :: %s' % (cur.lastrowid, cat, name, 'Scene' if scene=='1' else 'Non-scene'), prefixNick=False)

            if hasattr(self, 'ltses'):
                params = {'ti': None,
                        'name': name,
                        'flags': 516, # upload_mode and update_subscribe
                        'trackers': ['%s/%s/announce' % (tracker_url, bot_passkey)],
                        'info_hash': infohash,
                        'save_path': 'tmp/',
                        'storage_mode': lt.storage_mode_t(2)}
                self.ltses.add_torrent(params)
	def __init__(self):
		self.handles = []
		self.ses = lt.session()
		self.ses.listen_on(6881, 6891)
		"""
		Settings - Find a full list here: https://github.com/arvidn/libtorrent/blob/master/bindings/python/src/session_settings.cpp
		self.settings.<some_setting> = <some_setting_value>
		"""
		self.settings = lt.session_settings()
		self.settings.file_checks_delay_per_block = 1
		self.ses.set_settings(self.settings)
			
		self.ses.start_dht()
		self.params = { 'save_path': '/home/pi/downloads/',
    					'storage_mode': lt.storage_mode_t(2),
    					'paused': False,
    					'auto_managed': True,
    					'duplicate_is_error': True }
Пример #59
0
def download_magnet(url):
    global ses
    tempdir = tempfile.mkdtemp()
    if not ses:
        ses = lt.session()
    params = {
        'save_path': tempdir,
        'storage_mode': lt.storage_mode_t(2),
        'url':url,
    }
    handle = ses.add_torrent(params)

    for i in range(MAGNET_TIMEOUT):
        sleep(1)
        if handle.has_metadata():
            break
    # if we timed out:
    if not handle.has_metadata():
        print("Could not create torrent from magnet")
        handle.pause()
        ses.remove_torrent(handle,option=lt.options_t.delete_files)
##        del ses
        shutil.rmtree(tempdir)
        return None
    handle.pause()
    

    torinfo = handle.get_torrent_info()
    torfile = lt.create_torrent(torinfo)
    # are these 2 needed? probably not.
##    torfile.set_comment(torinfo.comment())
##    torfile.set_creator(torinfo.creator())
    
    torcontent = lt.bencode(torfile.generate())
    ses.remove_torrent(handle,option=lt.options_t.delete_files)
##    del ses
    shutil.rmtree(tempdir)
    return torcontent