Exemplo n.º 1
0
    def __archive(self):
        target = self.data['target']
        targets = self.data['targets[]']
        name = self.data['name']
        type = self.data['type']
        source_volume = self.get_volume(target)
        abs_path = source_volume._find_path(target)
        type_map = {
            "application/x-tar": 'tar',
            "application/zip": 'zip',
        }
        added = []
        zipfile = None
        if abs_path:
            zipfile = os.path.join(abs_path,
                                   "{}.{}".format(name, type_map[type]))
            files = []
            for trg in targets:
                orig_abs_path = source_volume._find_path(trg)
                files.append(orig_abs_path)

            patoolib.create_archive(zipfile, files)
        for node in source_volume.get_tree(target):
            if source_volume._find_path(node['hash']) == zipfile:
                added.append(node)
        self.response.update({"added": added})
Exemplo n.º 2
0
    def __archive(self):
        target = self.data['target']
        targets = self.data['targets[]']
        name = self.data['name']
        type = self.data['type']
        source_volume = self.get_volume(target)
        abs_path = source_volume._find_path(target)
        type_map = {
            "application/x-tar": 'tar',
            "application/zip": 'zip',
        }
        if abs_path:
            zipfile = os.path.join(abs_path, "{}.{}".format(name, type_map[type]))
            files = []
            added = []
            for trg in targets:
                orig_abs_path = source_volume._find_path(trg)
                files.append(orig_abs_path)

            patoolib.create_archive(zipfile, files)

        for node in source_volume.get_tree(target):
            if source_volume._find_path(node['hash']) == zipfile:
                added.append(node)
        self.response.update({"added": added})
Exemplo n.º 3
0
def create_archive(folder, archive, update_func=None):
    """Creates an archive file and returns the new path."""
    uncomp_size = files.human_readable_size(files.get_folder_size(folder))

    if update_func:
        update_func(
            "Creating archive {} ({} uncompressed).\n This will almost certainly take a while.".format(
                archive, uncomp_size
            )
        )

    # delete the archive if it already exists,
    # as patoolib will refuse to overwrite an existing archive
    files.delete_file(archive, update_func=update_func)

    logger.debug("Creating archive {}".format(archive))
    # create the archive
    try:
        # this expects files/folders in a list
        patoolib.create_archive(archive, (folder,), verbosity=-1, interactive=False)
    except patoolib.util.PatoolError:
        logger.exception("Unable to create archive")
        raise ExtractionError(archive)

    return archive
Exemplo n.º 4
0
def create_archive(folder: str,
                   archive: str,
                   update_func: Callable = None) -> str:
    """Creates an archive file and returns the new path."""
    uncomp_size = human_readable_size(get_folder_size(folder))

    if update_func:
        update_func(
            "Creating archive {} ({} uncompressed).\n This will almost certainly take a while."
            .format(archive, uncomp_size))

    # delete the archive if it already exists,
    # as patoolib will refuse to overwrite an existing archive
    delete_file(archive, update_func=update_func)

    logger.debug("Creating archive {}".format(archive))
    # create the archive
    try:
        # this expects files/folders in a list
        patoolib.create_archive(
            archive,
            (folder, ),
            verbosity=ARCHIVE_VERBOSITY,
            interactive=ARCHIVE_INTERACTIVE,
        )
    except patoolib.util.PatoolError as e:
        logger.exception("Unable to create archive")
        raise ExtractionError(str(e))

    return archive
Exemplo n.º 5
0
def packImages(files):

    print(currentDirectory)
    print(*files)

    patoolib.create_archive(
        tempDirectory + "test" + "_" + "photo" + "_" +
        dt.now().strftime("%Y%m%d-%H%M%S") + ".rar", (files, currentDirectory))
Exemplo n.º 6
0
def prepair_for_cheating_detection(submissions_dir, project):
    target_dir = project.name
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    target_dir = os.path.abspath(target_dir)
    concat_java_projects(extract_files_to_dirs(submissions_dir), target_dir)
    files = [os.path.join(target_dir, f) for f in os.listdir(target_dir)]
    patoolib.create_archive(target_dir + '.zip', files)
