def createTorrent(torrent_file_path, content_folder_path, progress_cb = None):
		print("createTorrent")

		fs = libtorrent.file_storage()

		if not os.path.isabs(torrent_file_path):
			raise "Torrent path not absolute"

		if not os.path.isabs(content_folder_path):
			raise "Content path not absolute"

		libtorrent.add_files(fs, content_folder_path)

		if fs.num_files() == 0:
			print("No files to add.")
			return

		t = libtorrent.create_torrent(fs, piece_size=0, pad_file_limit=(4 * 1024 * 1024))

		def progress(piece_num):
			if progress_cb:
				pc = int((100.0 * (1.0+ piece_num)) / fs.num_pieces())
				progress_cb(pc)
		
		parent = os.path.dirname(content_folder_path)
		libtorrent.set_piece_hashes(t, parent, progress)

		data = libtorrent.bencode(t.generate())

		file = open(torrent_file_path,'wb')
		file.write(data)
		file.close()
 def test_path_surrogate_bytes(self) -> None:
     fs = lt.file_storage()
     with get_tempdir_stack(os.fsencode("\udcff")) as (tempdir, ):
         with open(os.path.join(tempdir, b"test.txt"), mode="wb") as fp:
             fp.write(lib.get_random_bytes(1024))
         lt.add_files(fs, tempdir)
     self.assertEqual(fs.file_name(0), "test.txt")
Example #3
0
def make_torrent(file, tracker, save_dir):
    print("file:%s" % file)
    print("tracker:%s" % tracker)
    print("save:%s" % save_dir)
    print('version:%s' % lt.version)

    fs = lt.file_storage()  # get file storage obj
    lt.add_files(fs, file)  # add files to file storage
    print("fs files:%d" % fs.num_files())
    if fs.num_files() == 0:  # check
        os._exit(0)
    t = lt.create_torrent(fs, PIECE_SIZE, PAD_FILE_SIZE)
    print("picesize:%s" % t.piece_size(0))
    t.add_tracker(tracker)
    t.set_creator('libtorrent %s' % lt.version)  # optional.

    # real start create torrent
    lt.set_piece_hashes(t, os.path.dirname(file),
                        func)  # base file in this directory, fun callback

    # write to torrent file
    basename = os.path.basename(file)
    torrent_name = os.path.join(save_dir, basename + ".torrent")
    print("torrent:%s" % torrent_name)
    f = open(torrent_name, "wb+")
    f.write(lt.bencode(t.generate()))  #generere: create bencode file.
    f.close()
Example #4
0
def make_torrent(path, save):
    fs = lt.file_storage()
    lt.add_files(fs, path)
    if fs.num_files() == 0:
        print 'no files added'
        sys.exit(1)

    input = os.path.abspath(path)
    basename = os.path.basename(path)
    t = lt.create_torrent(fs, 0, 4 * 1024 * 1024)

    t.add_tracker("http://10.0.1.5:8760/announce")
    t.set_creator('libtorrent %s' % lt.version)

    lt.set_piece_hashes(t,
                        os.path.split(input)[0],
                        lambda x: sys.stderr.write('.'))
    sys.stderr.write('\n')

    save = os.path.dirname(input)
    save = "%s/%s.torrent" % (save, basename)
    f = open(save, "wb")
    f.write(lt.bencode(t.generate()))
    f.close()
    print "the bt torrent file is store at %s" % save
def generateTorrentOfdownloadedFiles(downloadedFolder):
    print("generateTorrentOfdownloaded Files for sharing...")
    # http://www.libtorrent.org/reference-Create_Torrents.html
    # downloadedFolder = utils.getHomeFolder()+"/"+config.DOWNLOAD_FOLDER
    from os import listdir
    for file in listdir (downloadedFolder):
        print (file)
        fs = lt.file_storage()
        # file_storage fs;

        # // recursively adds files in directories
        # add_files(fs, "./my_torrent");
        lt.add_files(fs, downloadedFolder)
        t = lt.create_torrent() # ?¿?¿?¿?¿?¿?¿?¿?¿¿?¿¿?
        # create_torrent t(fs);
        lt.create_torrent(t, fs)

        t.add_tracker("http://my.tracker.com/announce");
        t.set_creator("Ultraviolet test");


        # // reads the files and calculates the hashes
        # set_piece_hashes(t, ".");
        lt.set_piece_hashes(t,".")
        # ofstream out("my_torrent.torrent", std::ios_base::binary);
        # bencode(std::ostream_iterator<char>(out), t.generate());
        fileContent = t.generate()
        # byteContent= bytearray(fileContent)
        # newFile = open (utils.getHomeFolder()+"torrents/newTorrnet.torrent", "wb")
        # newFile.write(byteContent)
        writeBinaryFile(utils.getHomeFolder()+"torrents/newTorrnet.torrent", fileContent)
Example #6
0
 def finalize(self, path, uid):
   #print 'finalize', path, uid
   try:
     fs = lt.file_storage()
     tmp_fn = os.path.join(self.tmp, uid)
     try: st_size = os.stat(tmp_fn).st_size
     except:
       traceback.print_exc()
       return
       
     #print tmp_fn, st_size
     lt.add_files(fs, tmp_fn, st_size)
     t = lt.create_torrent(fs)
     t.set_creator("DelugeFS");
     lt.set_piece_hashes(t, self.tmp)
     tdata = t.generate()
     #print tdata
     with open(self.hgdb+path, 'wb') as f:
       f.write(lt.bencode(tdata))
     #print 'wrote', self.hgdb+path
     dat_dir = os.path.join(self.dat, uid[:2])
     if not os.path.isdir(dat_dir): 
       try: os.mkdir(dat_dir)
       except: pass
     os.rename(tmp_fn, os.path.join(dat_dir, uid))
     #if os.path.exists(self.shadow+path): os.remove(self.shadow+path)
     #os.symlink(os.path.join(dat_dir, uid), self.shadow+path)
     #print 'committing', self.hgdb+path
     self.repo.hg_commit('wrote %s' % path, files=[self.hgdb+path])
     self.should_push = True
     self.__add_torrent(tdata, path)
   except Exception as e:
     traceback.print_exc()
     raise e
