Exemple #1
0
 def _create_torrent(self, resource, fs, root='.', use_sudo=False):
     t = lt.create_torrent(fs)
     transports = resource.transports()
     torrent_transport = next(
         (x for x in transports if x['name'] == 'torrent'))
     trackers = torrent_transport['trackers']
     for tracker in trackers:
         t.add_tracker(tracker)
     lt.set_piece_hashes(t, os.path.join(root, '..'))
     torrent = t.generate()
     torrent['priv'] = True  # private torrent, no DHT, only trackers
     name = self._create_torrent_name()
     try:
         # not checking for path existence
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     except IOError as e:
         if e.errno != errno.ENOENT:
             raise
         os.makedirs(self._torrent_path)
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     log.debug("Created torrent file %s", name)
     magnet_uri = lt.make_magnet_uri(lt.torrent_info(name))
     # self._torrents[root] = (name, magnet_uri)
     if not use_sudo:
         self._torrents.append((name, magnet_uri, root))
     else:
         self._sudo_torrents.append((name, magnet_uri, root))
     return name
def create_torrent(path,filename=""):
    fs = lt.file_storage()
    if filename=="":
		listz = list_folder(top)
		for tuplez in listz:
			path=tuplez[0]
			filename=tuplez[1]
			fs.add_file(pathz , size)
    else:
        pathz = os.path.join(path,filename)
        print "pathz", pathz
        size = os.path.getsize(pathz)
        fs.add_file(filename, size)
        #fs.add_file(pathz , size)
    tor = lt.create_torrent(fs)
    lt.set_piece_hashes(tor,'.')
    tor.set_comment("COMEONES")
    tor.set_creator("PEONDUSUD")
    announce_url = "http://www.gks.gs/tracker"
    tor.add_tracker(announce_url)
    tor.set_priv(True)
    tor.add_url_seed("http://192.168.70.136:58888")
    print dir(tor)
    f = open(save_torrent_folder + filename + ".torrent", "wb")
    f.write(lt.bencode(tor.generate()))
    f.close()
    print "torrent raw :"
    print lt.bencode(tor.generate())
Exemple #3
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
Exemple #4
0
 def _create_torrent(self, resource, fs, root='.', use_sudo=False):
     t = lt.create_torrent(fs)
     transports = resource.transports()
     torrent_transport = next(
         (x for x in transports if x['name'] == 'torrent'))
     trackers = torrent_transport['trackers']
     for tracker in trackers:
         t.add_tracker(tracker)
     lt.set_piece_hashes(t, os.path.join(root, '..'))
     torrent = t.generate()
     torrent['priv'] = True  # private torrent, no DHT, only trackers
     name = self._create_torrent_name()
     try:
         # not checking for path existence
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     except IOError as e:
         if e.errno != errno.ENOENT:
             raise
         os.makedirs(self._torrent_path)
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     log.debug("Created torrent file %s", name)
     magnet_uri = lt.make_magnet_uri(lt.torrent_info(name))
     # self._torrents[root] = (name, magnet_uri)
     if not use_sudo:
         self._torrents.append((name, magnet_uri, root))
     else:
         self._sudo_torrents.append((name, magnet_uri, root))
     return name
Exemple #5
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)
Exemple #6
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
Exemple #7
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 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)
Exemple #9
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()
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 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()
Exemple #12
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 test_path_non_unicode_bytes(self) -> None:
     fs = lt.file_storage()
     with get_tempdir_stack(b"\xff", b"test") as (outer, inner):
         with open(os.path.join(inner, b"test.txt"), mode="wb") as fp:
             fp.write(lib.get_random_bytes(1024))
         fs.add_file(os.path.join("test", "test.txt"), 1024)
         ct = lt.create_torrent(fs)
         lt.set_piece_hashes(ct, outer)
Exemple #14
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()
 def test_exceptions(self) -> None:
     fs = lt.file_storage()
     fs.add_file("test.txt", 1024)
     ct = lt.create_torrent(fs)
     with tempfile.TemporaryDirectory() as path:
         with self.assertRaises(RuntimeError):
             lt.set_piece_hashes(ct, path)
         with self.assertRaises(RuntimeError):
             lt.set_piece_hashes(ct, path, lambda _: None)