Exemplo n.º 7
0
def add_to_compressed_file(production_folder="production_folder",
                           file_name="production_file"):
    file_name = Path(file_name)
    if file_name.suffix == "":
        file_name = file_name.with_suffix(".rar")

    if os.path.isfile(file_name):
        os.remove(file_name)

    print(f"patoolib.create_archive({file_name}, ({production_folder},))")
    patoolib.create_archive(str(file_name), (production_folder, ))
Exemplo n.º 8
0
Arquivo: archive.py Projeto: Nyrio/cms
    def create_from_dir(from_dir, archive_path):
        """Create a new archive containing all files in from_dir.

        from_dir (string): directory with the files to archive.
        archive_path (string): the new archive's path.

        """
        files = tuple(os.listdir(from_dir))
        cwd = os.getcwd()
        os.chdir(from_dir)
        patoolib.create_archive(archive_path, files, interactive=False)
        os.chdir(cwd)
Exemplo n.º 9
0
    def create_from_dir(from_dir, archive_path):
        """Create a new archive containing all files in from_dir.

        from_dir (string): directory with the files to archive.
        archive_path (string): the new archive's path.

        """
        files = tuple(os.listdir(from_dir))
        cwd = os.getcwd()
        os.chdir(from_dir)
        patoolib.create_archive(archive_path, files, interactive=False)
        os.chdir(cwd)
Exemplo n.º 10
0
def run_create(args):
    """Create an archive from given files."""
    res = 0
    try:
        patoolib.create_archive(args.archive,
                                args.filename,
                                verbosity=args.verbosity,
                                interactive=args.interactive,
                                password=args.password)
    except PatoolError as msg:
        log_error("error creating %s: %s" % (args.archive, msg))
        res = 1
    return res