Example #7
0
def generateTorrentOfdownloadedFiles(downloadedFolder):
    print("generateTorrentOfdownloaded Files for sharing...")
    # http://www.libtorrent.org/reference-Create_Torrents.html
    # downloadedFolder = utils.getHomeFolder()+"/"+config.DOWNLOAD_FOLDER
    from os import listdir
    for file in listdir(downloadedFolder):
        print(file)
        fs = lt.file_storage()
        # file_storage fs;

        # // recursively adds files in directories
        # add_files(fs, "./my_torrent");
        lt.add_files(fs, downloadedFolder)
        t = lt.create_torrent()  # ?¿?¿?¿?¿?¿?¿?¿?¿¿?¿¿?
        # create_torrent t(fs);
        lt.create_torrent(t, fs)

        t.add_tracker("http://my.tracker.com/announce")
        t.set_creator("Ultraviolet test")

        # // reads the files and calculates the hashes
        # set_piece_hashes(t, ".");
        lt.set_piece_hashes(t, ".")
        # ofstream out("my_torrent.torrent", std::ios_base::binary);
        # bencode(std::ostream_iterator<char>(out), t.generate());
        fileContent = t.generate()
        # byteContent= bytearray(fileContent)
        # newFile = open (utils.getHomeFolder()+"torrents/newTorrnet.torrent", "wb")
        # newFile.write(byteContent)
        writeBinaryFile(utils.getHomeFolder() + "torrents/newTorrnet.torrent",
                        fileContent)
Example #8
0
def create_torrent(directory, announces=None, output=None, comment=None, web_seeds=None):
    if not output:
        output = directory + ".torrent"

    # "If a piece size of 0 is specified, a piece_size will be calculated such that the torrent file is roughly 40 kB."
    piece_size_multiplier = 0
    piece_size = (16 * 1024) * piece_size_multiplier  # Must be multiple of 16KB

    # http://www.libtorrent.org/make_torrent.html#create-torrent
    flags = libtorrent.create_torrent_flags_t.calculate_file_hashes

    if not os.path.isdir(directory):
        raise Exception("The path {} is not a directory".format(directory))

    fs = libtorrent.file_storage()
    is_not_whitelisted = lambda node: not is_whitelisted(unicode_helpers.decode_utf8(node))
    libtorrent.add_files(fs, unicode_helpers.encode_utf8(directory), is_not_whitelisted, flags=flags)
    t = libtorrent.create_torrent(fs, piece_size=piece_size, flags=flags)

    for announce in announces:
        t.add_tracker(unicode_helpers.encode_utf8(announce))

    if comment:
        t.set_comment(unicode_helpers.encode_utf8(comment))

    for web_seed in web_seeds:
        t.add_url_seed(unicode_helpers.encode_utf8(web_seed))
    # t.add_http_seed("http://...")

    libtorrent.set_piece_hashes(t, unicode_helpers.encode_utf8(os.path.dirname(directory)))

    with open(output, "wb") as file_handle:
        file_handle.write(libtorrent.bencode(t.generate()))

    return output
Example #9
0
	def make_torrent(self, tracker_url, torrent_name, dir_name):
		mkdir_p('torrent_files')
		
		fs = lt.file_storage()
		lt.add_files(fs, dir_name)
		t = lt.create_torrent(fs)
		t.add_tracker(tracker_url)
		lt.set_piece_hashes(t, './torrent_data')
		
		f = open(torrent_name, "wb")
		f.write(lt.bencode(t.generate()))
		f.close()

		e = lt.bdecode(open(torrent_name, 'rb').read())
		info = lt.torrent_info(e)
		
		params = { 
			'save_path': './torrent_data',
		    'ti': info,
			'seed_mode': True
		}
		
		h = self.ses.add_torrent(params)
		
		# Wait a bit for the tracker
		sleep(5)
def addTorrent(filepath, torrentpath, osfilename, filename):
    global torrentName, ses, torrentList  #, torrentHandleList
    fileStorage = lt.file_storage()
    lt.add_files(fileStorage, os.path.normpath(filepath + osfilename))
    lTorrent = lt.create_torrent(fileStorage)  #lTorrent = localTorrent
    torrentList.append(lTorrent)
    addTrackerList(lTorrent)

    lTorrent.set_creator('Hubzilla using Libtorrent %s' % lt.version)
    lTorrent.set_comment(
        "Filename:" +
        filename.encode('utf8', 'strict').decode('unicode_escape'))

    lt.set_piece_hashes(lTorrent, os.path.normpath(filepath))
    gTorrent = lTorrent.generate()  #gTorrent = generated Torrent

    ##write Torrent file to filesystem
    tFile = open(os.path.normpath(torrentpath + filename + ".torrent"), "wb")
    tFile.write(lt.bencode(gTorrent))
    tFile.close()

    handle = ses.add_torrent({
        'ti':
        lt.torrent_info(os.path.normpath(torrentpath + filename + ".torrent")),
        'save_path':
        os.path.normpath(filepath),
        'seed_mode':
        True
    })
    #torrentHandleList.append(handle)
    torrentName[str(handle.get_torrent_info().info_hash())] = filename

    mLink = lt.make_magnet_uri(lt.torrent_info(gTorrent))
    magnetLinks[str(handle.get_torrent_info().info_hash())] = mLink
    return mLink
 def test_path_non_unicode_str(self) -> None:
     fs = lt.file_storage()
     with get_tempdir_stack(os.fsdecode(b"\xff")) as (tempdir, ):
         with open(os.path.join(tempdir, "test.txt"), mode="wb") as fp:
             fp.write(lib.get_random_bytes(1024))
         lt.add_files(fs, tempdir)
     self.assertEqual(fs.file_name(0), "test.txt")
Example #12
0
def NewTorrent(pt):
	info = lt.torrent_info(pt) # This is necessary for some reason
	fs = lt.file_storage()
	lt.add_files(fs,PackagesDirectory)
	h = ses.add_torrent({"save_path": MasterDirectory, "storage_mode": lt.storage_mode_t.storage_mode_sparse, "ti": info, "storage": fs, "flags": 1})
	#h = ses.add_torrent({"save_path": PackagesDirectory, "storage_mode": lt.storage_mode_t.storage_mode_sparse, "ti": info, "storage": fs })
	print("New torrent added")
	return h
