class GenerateThumbnails(WorkerInPublishPullPipeline): def __init__(self) -> None: self.random_file_name = GenerateRandomFileName() super().__init__("Thumbnails") def cache_full_size_file_from_camera(self, rpd_file: RPDFile) -> bool: """ Get the file from the camera chunk by chunk and cache it. :return: True if operation succeeded, False otherwise """ if rpd_file.file_type == FileType.photo: cache_dir = self.photo_cache_dir else: cache_dir = self.video_cache_dir cache_full_file_name = os.path.join( cache_dir, self.random_file_name.name(extension=rpd_file.extension)) try: self.camera.save_file_by_chunks( dir_name=rpd_file.path, file_name=rpd_file.name, size=rpd_file.size, dest_full_filename=cache_full_file_name, progress_callback=None, check_for_command=self.check_for_controller_directive, return_file_bytes=False, ) except CameraProblemEx as e: # TODO report error return False else: rpd_file.cache_full_file_name = cache_full_file_name return True def cache_file_chunk_from_camera(self, rpd_file: RPDFile, offset: int) -> bool: if rpd_file.file_type == FileType.photo: cache_dir = self.photo_cache_dir else: cache_dir = self.video_cache_dir cache_full_file_name = os.path.join( cache_dir, self.random_file_name.name(extension=rpd_file.extension)) try: self.camera.save_file_chunk( dir_name=rpd_file.path, file_name=rpd_file.name, chunk_size_in_bytes=min(offset, rpd_file.size), dest_full_filename=cache_full_file_name, ) rpd_file.temp_cache_full_file_chunk = cache_full_file_name return True except CameraProblemEx as e: # TODO problem reporting return False def extract_photo_video_from_camera( self, rpd_file: RPDFile, entire_file_required: bool, full_file_name_to_work_on, using_exiftool: bool, ) -> Tuple[ExtractionTask, str, bool]: """ Extract part of a photo of video to be able to get the orientation and date time metadata, if and only if we know how much of the file is needed to get the thumbnail. Otherwise, download the entire photo or video from the camera to be able to generate the thumbnail and cache it. :param rpd_file: photo or video :param entire_file_required: whether we already know (from scanning) that the entire file is required :param full_file_name_to_work_on: file name and path of the photo or video :param using_exiftool: if all the metadata extraction is done using ExifTool :return: extraction task, full file name, and whether the full file name refers to a temporary file that should be deleted """ task = ExtractionTask.undetermined file_to_work_on_is_temporary = False if rpd_file.is_mtp_device and rpd_file.file_type == FileType.video: entire_file_required = True if not entire_file_required: # For many photos videos, extract a small part of the file and use # that to get the metadata if using_exiftool: offset = thumbnail_offset_exiftool.get(rpd_file.extension) else: offset = thumbnail_offset.get(rpd_file.extension) if offset: if using_exiftool: offset = max( offset, datetime_offset_exiftool.get(rpd_file.extension)) else: offset = max(offset, datetime_offset.get(rpd_file.extension)) if offset and self.cache_file_chunk_from_camera(rpd_file, offset): if rpd_file.file_type == FileType.photo: task = ExtractionTask.load_from_bytes_metadata_from_temp_extract else: task = ExtractionTask.extract_from_file_and_load_metadata file_to_work_on_is_temporary = True full_file_name_to_work_on = rpd_file.temp_cache_full_file_chunk if task == ExtractionTask.undetermined: if self.cache_full_size_file_from_camera(rpd_file): task = ExtractionTask.extract_from_file_and_load_metadata full_file_name_to_work_on = rpd_file.cache_full_file_name else: # Failed to generate thumbnail task = ExtractionTask.bypass return task, full_file_name_to_work_on, file_to_work_on_is_temporary def do_work(self) -> None: try: self.generate_thumbnails() except SystemExit as e: sys.exit(e) except Exception: if hasattr(self, "device_name"): logging.error("Exception generating thumbnails for %s", self.device_name) else: logging.error("Exception generating thumbnails") logging.exception("Traceback:") def generate_thumbnails(self) -> None: self.camera = None arguments = pickle.loads( self.content) # type: GenerateThumbnailsArguments self.device_name = arguments.name logging.info("Generating %s thumbnails for %s", len(arguments.rpd_files), arguments.name) if arguments.log_gphoto2: self.gphoto2_logging = gphoto2_python_logging() self.frontend = self.context.socket(zmq.PUSH) self.frontend.connect("tcp://localhost:{}".format( arguments.frontend_port)) self.prefs = Preferences() # Whether we must use ExifTool to read photo metadata force_exiftool = self.prefs.force_exiftool # If the entire photo or video is required to extract the thumbnail, which is # determined when extracting sample metadata from a photo or video during the # device scan entire_photo_required = arguments.entire_photo_required entire_video_required = arguments.entire_video_required # Access and generate Rapid Photo Downloader thumbnail cache use_thumbnail_cache = self.prefs.use_thumbnail_cache thumbnail_caches = GetThumbnailFromCache( use_thumbnail_cache=use_thumbnail_cache) photo_cache_dir = video_cache_dir = None cache_file_from_camera = force_exiftool rpd_files = arguments.rpd_files # with open('tests/thumbnail_data_medium_no_tiff', 'wb') as f: # pickle.dump(rpd_files, f) # Must sort files by modification time prior to temporal analysis needed to figure out # which thumbnails to prioritize rpd_files = sorted(rpd_files, key=attrgetter("modification_time")) time_span = arguments.proximity_seconds rpd_files2 = [] if rpd_files: gaps, sequences = get_temporal_gaps_and_sequences( rpd_files, time_span) rpd_files2.extend(gaps) indexes = split_indexes(len(sequences)) rpd_files2.extend([sequences[idx] for idx in indexes]) assert len(rpd_files) == len(rpd_files2) rpd_files = rpd_files2 if arguments.camera is not None: self.camera = Camera( model=arguments.camera, port=arguments.port, is_mtp_device=arguments.is_mtp_device, specific_folders=self.prefs.folders_to_scan, ) if not self.camera.camera_initialized: # There is nothing to do here: exit! logging.debug( "Prematurely exiting thumbnail generation due to lack of access to " "camera %s", arguments.camera, ) self.content = pickle.dumps( GenerateThumbnailsResults( scan_id=arguments.scan_id, camera_removed=True, ), pickle.HIGHEST_PROTOCOL, ) self.send_message_to_sink() self.disconnect_logging() self.send_finished_command() sys.exit(0) if not cache_file_from_camera: for rpd_file in rpd_files: if use_exiftool_on_photo( rpd_file.extension, preview_extraction_irrelevant=False): cache_file_from_camera = True break must_make_cache_dirs = (not self.camera.can_fetch_thumbnails or cache_file_from_camera) if (must_make_cache_dirs or arguments.need_video_cache_dir or arguments.need_photo_cache_dir): # If downloading complete copy of the files to # generate previews, then may as well cache them to speed up # the download process self.photo_cache_dir = create_temp_dir( folder=arguments.cache_dirs.photo_cache_dir, prefix=cache_dir_name(self.device_name), ) self.video_cache_dir = create_temp_dir( folder=arguments.cache_dirs.video_cache_dir, prefix=cache_dir_name(self.device_name), ) cache_dirs = CacheDirs(self.photo_cache_dir, self.video_cache_dir) self.content = pickle.dumps( GenerateThumbnailsResults(scan_id=arguments.scan_id, cache_dirs=cache_dirs), pickle.HIGHEST_PROTOCOL, ) self.send_message_to_sink() from_thumb_cache = 0 from_fdo_cache = 0 if self.camera: rescan = RescanCamera(camera=self.camera, prefs=self.prefs) rescan.rescan_camera(rpd_files) rpd_files = rescan.rpd_files if rescan.missing_rpd_files: logging.error( "%s files could not be relocated on %s", len(rescan.missing_rpd_files), self.camera.display_name, ) for rpd_file in rescan.missing_rpd_files: # type: RPDFile self.content = pickle.dumps( GenerateThumbnailsResults(rpd_file=rpd_file, thumbnail_bytes=None), pickle.HIGHEST_PROTOCOL, ) self.send_message_to_sink() for rpd_file in rpd_files: # type: RPDFile # Check to see if the process has received a command self.check_for_controller_directive() exif_buffer = None file_to_work_on_is_temporary = False secondary_full_file_name = "" processing = set() # type: Set[ExtractionProcessing] # Attempt to get thumbnail from Thumbnail Cache # (see cache.py for definitions of various caches) cache_search = thumbnail_caches.get_from_cache(rpd_file) task, thumbnail_bytes, full_file_name_to_work_on, origin = cache_search if task != ExtractionTask.undetermined: if origin == ThumbnailCacheOrigin.thumbnail_cache: from_thumb_cache += 1 else: assert origin == ThumbnailCacheOrigin.fdo_cache logging.debug( "Thumbnail for %s found in large FDO cache", rpd_file.full_file_name, ) from_fdo_cache += 1 processing.add(ExtractionProcessing.resize) if not rpd_file.mdatatime: # Since we're extracting the thumbnail from the FDO cache, # need to grab its metadata too. # Reassign the task task = ExtractionTask.load_file_directly_metadata_from_secondary # It's not being downloaded from a camera, so nothing # special to do except assign the name of the file from which # to extract the metadata secondary_full_file_name = rpd_file.full_file_name logging.debug( "Although thumbnail found in the cache, tasked to extract " "file time recorded in metadata from %s", secondary_full_file_name, ) if task == ExtractionTask.undetermined: # Thumbnail was not found in any cache: extract it if self.camera: # type: Camera if rpd_file.file_type == FileType.photo: if rpd_file.is_heif(): # Load HEIF / HEIC using entire file. # We are assuming that there is no tool to extract a # preview image from an HEIF / HEIC, or the file simply # does not have one to extract. if self.cache_full_size_file_from_camera(rpd_file): task = ExtractionTask.load_heif_and_exif_directly processing.add(ExtractionProcessing.resize) full_file_name_to_work_on = ( rpd_file.cache_full_file_name) # For now, do not orient, as it seems pyheif or libheif does # that automatically. # processing.add(ExtractionProcessing.orient) elif self.camera.can_fetch_thumbnails: task = ExtractionTask.load_from_bytes if rpd_file.is_jpeg_type(): # gPhoto2 knows how to get jpeg thumbnails try: thumbnail_bytes = self.camera.get_thumbnail( rpd_file.path, rpd_file.name) except CameraProblemEx as e: # TODO handle error? thumbnail_bytes = None else: if force_exiftool or use_exiftool_on_photo( rpd_file.extension, preview_extraction_irrelevant=False, ): ( task, full_file_name_to_work_on, file_to_work_on_is_temporary, ) = self.extract_photo_video_from_camera( rpd_file, entire_photo_required, full_file_name_to_work_on, True, ) if (task == ExtractionTask. load_from_bytes_metadata_from_temp_extract ): secondary_full_file_name = ( full_file_name_to_work_on) file_to_work_on_is_temporary = False else: # gPhoto2 does not know how to get RAW thumbnails, # so we do that part ourselves if rpd_file.extension == "crw": # Could cache this file, since reading its # entirety But does anyone download a CRW file # from the camera these days?! bytes_to_read = rpd_file.size else: bytes_to_read = min( rpd_file.size, orientation_offset.get( rpd_file.extension, 500), ) exif_buffer = self.camera.get_exif_extract( rpd_file.path, rpd_file.name, bytes_to_read) try: thumbnail_bytes = self.camera.get_thumbnail( rpd_file.path, rpd_file.name) except CameraProblemEx as e: # TODO report error thumbnail_bytes = None processing.add( ExtractionProcessing.strip_bars_photo) processing.add(ExtractionProcessing.orient) else: # Many (all?) jpegs from phones don't include jpeg previews, # so need to render from the entire jpeg itself. Slow! # For raw, extract merely a part of phone's raw format, and # try to extract the jpeg preview from it (which probably # doesn't exist!). This is fast. if not rpd_file.is_jpeg(): bytes_to_read = thumbnail_offset.get( rpd_file.extension) if bytes_to_read: exif_buffer = self.camera.get_exif_extract( rpd_file.path, rpd_file.name, bytes_to_read) task = ExtractionTask.load_from_exif_buffer processing.add(ExtractionProcessing.orient) if (task == ExtractionTask.undetermined and self.cache_full_size_file_from_camera( rpd_file)): if rpd_file.is_jpeg(): task = ExtractionTask.load_file_and_exif_directly processing.add(ExtractionProcessing.resize) processing.add(ExtractionProcessing.orient) else: task = ExtractionTask.load_from_exif processing.add(ExtractionProcessing.resize) processing.add(ExtractionProcessing.orient) full_file_name_to_work_on = ( rpd_file.cache_full_file_name) else: # Failed to generate thumbnail task = ExtractionTask.bypass else: # video from camera if rpd_file.thm_full_name is not None: # Fortunately, we have a special video thumbnail file # Still need to get metadata time, however. if entire_video_required: offset = rpd_file.size else: offset = datetime_offset.get( rpd_file.extension) # If there is no offset, there is no point trying to # extract the metadata time from part of the video. It's # not ideal, but if this is from a camera on which there # were any other files we can assume we've got a # somewhat accurate date time for it from the # modification time. The only exception is if the video # file is not that big, in which case it's worth reading # in its entirety: if offset is None and rpd_file.size < 4000000: offset = rpd_file.size if rpd_file.mdatatime or not offset: task = ExtractionTask.load_from_bytes elif self.cache_file_chunk_from_camera( rpd_file, offset): task = ( ExtractionTask. load_from_bytes_metadata_from_temp_extract) secondary_full_file_name = ( rpd_file.temp_cache_full_file_chunk) else: # For some reason was unable to download part of the # video file task = ExtractionTask.load_from_bytes try: thumbnail_bytes = self.camera.get_THM_file( rpd_file.thm_full_name) except CameraProblemEx as e: # TODO report error thumbnail_bytes = None processing.add( ExtractionProcessing.strip_bars_video) processing.add(ExtractionProcessing.add_film_strip) else: ( task, full_file_name_to_work_on, file_to_work_on_is_temporary, ) = self.extract_photo_video_from_camera( rpd_file, entire_video_required, full_file_name_to_work_on, False, ) else: # File is not on a camera task = preprocess_thumbnail_from_disk( rpd_file=rpd_file, processing=processing) if task != ExtractionTask.bypass: if rpd_file.thm_full_name is not None: full_file_name_to_work_on = rpd_file.thm_full_name if (task == ExtractionTask. load_file_directly_metadata_from_secondary ): secondary_full_file_name = rpd_file.full_file_name else: full_file_name_to_work_on = rpd_file.full_file_name if task == ExtractionTask.bypass: self.content = pickle.dumps( GenerateThumbnailsResults(rpd_file=rpd_file, thumbnail_bytes=thumbnail_bytes), pickle.HIGHEST_PROTOCOL, ) self.send_message_to_sink() elif task != ExtractionTask.undetermined: # Send data to load balancer, which will send to one of its # workers self.content = pickle.dumps( ThumbnailExtractorArgument( rpd_file=rpd_file, task=task, processing=processing, full_file_name_to_work_on=full_file_name_to_work_on, secondary_full_file_name=secondary_full_file_name, exif_buffer=exif_buffer, thumbnail_bytes=thumbnail_bytes, use_thumbnail_cache=use_thumbnail_cache, file_to_work_on_is_temporary= file_to_work_on_is_temporary, write_fdo_thumbnail=False, send_thumb_to_main=True, force_exiftool=force_exiftool, ), pickle.HIGHEST_PROTOCOL, ) self.frontend.send_multipart([b"data", self.content]) if arguments.camera: self.camera.free_camera() # Delete our temporary cache directories if they are empty if photo_cache_dir is not None: if not os.listdir(self.photo_cache_dir): os.rmdir(self.photo_cache_dir) if video_cache_dir is not None: if not os.listdir(self.video_cache_dir): os.rmdir(self.video_cache_dir) logging.debug("Finished phase 1 of thumbnail generation for %s", self.device_name) if from_thumb_cache: logging.info( "{} of {} thumbnails for {} came from thumbnail cache".format( from_thumb_cache, len(rpd_files), self.device_name)) if from_fdo_cache: logging.info( "{} of {} thumbnails of for {} came from Free Desktop cache". format(from_fdo_cache, len(rpd_files), self.device_name)) self.disconnect_logging() self.send_finished_command() def cleanup_pre_stop(self): if self.camera is not None: self.camera.free_camera()
class Cache: """ Base class with which to write and read cache thumbnails. Create cache if it doesn't exist; checks validity. """ def __init__(self, cache_dir: str, failure_dir: Optional[str]) -> None: """ Create cache if it doesn't exist; checks validity. :param cache_dir: full path of the directory into which thumbnails will be saved / read. :param failure_dir: full path of the directory into which failed thumbnails will be saved / read (thumbnails that could not be generated) """ assert sys.platform.startswith('linux') self.cache_dir = cache_dir self.failure_dir = failure_dir assert self.cache_dir self.valid = self._create_directory(self.cache_dir, "Freedesktop.org thumbnail") if self.valid: self.random_filename = GenerateRandomFileName() self.md5 = MD5Name() if self.failure_dir is not None: self.valid = self._create_directory(self.failure_dir, "thumbnails failure") if not self.valid: self.random_filename = self.fs_encoding = None def _create_directory(self, dir: str, descrtiption: str) -> None: try: if not os.path.exists(dir): os.makedirs(dir, 0o700) logging.debug("Created %s cache at %s", descrtiption, dir) elif not os.path.isdir(dir): os.remove(dir) logging.warning("Removed file %s", dir) os.makedirs(dir, 0o700) logging.debug("Created %s cache at %s", descrtiption, dir) except OSError: logging.error("Failed to create %s cache at %s", descrtiption, dir) return False return True def save_thumbnail(self, full_file_name: str, size: int, modification_time: Union[float, int], generation_failed: bool, thumbnail: QImage, camera_model: str = None, free_desktop_org: bool = True) -> str: """ Save a thumbnail in the thumbnail cache. :param full_file_name: full path of the file (including file name). If the path contains symbolic links, two thumbnails will be saved: the canonical path (without symlinks), and the path as passed. :param size: size of the file in bytes :param modification_time: file modification time, to be turned into a float if it's not already :param generation_failed: True if the thumbnail is meant to signify the application failed to generate the thumbnail. If so, it will be saved as an empty PNG in the application subdirectory in the fail cache directory. :param thumbnail: the thumbnail to be saved. Will not be resized. Will be ignored if generation_failed is True. :param camera_model: optional camera model. If the thumbnail is not from a camera, then should be None. :param free_desktop_org: if True, then image will be convereted to 8bit mode if necessary :return the md5_name of the saved file, else None if operation failed """ if not self.valid: return None # Save to both the real path and the path passed, which may include # symbolic links full_file_name_real_path = os.path.realpath(full_file_name) if full_file_name_real_path != full_file_name: self.save_thumbnail(full_file_name_real_path, size, modification_time, generation_failed, thumbnail, camera_model, free_desktop_org) md5_name, uri = self.md5.md5_hash_name(full_file_name, camera_model) if generation_failed: thumbnail = QImage(QSize(1, 1), QImage.Format_Indexed8) save_dir = self.failure_dir else: save_dir = self.cache_dir path = os.path.join(save_dir, md5_name) thumbnail.setText('Thumb::URI', uri) thumbnail.setText('Thumb::MTime', str(float(modification_time))) thumbnail.setText('Thumb::Size', str(size)) if free_desktop_org and not generation_failed: if thumbnail.depth() != 8: thumbnail = thumbnail.convertToFormat(QImage.Format_Indexed8) temp_path = os.path.join(save_dir, self.random_filename.name(extension='png')) if thumbnail.save(temp_path): os.rename(temp_path, path) os.chmod(path, 0o600) if generation_failed: logging.debug("Wrote {}x{} thumbnail {} for {}".format( thumbnail.width(), thumbnail.height(), path, uri)) return md5_name else: return None def _get_thumbnail(self, path: str, modification_time: float, size: int) -> Optional[bytes]: if os.path.exists(path): png = QImage(path) if not png.isNull(): try: mtime = float(png.text('Thumb::MTime')) thumb_size = int(png.text('Thumb::Size')) except ValueError: return None if mtime == float(modification_time) and thumb_size == size: return png return None def get_thumbnail_md5_name(self, full_file_name: str, camera_model: Optional[str] = None) -> str: """ Returns the md5 name for the photo or video. Does not check if the file exists on the file system in the cache. :param full_file_name: full_file_name: full path of the file (including file name). Will be turned into an absolute path if it is a file system path :param camera_model: optional camera model. If the thumbnail is not from a camera, then should be None. :return: the md5 name """ return self.md5.md5_hash_name(full_file_name=full_file_name, camera_model=camera_model)[0] def get_thumbnail(self, full_file_name: str, modification_time, size: int, camera_model: Optional[str] = None) -> GetThumbnail: """ Attempt to retrieve a thumbnail from the thumbnail cache. :param full_file_name: full path of the file (including file name). Will be turned into an absolute path if it is a file system path :param size: size of the file in bytes :param modification_time: file modification time, to be turned into a float if it's not already :param camera_model: optional camera model. If the thumbnail is not from a camera, then should be None. :return a GetThumbnail tuple of (1) ThumbnailCacheDiskStatus, to indicate whether the thumbnail was found, a failure, or missing (2) the thumbnail as QImage, if found (or None), and (3) the path (including the md5 name), else None, """ if not self.valid: return GetThumbnail(ThumbnailCacheDiskStatus.not_found, None, None) md5_name, uri = self.md5.md5_hash_name(full_file_name=full_file_name, camera_model=camera_model) path = os.path.join(self.cache_dir, md5_name) png = self._get_thumbnail(path, modification_time, size) if png is not None: return GetThumbnail(ThumbnailCacheDiskStatus.found, png, path) if self.failure_dir is not None: path = os.path.join(self.failure_dir, md5_name) png = self._get_thumbnail(path, modification_time, size) if png is not None: return GetThumbnail(ThumbnailCacheDiskStatus.failure, None, None) return GetThumbnail(ThumbnailCacheDiskStatus.not_found, None, None) def modify_existing_thumbnail_and_save_copy( self, existing_cache_thumbnail: str, full_file_name: str, modification_time, size: int, error_on_missing_thumbnail: bool) -> str: """ :param existing_cache_thumbnail: the md5 name of the cache thumbnail, without the path to the cache :param full_file_name: full path of the file (including file name). Will be turned into an absolute path if need be :param size: size of the file in bytes :param modification_time: file modification time, to be turned into a float if it's not already :param error_on_missing_thumbnail: if True, issue error if thumbnail is not located (useful when dealing with FDO 128 cache, but not helpful with FDO 256 cache as not all RAW files have thumbnails large enough) :return: the path of the saved file, else None if operation failed """ existing_cache_thumbnail_full_path = os.path.join( self.cache_dir, existing_cache_thumbnail) if not os.path.isfile(existing_cache_thumbnail_full_path): if error_on_missing_thumbnail: logging.error("No FDO thumbnail to copy for %s", full_file_name) return None thumbnail = QImage(existing_cache_thumbnail_full_path) if not thumbnail.isNull(): return self.save_thumbnail(full_file_name=full_file_name, size=size, modification_time=modification_time, generation_failed=False, thumbnail=thumbnail, camera_model=None, free_desktop_org=False) else: return None def delete_thumbnail(self, full_file_name: str, camera_model: str = None) -> None: """ Delete the thumbnail associated with the file if it exists """ if not self.valid: return None md5_name, uri = self.md5_hash_name(full_file_name, camera_model) path = os.path.join(self.cache_dir, md5_name) if os.path.isfile(path): os.remove(path) else: path = os.path.join(self.failure_dir, md5_name) if os.path.isfile(path): os.remove(path)
class ThumbnailCacheSql: not_found = GetThumbnailPath(ThumbnailCacheDiskStatus.not_found, None, None, None) def __init__(self, create_table_if_not_exists: bool) -> None: self.cache_dir = get_program_cache_directory(create_if_not_exist=True) self.valid = self.cache_dir is not None if not self.valid: return assert self.cache_dir is not None self.cache_dir = os.path.join(self.cache_dir, 'thumbnails') try: if not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir, 0o700) logging.debug("Created thumbnails cache %s", self.cache_dir) elif not os.path.isdir(self.cache_dir): os.remove(self.cache_dir) logging.warning("Removed file %s", self.cache_dir) os.makedirs(self.cache_dir, 0o700) logging.debug("Created thumbnails cache %s", self.cache_dir) except: logging.error( "Failed to create Rapid Photo Downloader Thumbnail Cache at %s", self.cache_dir) self.valid = False self.cache_dir = None self.random_filename = None self.fs_encoding = None else: self.random_filename = GenerateRandomFileName() self.md5 = MD5Name() self.thumb_db = CacheSQL(self.cache_dir, create_table_if_not_exists) def save_thumbnail(self, full_file_name: str, size: int, mtime: float, mdatatime: float, generation_failed: bool, orientation_unknown: bool, thumbnail: Optional[QImage], camera_model: Optional[str] = None) -> Optional[str]: """ Save in the thumbnail cache using jpeg 75% compression. :param full_file_name: full path of the file (including file name). Will be turned into an absolute path if it is a file system path :param size: size of the file in bytes :param mtime: file modification time :param mdatatime: file time recorded in metadata :param generation_failed: True if the thumbnail is meant to signify the application failed to generate the thumbnail. If so, it will be saved as an empty PNG in the application subdirectory in the fail cache directory. :param thumbnail: the thumbnail to be saved. Will not be resized. Will be ignored if generation_failed is True. :param camera_model: optional camera model. If the thumbnail is not from a camera, then should be None. :return the path of the saved file, else None if operation failed """ if not self.valid: return None md5_name, uri = self.md5.md5_hash_name(full_file_name=full_file_name, camera_model=camera_model, extension='jpg') if generation_failed: logging.debug("Marking thumbnail for %s as 'generation failed'", uri) else: logging.debug("Saving thumbnail for %s in RPD thumbnail cache", uri) try: self.thumb_db.add_thumbnail( uri=uri, size=size, mtime=mtime, mdatatime=mdatatime, md5_name=md5_name, orientation_unknown=orientation_unknown, failure=generation_failed) except sqlite3.OperationalError as e: logging.error( "Database error adding thumbnail for %s: %s. Will not retry.", uri, e) return None if generation_failed: return None md5_full_name = os.path.join(self.cache_dir, md5_name) temp_path = os.path.join(self.cache_dir, self.random_filename.name(extension='jpg')) if thumbnail.save(temp_path, format='jpg', quality=75): try: os.rename(temp_path, md5_full_name) os.chmod(md5_full_name, 0o600) except OSError: return None return md5_full_name return None def get_thumbnail_path(self, full_file_name: str, mtime, size: int, camera_model: str = None) -> GetThumbnailPath: """ Attempt to get a thumbnail's path from the thumbnail cache. :param full_file_name: full path of the file (including file name). Will be turned into an absolute path if it is a file system path :param size: size of the file in bytes :param mtime: file modification time, to be turned into a float if it's not already :param camera_model: optional camera model. If the thumbnail is not from a camera, then should be None. :return a GetThumbnailPath tuple of (1) ThumbnailCacheDiskStatus, to indicate whether the thumbnail was found, a failure, or missing, (2) the path (including the md5 name), else None, (3) the file's metadata time, and (4) a bool indicating whether the orientation of the thumbnail is unknown """ if not self.valid: return self.not_found uri = self.md5.get_uri(full_file_name, camera_model) in_cache = self.thumb_db.have_thumbnail(uri, size, mtime) if in_cache is None: return self.not_found if in_cache.failure: return GetThumbnailPath(ThumbnailCacheDiskStatus.failure, None, in_cache.mdatatime, None) path = os.path.join(self.cache_dir, in_cache.md5_name) if not os.path.exists(path): self.thumb_db.delete_thumbnails([in_cache.md5_name]) return self.not_found return GetThumbnailPath(ThumbnailCacheDiskStatus.found, path, in_cache.mdatatime, in_cache.orientation_unknown) def cleanup_cache(self, days: int = 30) -> None: """ Remove all thumbnails that have not been accessed for x days :param how many days to remove from """ time_period = 60 * 60 * 24 * days if self.valid: i = 0 now = time.time() deleted_thumbnails = [] for name in os.listdir(self.cache_dir): thumbnail = os.path.join(self.cache_dir, name) if (os.path.isfile(thumbnail) and os.path.getatime(thumbnail) < now - time_period): os.remove(thumbnail) deleted_thumbnails.append(name) if len(deleted_thumbnails): if self.thumb_db.cache_exists(): self.thumb_db.delete_thumbnails(deleted_thumbnails) logging.debug( 'Deleted {} thumbnail files that had not been accessed for {} or more days' .format(len(deleted_thumbnails), days)) def purge_cache(self) -> None: """ Delete the entire cache of all contents and remove the directory """ if self.valid: if self.cache_dir is not None and os.path.isdir(self.cache_dir): # Delete the sqlite3 database too shutil.rmtree(self.cache_dir) def no_thumbnails(self) -> int: """ :return: how many thumbnails there are in the thumbnail database """ if not self.valid: return 0 return self.thumb_db.no_thumbnails() def cache_size(self) -> int: """ :return: the size of the entire cache (include the database) in bytes """ if not self.valid: return 0 cwd = os.getcwd() os.chdir(self.cache_dir) s = sum( os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)) os.chdir(cwd) return s def db_size(self) -> int: """ :return: the size in bytes of the sql database file """ if not self.valid: return 0 return os.path.getsize(self.thumb_db.db) def optimize(self) -> Tuple[int, int, int]: """ Check for any thumbnails in the db that are not in the file system Check for any thumbnails exist on the file system that are not in the db Vacuum the db :return db rows removed, file system photos removed, db size reduction in bytes """ rows = self.thumb_db.md5_names() rows = {row[0] for row in rows} cwd = os.getcwd() os.chdir(self.cache_dir) to_delete_from_db = {md5 for md5 in rows if not os.path.exists(md5)} if len(to_delete_from_db): self.thumb_db.delete_thumbnails(list(to_delete_from_db)) md5s = {md5 for md5 in os.listdir('.')} - {self.thumb_db.db_fs_name()} to_delete_from_fs = md5s - rows if len(to_delete_from_fs): for md5 in to_delete_from_fs: os.remove(md5) os.chdir(cwd) size = self.db_size() self.thumb_db.vacuum() return len(to_delete_from_db), len( to_delete_from_fs), size - self.db_size()
def do_work(self): self.problems = CopyingProblems() args = pickle.loads(self.content) # type: CopyFilesArguments if args.log_gphoto2: self.gphoto2_logging = gphoto2_python_logging() self.scan_id = args.scan_id self.verify_file = args.verify_file self.camera = None # To workaround a bug in iOS and possibly other devices, check if need to rescan the files # on the device rescan_check = [ rpd_file for rpd_file in args.files if rpd_file.from_camera and not rpd_file.cache_full_file_name ] no_rescan = [ rpd_file for rpd_file in args.files if not rpd_file.from_camera or rpd_file.cache_full_file_name ] if rescan_check: prefs = Preferences() # Initialize camera try: self.camera = Camera(args.device.camera_model, args.device.camera_port, raise_errors=True, specific_folders=prefs.folders_to_scan) except CameraProblemEx as e: self.problems.append( CameraInitializationProblem(gp_code=e.gp_code)) logging.error("Could not initialize camera %s", self.display_name) self.terminate_camera_removed() else: rescan = RescanCamera(camera=self.camera, prefs=prefs) rescan.rescan_camera(rpd_files=rescan_check) rescan_check = rescan.rpd_files if rescan.missing_rpd_files: logging.error("%s files could not be relocated on %s", len(rescan.missing_rpd_files), self.camera.display_name) rescan_check = list( chain(rescan_check, rescan.missing_rpd_files)) rpd_files = list(chain(rescan_check, no_rescan)) random_filename = GenerateRandomFileName() rpd_cache_same_device = defaultdict( lambda: None) # type: Dict[FileType, Optional[bool]] photo_temp_dir, video_temp_dir = create_temp_dirs( args.photo_download_folder, args.video_download_folder) # Notify main process of temp directory names self.content = pickle.dumps( CopyFilesResults(scan_id=args.scan_id, photo_temp_dir=photo_temp_dir or '', video_temp_dir=video_temp_dir or ''), pickle.HIGHEST_PROTOCOL) self.send_message_to_sink() # Sort the files to be copied by modification time # Important to do this with respect to sequence numbers, or else # they'll be downloaded in what looks like a random order rpd_files = sorted(rpd_files, key=attrgetter('modification_time')) self.display_name = args.device.display_name for idx, rpd_file in enumerate(rpd_files): self.dest = self.src = None if rpd_file.file_type == FileType.photo: dest_dir = photo_temp_dir else: dest_dir = video_temp_dir # Three scenarios: # 1. Downloading from device with file system we can directly # access # 2. Downloading from camera using libgphoto2 # 3. Downloading from camera where we've already cached at # least some of the files in the Download Cache self.init_copy_progress() if rpd_file.cache_full_file_name and os.path.isfile( rpd_file.cache_full_file_name): # Scenario 3 temp_file_name = os.path.basename( rpd_file.cache_full_file_name) temp_name = os.path.splitext(temp_file_name)[0] temp_full_file_name = os.path.join(dest_dir, temp_file_name) if rpd_cache_same_device[rpd_file.file_type] is None: rpd_cache_same_device[rpd_file.file_type] = same_device( rpd_file.cache_full_file_name, dest_dir) if rpd_cache_same_device[rpd_file.file_type]: try: shutil.move(rpd_file.cache_full_file_name, temp_full_file_name) copy_succeeded = True except (OSError, PermissionError, FileNotFoundError) as inst: copy_succeeded = False logging.error( "Could not move cached file %s to temporary file %s. Error " "code: %s", rpd_file.cache_full_file_name, temp_full_file_name, inst.errno) self.problems.append( FileMoveProblem(name=rpd_file.name, uri=rpd_file.get_uri(), exception=inst)) if self.verify_file: rpd_file.md5 = hashlib.md5( open(temp_full_file_name, 'rb').read()).hexdigest() self.update_progress(rpd_file.size, rpd_file.size) else: # The download folder changed since the scan occurred, and is now # on a different file system compared to that where the devices # files were cached. Or the file was downloaded in full by the scan # stage and saved, e.g. a sample video. source = rpd_file.cache_full_file_name destination = temp_full_file_name copy_succeeded = self.copy_from_filesystem( source, destination, rpd_file) try: os.remove(source) except (OSError, PermissionError, FileNotFoundError) as e: logging.error( "Error removing RPD Cache file %s while copying %s. Error code: %s", source, rpd_file.full_file_name, e.errno) self.problems.append( FileDeleteProblem(name=os.path.basename(source), uri=get_uri(source), exception=e)) else: # Scenario 1 or 2 # Generate temporary name 5 digits long, because we cannot # guarantee the source does not have duplicate file names in # different directories, and here we are copying the files into # a single directory temp_name = random_filename.name() temp_name_ext = '{}.{}'.format(temp_name, rpd_file.extension) temp_full_file_name = os.path.join(dest_dir, temp_name_ext) rpd_file.temp_full_file_name = temp_full_file_name if not rpd_file.cache_full_file_name: if rpd_file.from_camera: # Scenario 2 if not self.camera: copy_succeeded = False logging.error("Could not copy %s from the %s", rpd_file.full_file_name, self.display_name) # self.problems.append(CameraFileReadProblem(name=rpd_file.name, # uri=rpd_file.get_uri())) self.update_progress(rpd_file.size, rpd_file.size) else: copy_succeeded = self.copy_from_camera(rpd_file) else: # Scenario 1 source = rpd_file.full_file_name destination = rpd_file.temp_full_file_name copy_succeeded = self.copy_from_filesystem( source, destination, rpd_file) # increment this amount regardless of whether the copy actually # succeeded or not. It's necessary to keep the user informed. self.total_downloaded += rpd_file.size mdata_exceptions = None if not copy_succeeded: rpd_file.status = DownloadStatus.download_failed logging.debug("Download failed for %s", rpd_file.full_file_name) else: if rpd_file.from_camera: mdata_exceptions = copy_camera_file_metadata( float(rpd_file.modification_time), temp_full_file_name) else: mdata_exceptions = copy_file_metadata( rpd_file.full_file_name, temp_full_file_name) # copy THM (video thumbnail file) if there is one if rpd_file.thm_full_name: rpd_file.temp_thm_full_name = self.copy_associate_file( # translators: refers to the video thumbnail file that some # cameras generate -- it has a .THM file extension rpd_file, temp_name, dest_dir, rpd_file.thm_full_name, _('video THM')) # copy audio file if there is one if rpd_file.audio_file_full_name: rpd_file.temp_audio_full_name = self.copy_associate_file( rpd_file, temp_name, dest_dir, rpd_file.audio_file_full_name, _('audio')) # copy XMP file if there is one if rpd_file.xmp_file_full_name: rpd_file.temp_xmp_full_name = self.copy_associate_file( rpd_file, temp_name, dest_dir, rpd_file.xmp_file_full_name, 'XMP') # copy Magic Lantern LOG file if there is one if rpd_file.log_file_full_name: rpd_file.temp_log_full_name = self.copy_associate_file( rpd_file, temp_name, dest_dir, rpd_file.log_file_full_name, 'LOG') download_count = idx + 1 self.content = pickle.dumps( CopyFilesResults(copy_succeeded=copy_succeeded, rpd_file=rpd_file, download_count=download_count, mdata_exceptions=mdata_exceptions), pickle.HIGHEST_PROTOCOL) self.send_message_to_sink() if len(self.problems): logging.debug('Encountered %s problems while copying from %s', len(self.problems), self.display_name) self.send_problems() if self.camera is not None: self.camera.free_camera() self.disconnect_logging() self.send_finished_command()