Exemplo n.º 11
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "trying to download")
                ),
            )
            directory_name = downloaded_file_name
            await event.edit("creating rar archive, please wait..")
            # patoolib.create_archive(directory_name + '.7z',directory_name)
            patoolib.create_archive(
                directory_name + ".rar", (directory_name, Config.TMP_DOWNLOAD_DIRECTORY)
            )
            # patoolib.create_archive("/content/21.yy Avrupa (1).pdf.zip",("/content/21.yy Avrupa (1).pdf","/content/"))
            await borg.send_file(
                event.chat_id,
                directory_name + ".rar",
                caption="rarred By HellBot",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(directory_name + ".rar")
                os.remove(directory_name)
            except:
                pass
            await event.edit("Task Completed")
            await asyncio.sleep(3)
            await event.delete()
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str

        await event.edit(
            "Local file compressed to `{}`".format(directory_name + ".rar")
        )
Exemplo n.º 12
0
def create_archive(source, title, type_in, type_out, temp):
    newfile = os.path.join(source, title + "." + type_out)
    curfile = os.path.join(source, title + "." + type_in)
    bakfile = os.path.join(source, title + '.bak')
    if os.path.exists(newfile):
        if os.path.exists(bakfile):
            os.remove(bakfile)
        os.rename(newfile, bakfile)
    os.chdir(temp)
    patoolib.create_archive(newfile, ['.'])
    os.chdir(source)
    if newfile != curfile:
        os.remove(curfile)
    if os.path.exists(bakfile):
        os.remove(bakfile)
Exemplo n.º 13
0
 def _archive_create (self, archive, srcfiles, program=None, verbosity=0):
     """Create archive from filename."""
     for srcfile in srcfiles:
         self.assertFalse(os.path.isabs(srcfile))
         self.assertTrue(os.path.exists(srcfile))
     # create a temporary directory for creation
     tmpdir = patoolib.util.tmpdir(dir=basedir)
     try:
         archive = os.path.join(tmpdir, archive)
         self.assertTrue(os.path.isabs(archive), "archive path is not absolute: %r" % archive)
         patoolib.create_archive(archive, srcfiles, verbosity=verbosity, program=program)
         self.assertTrue(os.path.isfile(archive))
         self.check_created_archive_with_test(archive)
         self.check_created_archive_with_diff(archive, srcfiles)
     finally:
         shutil.rmtree(tmpdir)
Exemplo n.º 14
0
    def convert(self):
        try:

            files = []
            for r, d, f in os.walk(self.nereye):
                for file in f:
                    if ".jpg" in file:
                        files.append(os.path.join(r,file))
            
            images = tuple(files)
            patoolib.create_archive(f"{self.nereye}/#{self.name}.cbr", images, verbosity=-1)
            for f in files:
                os.remove(f)
            self.clear()
            messagebox.showinfo("Info","Convert Succeed!")
        except:
            self.statusbar["text"] = "There is a problem!"
Exemplo n.º 15
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await edit_or_reply(event, "Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await event.client.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, mone, c_time, "trying to download")),
            )
            directory_name = downloaded_file_name
            await mone.edit("creating rar archive, please wait..")
            patoolib.create_archive(
                directory_name + ".rar",
                (directory_name, Config.TMP_DOWNLOAD_DIRECTORY))
            await event.client.send_file(
                event.chat_id,
                directory_name + ".rar",
                caption="rarred By cat",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(directory_name + ".rar")
                os.remove(directory_name)
            except BaseException:
                pass
            await mone.edit("Task Completed")
            await asyncio.sleep(3)
            await mone.delete()
        except Exception as e:
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str
        await mone.edit(
            "Local file compressed to __{}__".format(directory_name + ".rar"))
Exemplo n.º 16
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Var.TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Var.TEMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:

            downloaded_file_name = await borg.download_media(
                reply_message, Var.TEMP_DOWNLOAD_DIRECTORY)
            directory_name = downloaded_file_name
            await event.edit("creating 7z archive, please wait..")
            # patoolib.create_archive(directory_name + '.7z',directory_name)
            patoolib.create_archive(
                directory_name + ".7z",
                (directory_name, Var.TEMP_DOWNLOAD_DIRECTORY))
            # patoolib.create_archive("/content/21.yy Avrupa (1).pdf.zip",("/content/21.yy Avrupa (1).pdf","/content/"))
            await borg.send_file(
                event.chat_id,
                directory_name + ".7z",
                caption="7z archived By @VirtualUserbot",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(directory_name + ".7z")
                os.remove(directory_name)
            except:
                pass
            await event.edit("Task Completed")
            await asyncio.sleep(3)
            await event.delete()
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str

        await event.edit(
            "Local file compressed to `{}`".format(directory_name + ".7z"))
Exemplo n.º 17
0
 def _archive_create(self, archive, srcfiles, program=None, verbosity=0):
     """Create archive from filename."""
     for srcfile in srcfiles:
         self.assertFalse(os.path.isabs(srcfile))
         self.assertTrue(os.path.exists(srcfile))
     # create a temporary directory for creation
     tmpdir = patoolib.util.tmpdir(dir=basedir)
     try:
         archive = os.path.join(tmpdir, archive)
         self.assertTrue(os.path.isabs(archive),
                         "archive path is not absolute: %r" % archive)
         patoolib.create_archive(archive,
                                 srcfiles,
                                 verbosity=verbosity,
                                 program=program)
         self.assertTrue(os.path.isfile(archive))
         self.check_created_archive_with_test(archive)
         self.check_created_archive_with_diff(archive, srcfiles)
     finally:
         shutil.rmtree(tmpdir)
Exemplo n.º 18
0
    def archive(self, source_path, destination_path, archive_name, extension):

        if not self.check_source(source_path):
            return False

        if not self.check_source(destination_path):
            return False

        if not self._check_program(extension):
            return False

        if os.path.isdir(source_path):
            file_list = glob.glob(source_path)
        else:
            file_list = [source_path]

        self.logger_obj.info("Archiving source files")
        out_file = os.path.join(destination_path, archive_name)
        patoolib.create_archive(archive=out_file, filenames=file_list)

        return True
Exemplo n.º 19
0
    def make_archive(cls, files, ip, ext, filename):
        total_files_count = cls.objects.filter(
            uploaded_at=timezone.now().date(), ip=ip).count()
        if settings.MAX_FILES_PER_DAY <= total_files_count:
            return
        media_temp_dir = os.path.join(settings.MEDIA_ROOT, 'temp_dir')
        archive_dir = os.path.join(media_temp_dir, filename + '.' + ext)
        if not os.path.exists(media_temp_dir):
            os.mkdir(media_temp_dir, )
        temp_files = []
        for f in files:
            with open(os.path.join(media_temp_dir, f.name), 'wb') as file:
                file.write(f.file.getvalue())
                temp_files.append(file.name)
        patoolib.create_archive(archive_dir, temp_files)

        cls.objects.create(
            archive=File(open(archive_dir, 'rb')),
            ip=ip,
        )

        shutil.rmtree(media_temp_dir)
        return
Exemplo n.º 20
0
def create_zip_code_files(output_file, submission_files):
    patoolib.create_archive(output_file, submission_files)
Exemplo n.º 21
0
    if args.project is None:
        print("A project folder is required")
    else:
        if os.path.isdir(args.project):
            print("The project folder already exists")
        else:
            os.mkdir(args.project)
            os.mkdir(args.project + '/orig')
            os.mkdir(args.project + '/edit')
            patoolib.extract_archive(args.input, outdir=args.project + '/orig')
            patoolib.extract_archive(args.input, outdir=args.project + '/edit')

elif args.output is not None:
    #generate Output
    if args.project is None or not os.path.isdir(args.project):
        print("Invalid project folder")
    elif os.path.exists(args.output):
        print("The output file already exists")
    else:
        patoolib.create_archive(args.output, (args.project + '/edit', ))

elif args.edit is True:
    if args.project is None or not os.path.isdir(args.project):
        print("Invalid project folder")
    else:
        editor = mangaeditor.MangaEditor(args.project)
        editor.start()

else:
    parser.print_help()
Exemplo n.º 22
0
def create_zip_code_files(out_path):
    '''
    Zip codes for submission.
    :param out_path: path to store the result file
    '''
    patoolib.create_archive(out_path, code_files)
Exemplo n.º 23
0
    else:
        print(r,
              "                 ",
              "{0:.9f}".format(probability),
              "          ",
              end="\n")
    H -= (probability) * math.log2(probability)

print("\nЕнтропія:", H, " біт")
bytesInfoQuantity = H * OverallLength / 8
print(
    "Кількість інформації в тексті:", "{0:.4f}".format(bytesInfoQuantity),
    "байт, що є більше за розмір файлу" if bytesInfoQuantity > OverallLength
    else "байт, що є менше за розмір файлу"
    if bytesInfoQuantity < OverallLength else "(рівне розміру файлу)")

patoolib.create_archive(filename[:len(filename) - 4] + ".rar", (filename, ))
patoolib.create_archive(filename[:len(filename) - 4] + ".lzma", (filename, ))
patoolib.create_archive(filename[:len(filename) - 4] + ".bz2", (filename, ))
patoolib.create_archive(filename[:len(filename) - 4] + ".gz", (filename, ))
patoolib.create_archive(filename[:len(filename) - 4] + ".zip", (filename, ))

print("Розміри оригінального файлу:")
print(os.path.getsize(filename))
print("Розміри зшакалених файлів:")
print("RAR      ",
      os.path.getsize(filename[:len(filename) - 4] + ".rar"), "\nLZMA     ",
      os.path.getsize(filename[:len(filename) - 4] + ".lzma"), "\nBZ2      ",
      os.path.getsize(filename[:len(filename) - 4] + ".bz2"), "\nGZ       ",
      os.path.getsize(filename[:len(filename) - 4] + ".gz"), "\nZIP       ",
      os.path.getsize(filename[:len(filename) - 4] + ".zip"))
def create_rar(rar_filename, input_file):
    remove_if_exist(rar_filename)
    patoolib.create_archive(rar_filename, (input_file,), verbosity=-1)
Exemplo n.º 25
0
def return_file():
    patoolib.create_archive("test.rar", ("demo.txt", ))
    return send_file("test.rar", attachment_filename='oso.jpg')
Exemplo n.º 26
0
import os
import sys
import patoolib

if len(sys.argv) < 2:
    print('Need argument of base path. quitting.')
    sys.exit(1)

walk_dir = sys.argv[1]

print('Base path: ' + os.path.abspath(walk_dir))

for root, subdirs, files in os.walk(walk_dir):

    if walk_dir != root and files:

        archive = root + '.zip'
        os.chdir(root)

        files[:] = [file for file in files if not file.startswith('.')]

        try:
            if os.path.exists(archive):
                os.remove(archive)
            patoolib.create_archive(archive, files)
        except:
            continue
Exemplo n.º 27
0
def create_cbz(file_path, files):
    patoolib.create_archive(file_path, files, verbosity=1, interactive=False)
from zipfile import ZipFile
import patoolib as p
f = "names.zip"
z = ZipFile(f)
z = z.namelist()
p.extract_archive("names.zip")
t = []
for i in z:
    a = open("names/" + i, 'r')
    b = a.read()
    print(b)
    b = str(b)
    t.append(b)
a.close()
op = open("output.txt", 'w')
for i in t:
    op.write(i)
op.close()
p.create_archive("final_output.zip", ("output.txt", ))
Exemplo n.º 29
0
            img_files.append(os.path.join(r, file))

with open('user_input.json') as inputs:
    json_inputs_object = json.load(inputs)

print("Converting images into cbr format...")
images = tuple(img_files)

comic_name = json_inputs_object.get('f_comic_name')
comic_url = json_inputs_object.get('f_comic_url')
issue_number = json_inputs_object.get('f_issue_number')
delete_image = json_inputs_object.get('f_delete_image')

if comic_url == 'None':
    patoolib.create_archive(f"{path}\\" + f"#{issue_number}.cbr",
                            images,
                            verbosity=-1)
else:
    patoolib.create_archive(f"{path}\\" + "comic.cbr", images, verbosity=-1)

os.remove('img_urls_file.json')
os.remove('user_input.json')

if delete_image == 'yes':
    print("Deleting the images...")
    for f in img_files:
        os.remove(f)
else:
    print(
        f"Creating folder '{issue_number}' inside the pages folder...\nMoving downloaded images to newly created folder '{issue_number}'..."
    )
Exemplo n.º 30
0
 def create(self, archive_name, archive_root):
     create_archive(archive_name, [archive_root])
Exemplo n.º 31
0
def zipConvert():
    # (namebof file.extension to convert, (actual file that need to be converted, 2nd file to be converted) )
    # 1st and 2nd file will be converted into zip
    patoolib.create_archive("test.zip", ("instruction.txt", "ttp.txt"))
    print("File zipped successfully....")
Exemplo n.º 32
0
if __name__ == '__main__':
    args = parse_args()
    if args.verbose > 0:
        if args.test:
            print( bcolors.OKBLUE + ' ===> ' + 'running as ' + \
                    bcolors.WARNING + 'test' + bcolors.ENDC)
    if args.verbose > 2:
        print( bcolors.OKBLUE + ' ===> ' + bcolors.OKGREEN + \
                ' retrieving direcotries within: ' + \
                bcolors.ENDC  + ''.join(args.root_dir))
    dirs = os.listdir(args.root_dir)
    if args.verbose > 2:
        print(bcolors.OKBLUE + ' ===> ' + bcolors.OKGREEN + \
                'Directories found:\n\t' + bcolors.ENDC + \
                '\n\t'.join(dirs))
    for d in dirs:
        if args.verbose > 0:
            print(bcolors.OKBLUE + ' ====> ' + bcolors.ENDC + \
                    'creating file %s' % d)
        archive_out = os.path.join(args.output_dir, d) + '.' + args.zip_format
        if args.verbose > 1:
            print(bcolors.OKBLUE + ' ====>  ' + bcolors.ENDC + \
                    '  Creating archive %s' % archive_out)
        outpath = os.path.join(args.root_dir, d)
        if not args.test:
            if args.verbose > 0:
                print(bcolors.OKGREEN + ' ====> ' + bcolors.ENDC + archive_out)
                print(bcolors.OKGREEN + ' ====> ' + bcolors.ENDC + outpath)
            patoolib.create_archive("%s" % archive_out, \
                    (outpath + '/'))
Exemplo n.º 33
0
 def archive_file(self):
     import patoolib
     patoolib.create_archive(
         os.path.join(DOWNLOADS_DIR, '%s.arj' % self.arj_file_name),
         (os.path.join(DOWNLOADS_DIR, '%s.dbf' % self.file_name), ))
     return '%s.arj' % self.arj_file_name