Exemple #16
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
Exemple #17
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
Exemple #18
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()
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"
Exemple #20
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)
Exemple #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
Exemple #22
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
Exemple #23
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
Exemple #24
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()
Exemple #25
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(),
        }
Exemple #26
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()
Exemple #27
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
Exemple #28
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
Exemple #29
0
def _create_fake_torrent(tmpdir):
    # beware, that's just for testing
    path = os.path.join(tmpdir, 'tmp')
    with open(path, 'wb') as myfile:
        size = myfile.write(
            bytes([random.randint(0, 255) for _ in range(40)]) * 1024)
    file_storage = libtorrent.file_storage()
    file_storage.add_file('tmp', size)
    t = libtorrent.create_torrent(file_storage, 0, 4 * 1024 * 1024)
    libtorrent.set_piece_hashes(t, tmpdir)
    info = libtorrent.torrent_info(t.generate())
    btih = sha1(info.metadata()).hexdigest()
    return info, btih
Exemple #30
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)
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))
Exemple #32
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())
Exemple #33
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
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"
Exemple #35
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
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(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)
Exemple #38
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."
Exemple #39
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()
Exemple #40
0
def create_torrent_from_folder(folder, files):
    file_storage = libtorrent.file_storage()
    file_storage.set_name(folder.name)

    for file in files:
        relative = file.relative_to(folder.parent)
        size = file.stat().st_size

        file_storage.add_file(str(relative), size)

    flags = libtorrent.create_torrent_flags_t.optimize
    torrent = libtorrent.create_torrent(file_storage, flags=flags)

    torrent.set_creator(_creator)
    libtorrent.set_piece_hashes(torrent, str(folder.parent))

    torrent_data = torrent.generate()
    return torrent_data, libtorrent.bencode(torrent_data)
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
Exemple #42
0
def create_torrent(input_path, output_path):
    input_path = os.path.abspath(input_path)
    input_dir = os.path.dirname(input_path)
    input_file_name = os.path.basename(input_path)
    output_path = os.path.abspath(output_path)

    fs = libtorrent.file_storage()
    file_size = os.path.getsize(input_path)
    fs.add_file(input_file_name, file_size)

    torrent = libtorrent.create_torrent(fs)
    torrent.set_creator("OpenFUN http://github.com/openfun/")
    for tracker in TRACKERS:
        torrent.add_tracker(tracker)
    libtorrent.set_piece_hashes(torrent, input_dir)

    with open(output_path, 'wb') as f:
        f.write(libtorrent.bencode(torrent.generate()))
Exemple #43
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)
Exemple #44
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 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
Exemple #46
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
Exemple #47
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)
def generateTorrentFromMagnet (magnet):
    print("generateTorrentFromMagnet")
    # file_storage fs;
    #
    # // recursively adds files in directories
    # add_files(fs, "./my_torrent");
    #
    # create_torrent t(fs);
    # torrent_info ti = handle.get_torrent_info()
    handle = lt.torrent_handle()
    ti = handle.get_torrent_info()

    t = lt.create_torrent() # ?¿?¿?¿?¿?¿?
    lt.create_torrent (t, ti)

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

    # // reads the files and calculates the hashes
    pieceHashes = lt.set_piece_hashes(t,".")
    # set_piece_hashes(t, ".");
    writeBinaryFile("tmp.torrent",t.generate())