Example #13
0
def GenerateTorrent():
	fs = lt.file_storage()
	lt.add_files(fs, PackagesDirectory)
	t = lt.create_torrent(fs, flags = 1&8&16) # 16 does nothing right now
	#t = lt.create_torrent(fs)
	t.add_tracker("http://tpm.blogwithme.net:81/tracker")
	lt.set_piece_hashes(t,MasterDirectory)# ## Not working
	return t.generate()
Example #14
0
    def create_torrent(self):
        # TODO check if root
        tarball_uid = self.get('tarball')
        if not tarball_uid:
            self.log.error("No tarball in DB.")
            return False

        cluster = Cluster(mongo_db=self._mongo_db)
        tarball = cluster.get('path') + "/torrents/" + tarball_uid + ".tgz"
        if not os.path.exists(tarball):
            self.log.error("Wrong path in DB.")
            return False

        tracker_address = cluster.get('frontend_address')
        if tracker_address == '':
            self.log.error("Tracker address needs to be configured.")
            return False

        tracker_port = cluster.get('frontend_port')
        if tracker_port == 0:
            self.log.error("Tracker port needs to be configured.")
            return False

        user = cluster.get('user')
        user_id = pwd.getpwnam(user).pw_uid
        grp_id = pwd.getpwnam(user).pw_gid

        old_cwd = os.getcwd()
        os.chdir(os.path.dirname(tarball))

        uid = str(uuid.uuid4())
        torrentfile = cluster.get('path') + "/torrents/" + uid + ".torrent"

        fs = libtorrent.file_storage()
        libtorrent.add_files(fs, os.path.basename(tarball))
        t = libtorrent.create_torrent(fs)
        if cluster.get('frontend_https'):
            proto = 'https'
        else:
            proto = 'http'
        t.add_tracker((proto + "://" + str(tracker_address) +
                       ":" + str(tracker_port) + "/announce"))

        t.set_creator(torrent_key)
        t.set_comment(uid)
        libtorrent.set_piece_hashes(t, ".")

        f = open(torrentfile, 'w')
        f.write(libtorrent.bencode(t.generate()))
        f.close()
        os.chown(torrentfile, user_id, grp_id)

        self.set('torrent', str(uid))
        os.chdir(old_cwd)

        return True
Example #15
0
    def create_torrent(self):
        # TODO check if root
        tarball_uid = self.get('tarball')
        if not tarball_uid:
            self.log.error("No tarball in DB.")
            return False

        cluster = Cluster(mongo_db=self._mongo_db)
        tarball = cluster.get('path') + "/torrents/" + tarball_uid + ".tgz"
        if not os.path.exists(tarball):
            self.log.error("Wrong path in DB.")
            return False

        tracker_address = cluster.get('frontend_address')
        if tracker_address == '':
            self.log.error("Tracker address needs to be configured.")
            return False

        tracker_port = cluster.get('frontend_port')
        if tracker_port == 0:
            self.log.error("Tracker port needs to be configured.")
            return False

        user = cluster.get('user')
        user_id = pwd.getpwnam(user).pw_uid
        grp_id = pwd.getpwnam(user).pw_gid

        old_cwd = os.getcwd()
        os.chdir(os.path.dirname(tarball))

        uid = str(uuid.uuid4())
        torrentfile = cluster.get('path') + "/torrents/" + uid + ".torrent"

        fs = libtorrent.file_storage()
        libtorrent.add_files(fs, os.path.basename(tarball))
        t = libtorrent.create_torrent(fs)
        if cluster.get('frontend_https'):
            proto = 'https'
        else:
            proto = 'http'
        t.add_tracker((proto + "://" + str(tracker_address) + ":" +
                       str(tracker_port) + "/announce"))

        t.set_creator(torrent_key)
        t.set_comment(uid)
        libtorrent.set_piece_hashes(t, ".")

        f = open(torrentfile, 'w')
        f.write(libtorrent.bencode(t.generate()))
        f.close()
        os.chown(torrentfile, user_id, grp_id)

        self.set('torrent', str(uid))
        os.chdir(old_cwd)

        return True
Example #16
0
def make_torrent(path):
    abs_path = os.path.abspath(path)
    fs = libtorrent.file_storage()
    libtorrent.add_files(fs, abs_path)
    ct = libtorrent.create_torrent(fs)
    ct.add_tracker("http://127.0.0.1/announce")
    # set True if private torrent.
    ct.set_priv(True)
    libtorrent.set_piece_hashes(ct, os.path.split(abs_path)[0])
    return ct.generate()
Example #17
0
def result():
    print(request.values['type']) # should display 'bar'   
    if(request.values['type']=="music"):
        print("ok")
        #videoFile = "c:/Users/龔鈺翔/Documents/BT stream/tmp/a"
        #workingPath = "c:/Users/龔鈺翔/Documents/BT stream/tmp"
        #mainPath = "c:/Users/龔鈺翔/Documents/BT stream/tmp"

        fs = lt.file_storage()
        lt.add_files(fs, videoFile)
        t = lt.create_torrent(fs)
        t.add_tracker("udp://tracker.publicbt.com:80")
        t.add_tracker("udp://open.stealth.si:80")
        t.add_tracker("udp://tracker.opentrackr.org:1337")
        t.add_tracker("udp://tracker.leechers-paradise.org:6969")
        t.add_tracker("udp://tracker.coppersurfer.tk:6969")
        t.add_tracker("udp://140.115.152.14:2255")
        t.add_tracker("http://54.39.98.124:80/announce")
        t.add_tracker("udp://p4p.arenabg.com:1337/announce")

        t.set_creator("My Torrent")
        t.set_comment("Test")
        lt.set_piece_hashes(t, workingPath)
        torrent = t.generate()

        f = open(workingPath+"/"+"mytorrent.torrent", "wb")
        f.write(lt.bencode(torrent))
        f.close()

