from pathlib import Path from .handler import Handler from ..exceptions import ValidationException @Handler.register class SubtitlesImportHandler(Handler): """ This class saves uploaded subtitles to a package. """ @classmethod def wants(cls, jobspec, existing_package): """ Return True if this handler wants to process this jobspec. Raises an exception if the job is wanted but doesn't pass validation. A job is wanted if the job specification contains a 'subtitles' key. """ if 'subtitles' in jobspec: return cls._validate(jobspec, existing_package) return False @classmethod def _validate(cls, jobspec, existing_package): """ Return True if the job is valid for this handler. Validity requirements are: - Keys in 'subtitles' and 'generate_subtitles' must be mututally unique. - If any value in the 'subtitles' object is not None, the job must contain an 'upload_dir' key which must point to an existing directory. - All 'subtitles' values that are not None must be existing files under 'upload_dir'. """ super()._validate(jobspec, existing_package) # Check for duplicate track names generate_names = jobspec.get('generate_subtitles', {}).keys() store_names = jobspec.get('subtitles', {}).keys() common_names = generate_names & store_names if common_names: names_string = ', '.join(common_names) raise ValidationException( f"Duplicate subtitle track name(s): {names_string}") # Validate storage tasks for name, subsfile in jobspec.get('subtitles', {}).items(): if not subsfile: continue if 'upload_dir' not in jobspec: raise ValidationException("upload_dir missing") subspath = Path(jobspec['upload_dir']) / subsfile if not subspath.is_file(): raise ValidationException( f"Error for subtitle track {name}: " f"{subspath} is not a valid file") return True def _handle(self, jobspec, existing_package, tempdir): def apply_func(package): for name, subsfile in jobspec.get('subtitles', {}).items(): subspath = None if subsfile: subspath = Path(jobspec['upload_dir']) / subsfile package.set_subtitle_track(name, subspath) return apply_func