Exemple #49
0
def create_torrent_file(file_path_list, params):
    fs = libtorrent.file_storage()

    # filter all non-files
    file_path_list_filtered = []
    for path in file_path_list:
        if not os.path.exists(path):
            raise IOError('Path does not exist: %s' % path)
        elif os.path.isfile(path):
            file_path_list_filtered.append(path)

    # get the directory where these files are in. If there are multiple files, take the common directory they are in
    if len(file_path_list_filtered) == 1:
        base_path = os.path.split(file_path_list_filtered[0])[0]
    else:
        base_path = os.path.abspath(commonprefix(file_path_list_filtered))

    # the base_dir directory is the parent directory of the base_path and is passed to the set_piece_hash method
    base_dir = os.path.split(base_path)[0]

    if len(file_path_list_filtered) == 1:
        filename = os.path.basename(file_path_list_filtered[0])
        fs.add_file(filename, os.path.getsize(file_path_list_filtered[0]))
    else:
        for full_file_path in file_path_list_filtered:
            filename = os.path.join(base_path[len(base_dir) + 1:], full_file_path[len(base_dir):])[1:]
            fs.add_file(filename, os.path.getsize(full_file_path))

    if params.get('piece length'):
        piece_size = params['piece length']
    else:
        piece_size = 0

    flags = libtorrent.create_torrent_flags_t.optimize

    # This flag doesn't exist anymore in libtorrent V1.1.0
    if hasattr(libtorrent.create_torrent_flags_t, 'calculate_file_hashes'):
        flags |= libtorrent.create_torrent_flags_t.calculate_file_hashes

    torrent = libtorrent.create_torrent(fs, piece_size=piece_size, flags=flags)
    if params.get('comment'):
        torrent.set_comment(params['comment'])
    if params.get('created by'):
        torrent.set_creator(params['created by'])
    # main tracker
    if params.get('announce'):
        torrent.add_tracker(params['announce'])
    # tracker list
    if params.get('announce-list'):
        tier = 1
        for tracker in params['announce-list']:
            torrent.add_tracker(tracker, tier=tier)
            tier += 1
    # DHT nodes
    # http://www.bittorrent.org/beps/bep_0005.html
    if params.get('nodes'):
        for node in params['nodes']:
            torrent.add_node(*node)
    # HTTP seeding
    # http://www.bittorrent.org/beps/bep_0017.html
    if params.get('httpseeds'):
        torrent.add_http_seed(params['httpseeds'])

    # Web seeding
    # http://www.bittorrent.org/beps/bep_0019.html
    if len(file_path_list) == 1:
        if params.get('urllist', False):
            torrent.add_url_seed(params['urllist'])

    # read the files and calculate the hashes
    if len(file_path_list) == 1:
        libtorrent.set_piece_hashes(torrent, base_path)
    else:
        libtorrent.set_piece_hashes(torrent, base_dir)

    t1 = torrent.generate()
    torrent = libtorrent.bencode(t1)

    postfix = u'.torrent'

    if params.get('name'):
        if not isinstance(params['name'], unicode):
            params['name'] = unicode(params['name'], 'utf-8')
        torrent_file_name = os.path.join(base_path, params['name'] + postfix)
    else:
        torrent_file_name = os.path.join(base_path, unicode(t1['info']['name'], 'utf-8') + postfix)
    with open(torrent_file_name, 'wb') as f:
        f.write(torrent)

    return {'success': True,
            'base_path': base_path,
            'base_dir': base_dir,
            'torrent_file_path': torrent_file_name}
Exemple #50
0
import libtorrent as lt
import time


piece_size = 256 * 1024
creator_str = "peerbay.p2p"
thetracker = "bttracker.debian.org"
theurlseed = "your desired url seed"

fs = lt.file_storage()
lt.add_files(fs, "demoCA")
fs.num_files()

t = lt.create_torrent(fs, piece_size)
t.add_tracker(thetracker)
lt.set_piece_hashes(t, ".")
t.set_root_cert("newkey.pem")
t.set_creator(creator_str)
#~ t.add_url_seed(theurlseed)

f = open("dom.torrent", "wb")
f.write(lt.bencode(t.generate()))
f.close()
ses = lt.session()
ses.listen_on(6881, 6891)


e = lt.bdecode(open("dom.torrent", 'rb').read())
info = lt.torrent_info(e)