#ps = lt.proxy_settings()
#ps.type = lt.proxy_type.http
#ps.hostname = "hostname.de"
#ps.port = 1003

        ses = lt.session()
        ses.listen_on(6881, 6891)
#ses.set_proxy(ps)
#ses.set_web_seed_proxy(ps)

        handle = ses.add_torrent({'ti': lt.torrent_info(torrent), 'save_path': workingPath,})
#handle.is_seed(1)
#h=lt.add_magnet_uri(ses,lt.make_magnet_uri(lt.torrent_info(torrent)),{'save_path':workingPath,'seed_mode':True})
        print(lt.make_magnet_uri(lt.torrent_info(torrent)))
    #z=input('press anything to go')
        
        print(handle.is_seed()) 
        thread1=threading.Thread(target=server)
        thread1.setDaemon(True)
        thread1.start()
        return lt.make_magnet_uri(lt.torrent_info(torrent))

        
    else:
        print("request.values['type']")
        return"error"
Example #18
0
 def create(target):
   url = "http://{0}:6969/announce".format(socket.gethostname())
   creator = "Ports Management Team <*****@*****.**>"
   fs = libtorrent.file_storage()
   libtorrent.add_files(fs, target)
   torrent = libtorrent.create_torrent(fs)
   torrent.add_tracker(url, 0)
   torrent.set_creator(creator)
   libtorrent.set_piece_hashes(torrent, os.path.dirname(target))
   data = libtorrent.bencode(torrent.generate())
   return Torrent(target, data=data)
Example #19
0
 def prepare_transmit( self, job ):
    # create the .torrent file from the given file
    fs = lt.file_storage()
    
    lt.add_files( fs, job.get_attr( iftfile.JOB_ATTR_SRC_NAME ) )
    
    ct = lt.create_torrent( fs, job.get_attr( iftfile.JOB_ATTR_CHUNKSIZE ) )
    
    ct.set_creator("iftd: " + self.name )
    
    self.file_to_send = job.get_attr( iftfile.JOB_ATTR_SRC_NAME )
    
    # if we were given a tracker or list of trackers, add them
    if job.get_attr( IFTBITTORRENT_TRACKER ) != None:
       if type(job.get_attr( IFTBITTORRENT_TRACKER )) == str:
          ct.add_tracker( job.get_attr( IFTBITTORRENT_TRACKER ), 0 )
       
       if type(job.get_attr( IFTBITTORRENT_TRACKER )) == list:
          for tracker in job.get_attr( IFTBITTORRENT_TRACKER ):
             ct.add_tracker(tracker, 0)
          
       
    
    else:
       # add some default trackers
       ct.add_tracker("http://tracker.openbittorrent.com/announce", 0)
       ct.add_tracker("udp://tracker.openbittorrent.com:80/announce", 0)
       ct.add_tracker("http://tracker.publicbt.com/announce", 0)
       ct.add_tracker("udp://tracker.publicbt.com:80/announce", 0)
    
    # if we were given one or more http seeds, add them too
    if job.get_attr( IFTBITTORRENT_HTTP_SEEDS ) != None:
       if type(job.get_attr( IFTBITTORRENT_HTTP_SEEDS )) == str:
          ct.add_url_seed( job.get_attr( IFTBITTORRENT_HTTP_SEEDS ) )
        
       if type(job.get_attr( IFTBITTORRENT_HTTP_SEEDS )) == list:
          for seed in job.get_attr( IFTBITTORRENT_HTTP_SEEDS ):
             ct.add_url_seed( seed )
    
    lt.set_piece_hashes( ct, os.path.dirname( job.get_attr( iftfile.JOB_ATTR_SRC_NAME ) ) )
    
    # encode the torrent into a .torrent buffer
    self.torrent_str = lt.bencode( ct.generate() )
    
    # if given a torrent path, write out the torrent
    if job.get_attr( IFTBITTORRENT_TORRENT_PATH ) != None:
       try:
          fd = open( job.get_attr( IFTBITTORRENT_TORRENT_PATH ), "wb" )
          fd.write( self.torrent_str )
          fd.close()
       except Exception, inst:
          iftlog.exception( self.name + ": could not output torrent data to " + job.get_attr( IFTBITTORRENT_TORRENT_PATH ), inst)
          return E_IOERROR
Example #20
0
def make_torrent(torrent_path, data_path):
    fs = libtorrent.file_storage()
    libtorrent.add_files(fs, data_path)
    t = libtorrent.create_torrent(fs)
    t.set_creator("ccas")
    libtorrent.set_piece_hashes(t, os.path.dirname(data_path))
    tdata = t.generate()
    if not os.access(os.path.dirname(torrent_path), os.W_OK):
        os.makedirs(os.path.dirname(torrent_path))
    with open(torrent_path, 'wb') as f:
        f.write(libtorrent.bencode(tdata))
    return
Example #21
0
def make_torrent(torrent_path, data_path):
    fs = libtorrent.file_storage()
    libtorrent.add_files(fs, data_path)
    t = libtorrent.create_torrent(fs)
    t.set_creator("ccas")
    libtorrent.set_piece_hashes(t, os.path.dirname(data_path))
    tdata = t.generate()
    if not os.access(os.path.dirname(torrent_path), os.W_OK):
        os.makedirs(os.path.dirname(torrent_path))
    with open(torrent_path, 'wb') as f:
        f.write(libtorrent.bencode(tdata))
    return
Example #22
0
def create_torrent(file_path,file_name):
	fs = lt.file_storage()
	lt.add_files(fs, file_path)
	t = lt.create_torrent(fs)
	t.add_tracker("udp://tracker.openbittorrent.com:80/announce", 0)
	t.set_creator('libtorrent %s' % lt.version)
	t.set_comment("Test")
	lt.set_piece_hashes(t, ".")
	torrent = t.generate()    
	f = open(file_name, "wb")
	f.write(lt.bencode(torrent))
	f.close()
