filesystem_files.py 8.75 KB
"""Path mapping, checked file descriptors and media decoding for the file source."""
from contextlib import contextmanager
from hashlib import sha1
from io import BytesIO
import math
import os
from pathlib import Path
import stat
import tempfile

import cv2
from PIL import Image


IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'}
VIDEO_FORMATS = {'.mp4', '.mov'}
IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaoriginals',
               '@eadir', '#recycle', '$recycle.bin', 'system volume information'}
IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'}


def below(path, root):
    return path.startswith(root.rstrip(os.sep) + os.sep)


def linked(info):
    return stat.S_ISLNK(info.st_mode) or bool(
        getattr(info, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT)


def reject_link(path):
    info = os.lstat(path)
    if linked(info):
        raise OSError('Symbolic link or reparse point')
    return info


class FilePaths:
    def __init__(self, roots, unc_prefixes):
        self.roots = self._prefixes(roots)
        self.unc_prefixes = self._prefixes(unc_prefixes)
        if any(not isinstance(marker, str) or not marker.strip() for marker in self.roots.values()):
            raise ValueError('Each scan root requires a marker name')
        destinations = []
        for prefix in self.unc_prefixes.values():
            if not isinstance(prefix, str) or not prefix.startswith('\\\\'):
                raise ValueError('UNC prefix must begin with two backslashes')
            parts = prefix[2:].rstrip('\\').split('\\')
            if len(parts) < 2 or any(part in {'', '.', '..'} or '/' in part for part in parts):
                raise ValueError('Invalid UNC prefix')
            destinations.append(tuple(part.casefold() for part in parts))
        if any(a[:len(b)] == b for i, a in enumerate(destinations)
               for j, b in enumerate(destinations) if i != j):
            raise ValueError('Overlapping UNC destinations')
        for root in self.roots:
            if not any(root == prefix or below(root, prefix) for prefix in self.unc_prefixes):
                raise ValueError(f'No UNC mapping for scan root {root}')

    @staticmethod
    def _prefixes(values):
        if not isinstance(values, dict) or not values:
            raise ValueError('Expected a nonempty path mapping')
        paths = {}
        for prefix, value in values.items():
            if not os.path.isabs(prefix) or prefix != os.path.normpath(prefix):
                raise ValueError(f'Expected a canonical absolute prefix: {prefix}')
            if any(os.path.normcase(prefix) == os.path.normcase(p)
                   or below(os.path.normcase(prefix), os.path.normcase(p))
                   or below(os.path.normcase(p), os.path.normcase(prefix)) for p in paths):
                raise ValueError(f'Overlapping path prefix: {prefix}')
            paths[prefix] = value
        return paths

    def root_for(self, path):
        return next((root for root in self.roots if below(path, root)), None)

    def unc(self, path):
        for prefix, unc in self.unc_prefixes.items():
            if below(path, prefix):
                suffix = path[len(prefix.rstrip(os.sep)) + 1:].replace(os.sep, '\\')
                return unc.rstrip('\\') + '\\' + suffix
        raise ValueError(f'Path has no UNC mapping: {path}')


def file_metadata(info):
    return info.st_mtime, info.st_size


def fingerprint(info):
    return info.st_dev, info.st_ino, info.st_mode, info.st_mtime_ns, info.st_size


def check_open_file(src, path, root, initial):
    current = os.fstat(src.fileno())
    real_root = os.path.realpath(root)
    if (not stat.S_ISREG(current.st_mode) or fingerprint(current) != fingerprint(initial)
            or os.path.normcase(real_root) != os.path.normcase(root)
            or not below(os.path.normcase(os.path.realpath(path)), os.path.normcase(real_root))
            or fingerprint(reject_link(path)) != fingerprint(current)):
        raise OSError('File changed or escaped scan root')


@contextmanager
def open_checked(path, root, expected=None):
    """On POSIX walk from the anchor with no-follow directory and file opens."""
    if not below(path, root) or path != os.path.normpath(path):
        raise OSError('Path outside scan root')
    flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_BINARY', 0)
    if os.open in os.supports_dir_fd and getattr(os, 'O_NOFOLLOW', 0):
        parts = Path(path).parts
        dir_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
        directory = os.open(parts[0], dir_flags)
        try:
            for part in parts[1:-1]:
                child = os.open(part, dir_flags, dir_fd=directory)
                os.close(directory)
                directory = child
            fd = os.open(parts[-1], flags | os.O_NONBLOCK, dir_fd=directory)
        finally:
            os.close(directory)
    else:
        for parent in Path(path).parents:
            reject_link(parent)
        reject_link(path)
        fd = os.open(path, flags)
    with os.fdopen(fd, 'rb') as src:
        initial = os.fstat(src.fileno())
        check_open_file(src, path, root, initial)
        if expected is not None and file_metadata(initial) != expected:
            raise OSError('File changed since enumeration or indexing')
        yield src
        check_open_file(src, path, root, initial)


def marker_identity(root, name):
    info = reject_link(root)
    if not stat.S_ISDIR(info.st_mode):
        raise OSError('Root is not a directory')
    with open_checked(os.path.join(root, '.image-search-root'), root) as src:
        marker = src.read(4097).decode('utf-8').strip()
    if marker != name:
        raise OSError('Root marker mismatch')
    current = reject_link(root)
    if not os.path.samestat(info, current):
        raise OSError('Root changed during marker check')
    return info.st_dev, info.st_ino


@contextmanager
def staged_video(src, suffix, digest=None):
    """OpenCV 4.8 needs a seekable pathname. Stage bytes from the checked fd."""
    with tempfile.TemporaryDirectory(prefix='image-search-video-') as directory:
        path = os.path.join(directory, 'video' + suffix)
        with open(path, 'wb') as dst:
            while chunk := src.read(1024 * 1024):
                if digest is not None:
                    digest.update(chunk)
                dst.write(chunk)
        yield path


@contextmanager
def video_capture(path):
    cap = cv2.VideoCapture(path)
    try:
        if not cap.isOpened():
            raise ValueError('Cannot decode video')
        yield cap
    finally:
        cap.release()


def frame_times(duration, cap):
    if not math.isfinite(duration) or duration <= 0 or cap <= 0:
        raise ValueError('Invalid video duration or frame cap')
    step = max(1.5, duration / cap)
    return [round(i * step * 1000) for i in range(min(cap, math.ceil(duration / step)))]


def read_frame(capture, frame_ms):
    if not capture.set(cv2.CAP_PROP_POS_MSEC, frame_ms):
        raise ValueError('Cannot seek video frame')
    ok, frame = capture.read()
    if not ok:
        # The time seek can round to EOF for a sample within the last frame's display interval.
        fps = capture.get(cv2.CAP_PROP_FPS)
        count = capture.get(cv2.CAP_PROP_FRAME_COUNT)
        if (math.isfinite(fps) and math.isfinite(count) and fps > 0 and count >= 1
                and (count - 1) / fps <= frame_ms / 1000 < count / fps
                and capture.set(cv2.CAP_PROP_POS_FRAMES, count - 1)):
            ok, frame = capture.read()
    if not ok:
        raise ValueError('Cannot decode video frame')
    return Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))


def extract_video(path, frame_cap, extractor):
    with video_capture(path) as capture:
        fps = capture.get(cv2.CAP_PROP_FPS)
        if not math.isfinite(fps) or fps <= 0:
            raise ValueError('Invalid video FPS')
        duration = capture.get(cv2.CAP_PROP_FRAME_COUNT) / fps
        return [(when, extractor.extract_all_features(read_frame(capture, when)))
                for when in frame_times(duration, frame_cap)]


def read_image_bytes(path, root, expected):
    with open_checked(path, root, expected) as src:
        content = src.read()
    return content, sha1(content).hexdigest()


def jpeg_thumbnail(path, root, expected, frame_ms):
    output = BytesIO()
    with open_checked(path, root, expected) as src:
        if frame_ms == -1:
            with Image.open(src) as decoded:
                decoded.thumbnail((180, 180))
                image = decoded.convert('RGB')
        else:
            with staged_video(src, Path(path).suffix) as staged, video_capture(staged) as cap:
                image = read_frame(cap, frame_ms)
                image.thumbnail((180, 180))
        image.save(output, 'JPEG')
    return output.getvalue()