params = { "save_path": './', \
Exemple #51
0
#!/usr/bin/python

import sys
import os

file = sys.argv[1]
output = sys.argv[2]

import libtorrent as lt

fs = lt.file_storage()
lt.add_files( fs, file )

ct = lt.create_torrent( fs, 5000 )

#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)

ct.set_creator("iftd")

lt.set_piece_hashes( ct, os.path.dirname(file))

bt_str = lt.bencode( ct.generate() )

fd = open(output, "wb" )
fd.write( bt_str )
fd.close() 
Exemple #52
0
def create_torrent_file(file_path_list, params, callback=None):
    base_dir = None

    num_files = len([file for file in file_path_list if os.path.isfile(file)])
    if num_files > 1:
        # outpaths should start with a common prefix, this prefix is the swarmname of the torrent
        # if srcpaths contain c:\a\1, c:\a\2 -> basepath should be c:\ and basedir a and outpaths should be a\1 and a\2
        # if srcpaths contain c:\a\1, c:\a\2, c:\a\b\1, c:\a\b\2 -> basepath
        # should be c:\ and outpaths should be a\1, a\2, a\b\1 and a\b\2
        base_path = os.path.abspath(os.path.commonprefix(file_path_list))
        base_path, base_dir = os.path.split(base_path)

    else:
        file_path_list = [file for file in file_path_list if os.path.isfile(file)]

        src_path = file_path_list[0]
        base_path, _ = os.path.split(src_path)

    fs = libtorrent.file_storage()
    for f in file_path_list:
        libtorrent.add_files(fs, f)

    if params.get('piece length'):
        piece_size = params['piece length']
    else:
        piece_size = 0

    flags = libtorrent.create_torrent_flags_t.optimize | libtorrent.create_torrent_flags_t.calculate_file_hashes
    torrent = libtorrent.create_torrent(fs, piece_size=piece_size, flags=flags)
    if params.get('comment'):
        torrent.set_comment(params['comment'])
    if params.get('created by'):
        torrent.set_creator(params['created by'])
    # main tracker
    if params.get('announce'):
        torrent.add_tracker(params['announce'])
    # tracker list
    if params.get('announce-list'):
        tier = 1
        for tracker in params['announce-list']:
            torrent.add_tracker(params['announce'], tier=tier)
            tier += 1
    # DHT nodes
    if params.get('nodes'):
        for node in params['nodes']:
            torrent.add_node(node)
    # HTTP seeding
    if params.get('httpseeds'):
        torrent.add_http_seed(params['httpseeds'])

    if num_files == 1:
        if params.get('urllist', False):
            torrent.add_url_seed(params['urllist'])

    # read the files and calculate the hashes
    libtorrent.set_piece_hashes(torrent, base_path)

    t1 = torrent.generate()
    torrent = libtorrent.bencode(t1)

    postfix = '.torrent'

    torrent_file_name = os.path.join(base_path, t1['info']['name'] + postfix)
    with open(torrent_file_name, 'wb') as f:
        f.write(torrent)

    if callback is not None:
        result = {'success': True,
                  'base_path': base_path,
                  'base_dir': base_dir,
                  'torrent_file_path': torrent_file_name}
        callback(result)
Exemple #53
0
#!/bin/python

import sys
import os
import libtorrent

if len(sys.argv) < 3:
	print 'usage make_torrent.py file tracker-url'
	sys.exit(1)

input = os.path.abspath(sys.argv[1])

fs = libtorrent.file_storage()
libtorrent.add_files(fs, input)
if fs.num_files() == 0:
	print 'no files added'
	sys.exit(1)

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

t.add_tracker(sys.argv[2])
t.set_creator('libtorrent %s' % libtorrent.version)

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

print libtorrent.bencode(t.generate())
Exemple #54
0
                             'downloading metadata',
                             'downloading',
                             'finished',
                             'seeding',
                             'allocating',
                             'checking fastresume']

progress_string = '{0:3.2f}% complete (down: {1:.1f}% kb/s up:'\
                               ' {2:.1f}% kb/s peers: {3}) {4}\r'


tfile_path = './test.torrent'
files = libtorrent.file_storage()
libtorrent.add_files(files, './dummy_torrent')
torrent_file = libtorrent.create_torrent(files)
libtorrent.set_piece_hashes(torrent_file, ".")
torrent_file.set_comment('Test torrent1')
torrent_file.set_creator('bpurgaso')
# Needs to be changed to correct tracker
torrent_file.add_tracker('udp://babylon.att.net:6969/announce')

try:
    os.remove(tfile_path)
except OSError:
    pass
with open(tfile_path, 'wb') as f:
    f.write(libtorrent.bencode(torrent_file.generate()))


session = libtorrent.session()
session.listen_on(6881, 6891)
Exemple #55
0
    for f in files:
        # skip files starting with .
        if f[0] == '.':
            continue

        # skip thumbs.db on windows
        if f == 'Thumbs.db':
            continue

        fname = os.path.join(root[len(parent_input)+1:], f)
        size = os.path.getsize(os.path.join(parent_input, fname))
        print('%10d kiB  %s' % (size / 1024, fname))
        fs.add_file(fname, size)