Example #23
0
    def create_module_package(self, module):
        payloads_directory = os.path.join(self.working_directory, PAYLOADS_DIR)
        torrents_directory = os.path.join(self.working_directory, TORRENTS_DIR)

        tracker_list = [
            'udp://tracker.publicbt.com:80/announce',
            'udp://tracker.openbittorrent.com:80/announce'
        ]

        self._logger.debug("transport: creating torrent (%s)", module)

        # Create torrent
        fs = lt.file_storage()
        lt.add_files(fs, os.path.join(payloads_directory, module))
        t = lt.create_torrent(fs)

        if self.tracker_enable:
            for tracker in tracker_list:
                t.add_tracker(tracker, 0)

        lt.set_piece_hashes(t, payloads_directory)
        torrent = t.generate()

        # Create torrent file
        torrent_file_path = os.path.join(torrents_directory,
                                         module + ".torrent")
        f = open(torrent_file_path, "wb")
        f.write(lt.bencode(torrent))
        f.close()

        # Create magnet link
        torrent_info = lt.torrent_info(torrent_file_path)
        magnet_link = "magnet:?xt=urn:btih:%s&dn=%s" % (
            torrent_info.info_hash(), torrent_info.name())
        magnet_file = os.path.join(torrents_directory, module + ".magnet")
        f = open(magnet_file, "wb")
        f.write(magnet_link)
        f.close()

        self._logger.debug("transport: seeding torrent (%s)", module)

        # Seed torrent
        h = self.ses.add_torrent({
            'ti': torrent_info,
            'save_path': payloads_directory,
            'seed_mode': True
        })

        return {
            'info_hash': torrent_info.info_hash(),
            'name': torrent_info.name(),
        }
Example #24
0
 def create_torrent(self, torrent_path, creator=None, comment=None):
     fs = libtorrent.file_storage()
     libtorrent.add_files(fs, self.target_file)
     t = libtorrent.create_torrent(fs)
     for tracker in self.tracker_list:
         t.add_tracker(tracker, 0)
     t.set_creator(creator or 'libtorrent %s' % libtorrent.version)
     t.set_comment(comment or 'kanjian')
     libtorrent.set_piece_hashes(t, self.base_path)
     torrent = t.generate()
     f = open(torrent_path, "wb")
     f.write(libtorrent.bencode(torrent))
     f.close()
Example #25
0
def create_torrent_from_dir(directory, torrent_filename):
    fs = file_storage()
    add_files(fs, directory)
    t = create_torrent(fs)
    # t = create_torrent(fs, flags=17) # piece alignment
    t.set_priv(False)
    set_piece_hashes(t, os.path.dirname(directory))
    torrent = t.generate()
    with open(torrent_filename, 'wb') as f:
        f.write(bencode(torrent))

    infohash = torrent_info(torrent).info_hash().to_bytes()
    return torrent, infohash
Example #26
0
def create_torrent_from_dir(directory, torrent_filename):
    fs = file_storage()
    add_files(fs, directory)
    t = create_torrent(fs)
    # t = create_torrent(fs, flags=17) # piece alignment
    t.set_priv(False)
    set_piece_hashes(t, os.path.dirname(directory))
    torrent = t.generate()
    with open(torrent_filename, 'wb') as f:
        f.write(bencode(torrent))

    infohash = torrent_info(torrent).info_hash().to_bytes()
    return torrent, infohash
Example #27
0
def make_torrent(update_dir):
    fs = lt.file_storage()
    lt.add_files(fs, os.path.join(os.getcwd(), 'upload/%s' % (update_dir, )))

    t = lt.create_torrent(fs)
    t.set_creator('server example')
    lt.set_piece_hashes(t, os.path.join(os.getcwd(), 'upload'))

    contents = t.generate()

    from pprint import pprint
    pprint(dict(contents))

    return lt.torrent_info(contents)
Example #28
0
def make_torrent(file):
    import libtorrent as lt

    fs = lt.file_storage()
    piece_size = 256 * 1024
    lt.add_files(fs, file.path)
    if file.real_name:
        fs.set_name(file.real_name)

    t = lt.create_torrent(fs, piece_size)
    lt.set_piece_hashes(t, file.storage_folder)
    t.add_url_seed(file.blob)
    t.set_creator('a2p')

    return lt.bencode(t.generate())
def maketorrent(source):
    print "Making .torrent file for " + source + "..."
    fs = lt.file_storage()
    lt.add_files(fs, source)
    t = lt.create_torrent(fs)
    for ip in ip4_addresses():
        trAddress = "http://" + ip + ":6969/announce"
        t.add_tracker(trAddress,0)
    t.set_creator('A bunny')
    lt.set_piece_hashes(t, ".")
    torrent = t.generate()
    f = open("t.torrent", "wb")
    f.write(lt.bencode(torrent))
    f.close()
    print "Finished making .torrent file"
def mktorrent(f,o):
    """create a torrent from file f (or directory) to o.torrent"""
    print("Let's create : {}".format(o))
    fs = lt.file_storage()
    lt.add_files(fs, f)
    t = lt.create_torrent(fs)
    t.set_creator('btshare.py - libtorrent {0}'.format(lt.version))
    t.set_comment("Smile!")
    t.add_node("dht.transmissionbt.com", 6881)
    t.add_node("router.bittorrent.com", 6881)
    t.add_node("127.0.0.1", 6881)
    lt.set_piece_hashes(t, os.path.dirname(f))
    torrent = t.generate()    
    with open(o, "wb") as torrentfile:
        torrentfile.write(lt.bencode(torrent))
Example #31
0
def createTorrent(filename):
    fs = lt.file_storage()
    lt.add_files(fs, C['producer']['source'] + "/" + filename)
    t = lt.create_torrent(fs)
    t.add_tracker(C['producer']['announce'], 0)
    t.set_creator('libtorrent %s' % lt.version)
    t.set_comment(C['producer']['comment'])
    lt.set_piece_hashes(t, C['producer']['source'])
    torrent = t.generate()
    tn = torrentName(filename)
    f = open(tn, "wb")
    f.write(lt.bencode(torrent))
    f.close()
    logger.debug("created torrent file for {}".format(filename))
    return tn
