"""Media metadata extraction module.""" import json import subprocess from owsresponse import response from sentry_sdk import capture_exception from transcoding import config from transcoding.constants import error def get_media_info(file_path, filter_pattern): """Get mediainfo output for file by filter pattern. Args: file_path (str): path to file or url. filter_pattern (str): String pattern for grabbing mediainfo results Returns: response.Response: dictionary with mediainfo output in message or error response. """ try: pipes = subprocess.Popen( [config.MEDIAINFO_PATH, filter_pattern, file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) media_info_binary_data, error_output = pipes.communicate() media_info = json.loads(media_info_binary_data.decode('utf-8')) media_info_error = error_output.decode('utf-8') # validate cli output if not media_info or media_info_error: error_message = error.ERROR_MEDIAINFO_ERROR_MESSAGE.format( media_info_error) return response.create_fatal_response(error_message) return response.Response(media_info.get('media').get('track')[1]) except (OSError, subprocess.CalledProcessError) as e: capture_exception(e) return response.create_fatal_response(str(e)) except (ValueError, TypeError) as e: capture_exception(e) error_message = error.ERROR_MESSAGE_INVALID_AUDIO_ASSET.format( asset_path=file_path) return response.create_error_response( error.ERROR_CODE_BODY_VALIDATION, error_message, status=400)