def is_updated_version(db_file_name, ftp_file_name):
    db_version = PurePath(db_file_name).stem.split('_')[1].split(' ')[0]
    ftp_version = PurePath(ftp_file_name).stem.split('_')[1].split(' ')[0]
    # Numbers always newer than letters
    if ftp_version.isdigit() and db_version.isalpha():
        return True
    elif ftp_version.isalpha() and db_version.isdigit():
        return False
    if ftp_version.isdigit():
        return int(ftp_version) > int(db_version)
    return ftp_version.lower() > db_version.lower()
Exemple #2
0
    def listMoving(self, targetFiles: list, listData: list) -> list:
        tempList = []
        toMovingList = []

        for item in listData:
            path = os.path.normpath(item['path'])
            ext = item['extension']
            if not ext:
                continue

            filesNames = [PurePath(x).name for x in self.scandir(path)]

            for itemTarget in targetFiles:
                nameTarget = PurePath(itemTarget).stem
                extTarget = PurePath(itemTarget).suffix
                fullName = PurePath(itemTarget).name

                if extTarget.lower() in ext:
                    size = os.path.getsize(itemTarget)
                    self.totalSize += size

                    if fullName in filesNames or fullName in tempList:
                        if not shutil._samefile(itemTarget,
                                                os.path.join(path, fullName)):
                            fullName = self.rename_files(
                                fullName, filesNames, tempList)

                    tempList.append(fullName)
                    toMovingList.append(
                        (itemTarget, os.path.join(path, fullName),
                         PurePath(itemTarget).name, size))

        return sorted(toMovingList, key=lambda x: x[3])
 def validate_file(self, value):
     ext = PurePath(value.name).suffix
     if ext.lower() not in [".pdf", ".jpg", ".jpeg", ".png", ".docx"]:
         raise serializers.ValidationError(
             detail="Format de fichier incorrect, seuls .PDF, .JPG, .PNG et .DOCX sont autorisés",
             code="formulaire_format_incorrect",
         )
     return value
Exemple #4
0
 def getImages(self, dir):
     print("Scanning " + dir)
     allImages = []
     p = Path(dir)
     for file in p.iterdir():
         b = PurePath(file).stem
         e = PurePath(file).suffix
         if e.lower() not in image_extensions:
             continue
         allImages += [file]
     return allImages
    def validate_formulaire(self, value):
        name = value.name
        ext = PurePath(name).suffix

        if ext.lower() not in [".pdf", ".jpg", ".jpeg", ".png"]:
            raise serializers.ValidationError(
                detail=
                "Format de fichier incorrect, seuls jpg, pdf, et png sont autorisés",
                code="formulaire_format_incorrect",
            )

        return value
def process_frame_segments(args, segments, width, height):
    """Post-process frame segments to set frame images, etc."""
    fn = "process_frame_segments"
    globals.log.info("Processing frames...")
    frame_segments = [s for s in segments if isinstance(s, FrameSegment)]
    n = len(frame_segments)
    globals.log.debug("{fn}(): num frames = {n}".format(fn=fn, n=n))
    progress = ProgressBar(max_value=n,
                           quiet=args.quiet or args.debug or n == 0)
    progress.update(0)
    for i, f in enumerate(frame_segments):
        try:
            globals.log.debug(
                "{fn}(): frame (before) = {b}".format(fn=fn, b=f))
            # Frame segments that use a frame from the previous segment.
            if (f.input_file == "^"):
                if (f.segment_number > 0):
                    prev = segments[f.segment_number - 1]
                    globals.log.debug(
                        "{fn}(): prev = {p}".format(fn=fn, p=prev))
                    prev.generate_temp_file(args.output, width=width,
                                            height=height)
                    f.use_frame(
                        prev.generate_frame(f.frame_number, args.output,
                                            width=width, height=height))
                else:
                    globals.log.error(
                        "frame segment {s} is attempting to use the last "
                        "frame of a non-existent previous "
                        "segment".format(s=f.segment_number))
                    sys.exit(1)
            # Frame segments whose frame comes from a PDF file.
            else:
                suffix = PurePath(f.input_file).suffix
                if (suffix.lower() == ".pdf"):
                    f.use_frame(f.generate_temp_file(args.output, width=width,
                                            height=height))
                else:
                    globals.log.error(
                        'unexpected input file type "{s}" for frame segment '
                        "{f}".format(s=suffix, f=f.segment_number))
                    sys.exit(1)
            progress.update(i)
            globals.log.debug("{fn}(): frame (after) = ""{a}".format(fn=fn, a=f))
        except SegmentError as e:
            progress.finish()
            globals.log.exception(e)
            sys.exit(1)
    else:
        progress.finish()
Exemple #7
0
def filepath(instance, filename):
    """Return a "slugified" filename using the instance name.

    The extension of the original filename is preserved.

    :param models.Equipment instance: Equipment instance
    :param str filename: Name of the file

    :return: Slugified filename from instance name and file extension.
    :rtype: str
    """
    # Keep the extension of the uploaded file
    extension = PurePath(filename).suffix

    name = django.utils.text.slugify(instance.name)  # Safer

    path = "{0}{1}".format(name, extension.lower())

    return path
Exemple #8
0
def secure_path(filename: str,
                name: str = None,
                uuid_name: bool = True) -> PurePath:
    """
    This is a helper used by :py:func:`flask_googlestorage.Bucket.save` to get a secured path. with
    the file extension in lower case.

    :param filename: The original filename.

    :param name: A name preferred over the original filename which could contain nested folders.

    :param uuid_name: If set to ``True`` a UUID name is preferred over the original filename.

    :returns: A secured filename with the extension in lower case
    """
    ext = PurePath(filename).suffix

    if name:
        path = PurePath(name)
        parent, stem, suffix = path.parent, path.stem, path.suffix
        if stem.endswith("."):
            stem = stem[:-1]

        if suffix:
            ext = suffix

        secure_parent = PurePath(*(secure_filename(part)
                                   for part in parent.parts if part != ".."))
        secure_name = secure_filename(path.name)
    else:
        secure_parent = ""
        secure_name = str(uuid4()) if uuid_name else secure_filename(filename)

    if not secure_name:
        secure_name = str(uuid4())

    return secure_parent / PurePath(secure_name).with_suffix(ext.lower())