Example #32
0
 def create_torrent(self):
     # TODO check if root
     tarball_uid = self.get('tarball')
     cluster = Cluster(mongo_db = self._mongo_db)
     if not bool(tarball_uid):
         self._logger.error("No tarball in DB.")
         return None
     tarball = cluster.get('path') + "/torrents/" + tarball_uid + ".tgz"
     if not os.path.exists(tarball):
         self._logger.error("Wrong path in DB.")
         return None
     tracker_address = cluster.get('frontend_address')
     if tracker_address == '':
         self._logger.error("Tracker address needs to be configured.")
         return None
     tracker_port = cluster.get('frontend_port')
     if tracker_port == 0:
         self._logger.error("Tracker port needs to be configured.")
         return None
     user = cluster.get('user')
     if not user:
         self._logger.error("User needs to be configured.")
         return None
     #group = cluster.get('group')
     #if not group:
     #    self._logger.error("Group needs to be configured.")
     #    return None
     user_id = pwd.getpwnam(user).pw_uid
     grp_id = pwd.getpwnam(user).pw_gid
     old_cwd = os.getcwd()
     os.chdir(os.path.dirname(tarball))
     uid = str(uuid.uuid4())
     torrentfile = str(cluster.get('path')) + "/torrents/" + uid
     fs = libtorrent.file_storage()
     libtorrent.add_files(fs, os.path.basename(tarball))
     t = libtorrent.create_torrent(fs)
     t.add_tracker("http://" + str(tracker_address) + ":" + str(tracker_port) + "/announce")
     t.set_creator(torrent_key)
     t.set_comment(uid)
     libtorrent.set_piece_hashes(t, ".")
     f = open(torrentfile, 'w')
     f.write(libtorrent.bencode(t.generate()))
     f.close()
     self.set('torrent', str(uid))
     os.chown(torrentfile, user_id, grp_id)
     shutil.move(torrentfile, torrentfile + ".torrent")
     os.chdir(old_cwd)
     return True
Example #33
0
def create_torrent(blob, path):
    destination = os.path.join("storage/torrents", blob + ".torrent")
    if os.path.exists(destination):
        return destination
    fs = torrent.file_storage()
    torrent.add_files(fs, path)
    t = torrent.create_torrent(fs)
    t.add_tracker(TRACKER, 0)
    t.set_comment(blob)
    torrent.set_piece_hashes(t, os.path.dirname(path))
    generated_torrent = t.generate()
    with open(destination, "wb") as f:
        f.write(torrent.bencode(generated_torrent))

    add_torrent(destination)
    return destination
    def test_args_pred_positional(self) -> None:
        with tempfile.TemporaryDirectory() as path:
            # Write some random data to two files
            file_paths = [
                os.path.join(path, name) for name in ("a.txt", "b.txt")
            ]
            for file_path in file_paths:
                with open(file_path, mode="wb") as fp:
                    fp.write(lib.get_random_bytes(1024))
            calls = [unittest.mock.call(file_path) for file_path in file_paths]

            fs = lt.file_storage()
            pred = unittest.mock.Mock(return_value=True)
            lt.add_files(fs, path, pred)
            pred.assert_has_calls(calls, any_order=True)
            self.assertEqual(fs.num_files(), 2)
    def test_args(self) -> None:
        fs = lt.file_storage()
        callback = unittest.mock.Mock()
        with get_tempdir_stack("outer", "inner") as (outer, inner):
            with open(os.path.join(inner, "test.txt"), mode="wb") as fp:
                fp.write(lib.get_random_bytes(1024))
            lt.add_files(fs, inner)
            ct = lt.create_torrent(fs)

            # path str
            lt.set_piece_hashes(ct, outer)

            # path str and callback
            lt.set_piece_hashes(ct, outer, callback)
            calls = [unittest.mock.call(0)]
            callback.assert_has_calls(calls)
Example #36
0
    def do(self):
        """make a torrent file."""
        def file_filter(name):
            print "filter name:", name
            print "torrent type:", self.type
            if os.path.samefile(name ,os.path.dirname(self.source_path)):
                return True
            if self.type == 'vhd':
                chain = list()
                vhd = RBTreeVHD(self.source_path)
                chain = vhd.get_chain()
                log.debug("vhd-chain: %s" % chain)
                if name in chain:
                    return True
            else:
                if os.path.samefile(name, self.source_path):
                    return True

        if not os.path.exists(self.source_path):
            raise InvalidParamError("%s not exists." % self.source_path)
        source_path = os.path.abspath(self.source_path)
        torrent_file = "%s/%s.torrent" % (self.save_dir, os.path.basename(source_path))
        fs = lt.file_storage()
        lt.add_files(fs, os.path.dirname(source_path), file_filter)
        log.debug("add %s files to torrent." % fs.num_files())
        log.debug("total_size: %s" % fs.total_size())
        creator = lt.create_torrent(fs, 0, 4*1024*1024)
        #creator.add_tracker(str(self.tracker_url).strip())
        creator.set_creator("RBTree Vtrans %s" % VTRANS_VERSION)
        comment = dict()
        comment["type"] = self.type
        creator.set_comment(json.dumps(comment))
        #lt.set_piece_hashes(creator, os.path.split(source_path)[0], lambda x: sys.stderr.write('.'))
        #lt.set_piece_hashes(creator, "/home/xjc/vtrans-master/test", lambda x: sys.stderr.write('.'))
        #lt.set_piece_hashes(creator, os.path.dirname(os.path.dirname(source_path)), lambda x: sys.stderr.write('.'))
        num_pieces = creator.num_pieces()
        def piece_hash_process(x):
            self.progress = (x+1)*100/num_pieces
            print "\rall %s pieces, setting piece %s, porcess: %s%%" % (num_pieces, x+1, self.progress),
            sys.stdout.flush()
        #lt.set_piece_hashes(creator, os.path.dirname(os.path.dirname(source_path)), lambda x: sys.stderr.write("%s " % x/))
        lt.set_piece_hashes(creator, os.path.dirname(os.path.dirname(source_path)), piece_hash_process)
        sys.stderr.write('\n')
        with open(torrent_file, "wb") as f:
            f.write(lt.bencode(creator.generate()))
        return 0, "make torrent succesfully."