if fs.num_files() == 0:
    print('no files added')
    sys.exit(1)

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

t.add_tracker(sys.argv[2])
t.set_creator('libtorrent %s' % libtorrent.__version__)

libtorrent.set_piece_hashes(t, parent_input, lambda x: sys.stdout.write('.'))
sys.stdout.write('\n')

f = open('out.torrent', 'wb+')
f.write(libtorrent.bencode(t.generate()))
f.close()
Exemple #56
0
    def generate_torrent(self, shard_directory, piece_size=0,
                         pad_size_limit=4 * 1024 * 1024, flags=1,
                         comment='Storj - Be the Cloud.', creator='Storj',
                         private=False, torrent_name='storj.torrent',
                         save_path=".", verbose=False):
        """Creates a torrent with specified files.

        A torrent is created by determining the files that will be included,
        defining the torrent properties (such as DHT nodes), reading through
        all the torrent files, SHA-1ing all the data, setting the piece hashes
        and bencoding the torrent into a file.

        :param piece_size: The size of each piece in bytes. It must be a
                           multiple of 16 kiB. If a piece size of 0 is
                           specified, a piece_size will be calculated such that
                           the torrent file is roughly 40 kB.
        :type piece_size: int
        :param shard_directory: The directory containing the shards you wish to
                                include in the torrent.
        :type shard_directory: str
        :param pad_size_limit: If specified (other than -1), any file larger
                               than the specified number of bytes will be
                               preceeded by a pad file to align it with the
                               start of a peice. The pad_file_limit is ignored
                               unless the optimize flag is passed. Typically it
                               doesn't make sense to set this any lower than
                               4kiB.
        :type pad_size_limit: int
        :param flags: Specifies options for the torrent creation.
        :type flags: int
        :param comment: Comment to be associated with torrent.
        :type comment: str
        :param creator: Creator to be associated with torrent.
        :type creator: str
        :param private: Whether torrent should be private or not. Should be
                        false for DHT.
        :type private: bool
        :param torrent_name: The filename for your torrent. Will default to
        save_path location unless explicitly stated.
        :type torrent_name: str
        :param save_path: Save location for file.
        :type save_path: str
        :param verbose: Indicate if actions should be made verbosely or not.
        :type verbose: bool
        """

        if piece_size % 16384 is not 0:
            raise StorjTorrentError(
                'Torrent piece size must be 0 or a multiple of 16 kiB.')

        storage = lt.file_storage()
        directory = os.path.abspath(shard_directory)
        parent_directory = os.path.split(directory)[0]

        for root, dirs, files in os.walk(directory):
            if os.path.split(root)[1][0] == '.':
                continue
            for f in files:
                if f[0] in ['.', 'Thumbs.db']:
                    continue
                filename = os.path.join(root[len(parent_directory) + 1:], f)
                size = os.path.getsize(
                    os.path.join(parent_directory, filename))
                if verbose:
                    print '%10d kiB  %s' % (size / 1024, filename)
                storage.add_file(filename, size)

        if storage.num_files() == 0:
            raise StorjTorrentError(
                'No files were loaded from the specified directory.')

        torrent = lt.create_torrent(storage, piece_size, pad_size_limit, flags)
        torrent.set_comment(comment)
        torrent.set_creator(creator)
        torrent.set_priv(private)

        if verbose:
            sys.stderr.write('Setting piece hashes.')
            lt.set_piece_hashes(
                torrent, parent_directory, lambda x: sys.stderr.write('.'))
            sys.stderr.write('done!\n')
        else:
            lt.set_piece_hashes(torrent, parent_directory)

        """ Check the save path, if it is specified absolutely
        then parse it."""
        if os.path.isabs(save_path):
            torrent_name = os.path.join(os.path.abspath(save_path),
                                        torrent_name)
        else:
            torrent_name = os.path.join(save_path, torrent_name)

        try:
            open(torrent_name, 'w')
        except IOError:
            raise StorjTorrentError(
                'Bad torrent save path or name, unable to save.')

        with open(torrent_name, 'wb+') as torrent_file:
            torrent_file.write(lt.bencode(torrent.generate()))