Example #37
0
def _mkatp(tmp_path_factory: pytest.TempPathFactory,
           *,
           proto=Proto.HYBRID) -> lt.add_torrent_params:
    atp = lt.add_torrent_params()
    # As of 2.0.6, create_torrent.set_hash2 isn't bound in python
    tmp_path = tmp_path_factory.mktemp("test-atp")
    (tmp_path / "file.txt").write_bytes(random.randbytes(1024))
    fs = lt.file_storage()
    lt.add_files(fs, str(tmp_path))
    flags = 0
    if not (proto & V2):
        flags = lt.create_torrent.v1_only
    elif not (proto & V1):
        flags = lt.create_torrent.v2_only
    ct = lt.create_torrent(fs, flags=flags)
    lt.set_piece_hashes(ct, str(tmp_path.parent))
    atp.ti = lt.torrent_info(ct.generate())
    return atp
Example #38
0
def generate_torrent(incl_file: pathlib.Path, resource_hash: str) -> dict:
    """Generate torrent file for a given file and write it to disk
    :param pathlib.Path incl_file: file to include in torrent
    :param str resource_hash: resource hash
    :rtype: tuple
    :return: (torrent file as pathlib, torrent file data sha1 hash)
    """
    fs = libtorrent.file_storage()
    libtorrent.add_files(fs, str(incl_file))
    tor = libtorrent.create_torrent(fs)
    tor.set_creator('libtorrent {}'.format(libtorrent.version))
    libtorrent.set_piece_hashes(tor, str(incl_file.parent))
    torrent = tor.generate()
    torrent_data = libtorrent.bencode(torrent)
    fp = _TORRENT_DIR / '{}.torrent'.format(resource_hash)
    with fp.open('wb') as f:
        f.write(torrent_data)
    return fp, hashlib.sha1(torrent_data).hexdigest()
Example #39
0
def create_torrent(message_digest):
    #Create torrent
    name = str(message_digest) + ".torrent"
    fs = lt.file_storage()
    lt.add_files(fs, path)
    t = lt.create_torrent(fs)
    trackerList = [
        'udp://tracker.coppersurfer.tk:6969',
        'udp://tracker.opentrackr.org:1337/announce',
        'udp://torrent.gresille.org:80/announce',
        'udp://9.rarbg.me:2710/announce', 'udp://p4p.arenabg.com:1337',
        'udp://tracker.internetwarriors.net:1337'
    ]

    for tracker in trackerList:
        t.add_tracker(tracker, 0)
        t.set_creator('libtorrent %s' % lt.version)
        t.set_comment("Test")
        lt.set_piece_hashes(t, ".")
        torrent = t.generate()
        f = open(name, "wb")
        f.write(lt.bencode(torrent))
        f.close()

        #Seed torrent
        ses = lt.session()
        ses.listen_on(6881, 6891)
        h = ses.add_torrent({
            'ti': lt.torrent_info(name),
            'save_path': '.',
            'seed_mode': True
        })
        print("Total size: " + str(h.status().total_wanted))
        print("Name: " + h.name())
        while h.is_seed():
            s = h.status()
            state_str = ['queued', 'checking', 'downloading metadata', \
              'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']

            print('\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
              (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state]))
            sys.stdout.flush()

            time.sleep(1)
Example #40
0
    def execute(self):
        if not self._torrent_data:
            raise ValueError('Missing file or directory path for torrent data')
        if not self._output_file:
            raise ValueError('Missing torrent output file')

        if os.path.exists(self._output_file) and not self._overwrite:
            self._println('Torrent file already exists')
            return

        input = os.path.abspath(self._torrent_data)

        fs = lt.file_storage()
        lt.add_files(fs, input)
        if fs.num_files() == 0:
            self._println('Error: no files added to torrent')
            return

        piece_length = self._calculate_piece_length()
        #pad_size_limit = 4 * 1024 * 1024
        pad_size_limit = -1

        t = lt.create_torrent(fs, piece_length, pad_size_limit)

        # TODO: support multiple tracker urls
        if not self._tracker:
            raise ValueError('Missing tracker URL')
        t.add_tracker(self._tracker)

        creator = 'terasaur seedbank %s' % lt.version
        t.set_creator(creator)
        if self._comment:
            t.set_comment(self._comment)
        t.set_priv(self._private)

        data_dir = os.path.split(input)[0]
        if self._show_progress:
            lt.set_piece_hashes(t, data_dir, lambda x: self._print('.'))
            self._println('')
        else:
            lt.set_piece_hashes(t, data_dir)

        self._write_output_file(t, self._output_file)
Example #41
0
 def __finalize(self, path, olduid):
     if self.LOGLEVEL > 2: print 'finalize', path, olduid
     try:
         # try sha256 before making torrent
         old_tmp_fn = os.path.join(self.tmp, olduid).encode(FS_ENCODE)
         uid = sha256sum(old_tmp_fn, 4096)
         tmp_fn = os.path.join(self.tmp, uid).encode(FS_ENCODE)
         path = None
         if self.LOGLEVEL > 3: print 'olduid',olduid
         for k,v in self.open_files.items():
             if self.LOGLEVEL > 3: print 'k',k
             if self.LOGLEVEL > 3: print 'v',v
             if olduid.strip() == v:
                 if self.LOGLEVEL > 3: print 'found k',k
                 path = k
         if self.LOGLEVEL > 3: print 'path',path
         if self.LOGLEVEL > 3: print 'old_tmp',old_tmp_fn
         if self.LOGLEVEL > 3: print 'sha_tmp_fn',tmp_fn
         os.rename(old_tmp_fn, tmp_fn)
         fs = libtorrent.file_storage()
         #print tmp_fn
         libtorrent.add_files(fs, tmp_fn)
         t = libtorrent.create_torrent(fs)
         t.set_creator("DelugeFS");
         libtorrent.set_piece_hashes(t, self.tmp)
         tdata = t.generate()
         #print tdata
         fn = os.path.join(self.indexdir, path).encode(FS_ENCODE)
         with open(fn, 'wb') as f:
             f.write(libtorrent.bencode(tdata))
         #print 'wrote', fn
         dat_dir = os.path.join(self.chunksdir, uid[:2]).encode(FS_ENCODE)
         if not os.path.isdir(dat_dir):
             try: os.mkdir(dat_dir)
             except: pass
         shutil.copyfile(tmp_fn, os.path.join(dat_dir, uid).encode(FS_ENCODE))
         os.remove(tmp_fn)
         #print 'committing', fn
         self.__add_torrent(tdata, path)
         del self.open_files[path]
     except Exception as e:
         traceback.print_exc()
         raise e
Example #42
0
def make_torrent(path, save):
    fs = lt.file_storage()
    lt.add_files(fs, path)
    if fs.num_files() == 0:
        print 'no files added'
        sys.exit(1)
    input = os.path.abspath(path)
    basename = os.path.basename(path)
    t = lt.create_torrent(fs, 0, 4 * 1024 * 1024)
    t.add_tracker("http://10.0.1.5:8760/announce")
    t.set_creator('libtorrent %s' % lt.version)
    lt.set_piece_hashes(t, os.path.split(input)[0], lambda x: sys.stderr.write('.'))
    sys.stderr.write('\n')
    save = os.path.dirname(input)
    save = "%s/%s.torrent" % (save, basename)
    f=open(save, "wb")
    f.write(lt.bencode(t.generate()))
    f.close()
    print "the bt torrent file is store at %s" % save
Example #43
0
 def create(self, tracker_ip):
     """
     Description: Creates a new torrent.
     
     tracker_ip: The tracker IP:PORT string to use when creating the torrent.  Should match whatever tracker we're using for the cloud, obviously! :)
     """
     
     log.debug("Creating new torrent file, setting tracker to: %s" % tracker_ip)
     
     # Set the name of our torrent
     self.ti.torr_name = self.ti.torr_path + "/" + self.name_torrent(self.ti.file_name)                      
     
     # Create a storage object, and add the file which will be torrentized
     file_st = lt.file_storage()
     lt.add_files(file_st, self.ti.file_name)
            
     # Create the torrent
     try:
         torr = lt.create_torrent(file_st, self.ti.piece_size)
         torr.add_tracker("http://" + tracker_ip.tracker_ip + tracker_ip.announce_url)
         torr.set_comment(self.ti.comments)
         torr.set_creator(self.ti.creator)
         lt.set_piece_hashes(torr, os.path.dirname(self.ti.file_name))
     except:
         log.exception("Failed to create torrent")
         raise
     
     # Write to file
     try:
         f = open(self.ti.torr_name, "wb")
         f.write(lt.bencode(torr.generate()))
         f.close()
     except:
         raise
     
     # get the info_hash before returning
     self.ti.info      = lt.torrent_info(self.ti.torr_name)
     self.ti.info_hash = self.ti.info.info_hash()
     
     log.debug("New torrent details: %s" % self.ti)
     
     # Return the TorrentMetaInfo Object
     return self.ti
Example #44
0
 def create_handle(self, link=None, path=None):
     params = {
         'save_path': 'tmp',
         # 'upload_mode': True,
         'storage_mode': lt.storage_mode_t.storage_mode_compact,
         'paused': False,
         'auto_managed': True,
     }
     if link:
         return lt.add_magnet_uri(self.session, link, params)
     if path:
         return lt.add_files(self.session, path, params)
Example #45
0
    def make_torrent(self, tracker_url, torrent_name, dir_name):
        mkdir_p('torrent_files')

        fs = lt.file_storage()
        lt.add_files(fs, dir_name)
        t = lt.create_torrent(fs)
        t.add_tracker(tracker_url)
        lt.set_piece_hashes(t, './torrent_data')

        f = open(torrent_name, "wb")
        f.write(lt.bencode(t.generate()))
        f.close()

        e = lt.bdecode(open(torrent_name, 'rb').read())
        info = lt.torrent_info(e)

        params = {'save_path': './torrent_data', 'ti': info, 'seed_mode': True}

        h = self.ses.add_torrent(params)

        # Wait a bit for the tracker
        sleep(5)
Example #46
0
    def create_torrent(self, file_path):
	
	print "Creating .torrent for %s..." % file_path
	
	
	if os.path.exists(file_path):
	    fs = libtorrent.file_storage()
	    libtorrent.add_files(fs, str(file_path)) #Apparently file_path is unicode, and libtorrent does not like that. 
	    self.t = libtorrent.create_torrent(fs)
	    #self.t.add_tracker(self.tracker) tpm_daemon -> tpm_server -> opentracker
	    self.t.set_creator("tpmd 1.0")
	    torrent_name = self.t.generate()["info"]["name"]
	    with open("%s.torrent" % (torrent_name), "wb") as torrent_file:
		torrent_file.write(libtorrent.bencode(self.t.generate()))
	    print "Torrent %s created" % torrent_name
	    
	    #implement integrity check here
	    
	    return True
	
	else:
	    print "File does not exist"
Example #47
0
    def finalize(self, path, uid):
        #print 'finalize', path, uid
        try:
            fs = lt.file_storage()
            tmp_fn = os.path.join(self.tmp, uid)
            try:
                st_size = os.stat(tmp_fn).st_size
            except:
                traceback.print_exc()
                return

            #print tmp_fn, st_size
            lt.add_files(fs, tmp_fn, st_size)
            t = lt.create_torrent(fs)
            t.set_creator("DelugeFS")
            lt.set_piece_hashes(t, self.tmp)
            tdata = t.generate()
            #print tdata
            with open(self.hgdb + path, 'wb') as f:
                f.write(lt.bencode(tdata))
            #print 'wrote', self.hgdb+path
            dat_dir = os.path.join(self.dat, uid[:2])
            if not os.path.isdir(dat_dir):
                try:
                    os.mkdir(dat_dir)
                except:
                    pass
            os.rename(tmp_fn, os.path.join(dat_dir, uid))
            #if os.path.exists(self.shadow+path): os.remove(self.shadow+path)
            #os.symlink(os.path.join(dat_dir, uid), self.shadow+path)
            #print 'committing', self.hgdb+path
            self.repo.hg_commit('wrote %s' % path, files=[self.hgdb + path])
            self.should_push = True
            self.__add_torrent(tdata, path)
        except Exception as e:
            traceback.print_exc()
            raise e