






import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


__UpperCamelCase   :   Tuple      =    get_logger(__name__)


class 							__UpperCamelCase     :







	def __init__(	self   :				List[Any]							,					_lowerCAmelCase   :				Optional[str] = None      )		->			Optional[int]:
		"""simple docstring"""







		__lowercase   							=	(
		    os.path.join(_lowerCAmelCase							,					config.EXTRACTED_DATASETS_DIR      ) if cache_dir else config.EXTRACTED_DATASETS_PATH
		)
		__lowercase   							=	Extractor







	def 			_a (	self   :				List[Any]							,					_lowerCAmelCase   :				str      )		->			str:
		"""simple docstring"""







		from .file_utils import hash_url_to_filename

		# Path where we extract compressed archives
		# We extract in the cache dir, and get the extracted path name by hashing the original path"
		__lowercase   							=	os.path.abspath(_lowerCAmelCase      )
		return os.path.join(self.extract_dir							,					hash_url_to_filename(_lowerCAmelCase      )      )







	def 			_a (	self   :				Any							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				bool      )		->			bool:
		"""simple docstring"""







		return force_extract or (
		    not os.path.isfile(_lowerCAmelCase      ) and not (os.path.isdir(_lowerCAmelCase      ) and os.listdir(_lowerCAmelCase      ))
		)







	def 			_a (	self   :				Optional[int]							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				bool = False      )		->			str:
		"""simple docstring"""







		__lowercase   							=	self.extractor.infer_extractor_format(_lowerCAmelCase      )
		if not extractor_format:
			return input_path
		__lowercase   							=	self._get_output_path(_lowerCAmelCase      )
		if self._do_extract(_lowerCAmelCase							,					_lowerCAmelCase      ):
			self.extractor.extract(_lowerCAmelCase							,					_lowerCAmelCase							,					_lowerCAmelCase      )
		return output_path


class 							__UpperCamelCase     (  _lowerCAmelCase ):







	@classmethod
	@abstractmethod
	def 			_a (	cls   :				str							,					_lowerCAmelCase   :				Union[Path, str]							,					**_lowerCAmelCase   :				Union[str, Any]      )		->			bool:
		"""simple docstring"""







		...







	@staticmethod
	@abstractmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		...


class 							__UpperCamelCase     (  _lowerCAmelCase ,      _lowerCAmelCase ):
	__snake_case						:List[bytes] =							[]







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				int      )		->			Tuple:
		"""simple docstring"""







		with open(_lowerCAmelCase							,					"""rb"""      ) as f:
			return f.read(_lowerCAmelCase      )







	@classmethod
	def 			_a (	cls   :				Dict							,					_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				bytes = b""      )		->			bool:
		"""simple docstring"""







		if not magic_number:
			__lowercase   							=	max(len(_lowerCAmelCase      ) for cls_magic_number in cls.magic_numbers      )
			try:
				__lowercase   							=	cls.read_magic_number(_lowerCAmelCase							,					_lowerCAmelCase      )
			except OSError:
				return False
		return any(magic_number.startswith(_lowerCAmelCase      ) for cls_magic_number in cls.magic_numbers      )


class 							__UpperCamelCase     (  _lowerCAmelCase ):







	@classmethod
	def 			_a (	cls   :				Optional[int]							,					_lowerCAmelCase   :				Union[Path, str]							,					**_lowerCAmelCase   :				List[Any]      )		->			bool:
		"""simple docstring"""







		return tarfile.is_tarfile(_lowerCAmelCase      )







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Any							,					_lowerCAmelCase   :				str      )		->			Any:
		"""simple docstring"""







		def resolved(_lowerCAmelCase   :				str      ) -> str:
			return os.path.realpath(os.path.abspath(_lowerCAmelCase      )      )

		def badpath(_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				str      ) -> bool:
			# joinpath will ignore base if path is absolute
			return not resolved(os.path.join(_lowerCAmelCase							,					_lowerCAmelCase      )      ).startswith(_lowerCAmelCase      )

		def badlink(_lowerCAmelCase   :				Union[str, Any]							,					_lowerCAmelCase   :				str      ) -> bool:
			# Links are interpreted relative to the directory containing the link
			__lowercase   							=	resolved(os.path.join(_lowerCAmelCase							,					os.path.dirname(info.name      )      )      )
			return badpath(info.linkname							,					base=_lowerCAmelCase      )

		__lowercase   							=	resolved(_lowerCAmelCase      )

		for finfo in members:
			if badpath(finfo.name							,					_lowerCAmelCase      ):
				logger.error(F'Extraction of {finfo.name} is blocked (illegal path)'      )
			elif finfo.issym() and badlink(_lowerCAmelCase							,					_lowerCAmelCase      ):
				logger.error(F'Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}'      )
			elif finfo.islnk() and badlink(_lowerCAmelCase							,					_lowerCAmelCase      ):
				logger.error(F'Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}'      )
			else:
				yield finfo







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		os.makedirs(_lowerCAmelCase							,					exist_ok=_lowerCAmelCase      )
		__lowercase   							=	tarfile.open(_lowerCAmelCase      )
		tar_file.extractall(_lowerCAmelCase							,					members=TarExtractor.safemembers(_lowerCAmelCase							,					_lowerCAmelCase      )      )
		tar_file.close()


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Dict =							[B'\x1F\x8B']







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		with gzip.open(_lowerCAmelCase							,					"""rb"""      ) as gzip_file:
			with open(_lowerCAmelCase							,					"""wb"""      ) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase							,					_lowerCAmelCase      )


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:List[str] =							[
	    B'PK\x03\x04',
	    B'PK\x05\x06',  # empty archive
	    B'PK\x07\x08',  # spanned archive
	]







	@classmethod
	def 			_a (	cls   :				Tuple							,					_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				bytes = b""      )		->			bool:
		"""simple docstring"""







		if super().is_extractable(_lowerCAmelCase							,					magic_number=_lowerCAmelCase      ):
			return True
		try:
			# Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
			# From: https://github.com/python/cpython/pull/5053
			from zipfile import (
			    _CD_SIGNATURE,
			    _ECD_DISK_NUMBER,
			    _ECD_DISK_START,
			    _ECD_ENTRIES_TOTAL,
			    _ECD_OFFSET,
			    _ECD_SIZE,
			    _EndRecData,
			    sizeCentralDir,
			    stringCentralDir,
			    structCentralDir,
			)

			with open(_lowerCAmelCase							,					"""rb"""      ) as fp:
				__lowercase   							=	_EndRecData(_lowerCAmelCase      )
				if endrec:
					if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
						return True  # Empty zipfiles are still zipfiles
					elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
						fp.seek(endrec[_ECD_OFFSET]      )  # Central directory is on the same disk
						if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
							__lowercase   							=	fp.read(_lowerCAmelCase      )  # CD is where we expect it to be
							if len(_lowerCAmelCase      ) == sizeCentralDir:
								__lowercase   							=	struct.unpack(_lowerCAmelCase							,					_lowerCAmelCase      )  # CD is the right size
								if centdir[_CD_SIGNATURE] == stringCentralDir:
									return True  # First central directory entry  has correct magic number
			return False
		except Exception:  # catch all errors in case future python versions change the zipfile internals
			return False







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		os.makedirs(_lowerCAmelCase							,					exist_ok=_lowerCAmelCase      )
		with zipfile.ZipFile(_lowerCAmelCase							,					"""r"""      ) as zip_file:
			zip_file.extractall(_lowerCAmelCase      )
			zip_file.close()


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Tuple =							[B'\xFD\x37\x7A\x58\x5A\x00']







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		with lzma.open(_lowerCAmelCase      ) as compressed_file:
			with open(_lowerCAmelCase							,					"""wb"""      ) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase							,					_lowerCAmelCase      )


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Union[str, Any] =							[B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		if not config.RARFILE_AVAILABLE:
			raise ImportError("""Please pip install rarfile"""      )
		import rarfile

		os.makedirs(_lowerCAmelCase							,					exist_ok=_lowerCAmelCase      )
		__lowercase   							=	rarfile.RarFile(_lowerCAmelCase      )
		rf.extractall(_lowerCAmelCase      )
		rf.close()


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Dict =							[B'\x28\xb5\x2F\xFD']







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		if not config.ZSTANDARD_AVAILABLE:
			raise ImportError("""Please pip install zstandard"""      )
		import zstandard as zstd

		__lowercase   							=	zstd.ZstdDecompressor()
		with open(_lowerCAmelCase							,					"""rb"""      ) as ifh, open(_lowerCAmelCase							,					"""wb"""      ) as ofh:
			dctx.copy_stream(_lowerCAmelCase							,					_lowerCAmelCase      )


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:List[Any] =							[B'\x42\x5A\x68']







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		with bza.open(_lowerCAmelCase							,					"""rb"""      ) as compressed_file:
			with open(_lowerCAmelCase							,					"""wb"""      ) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase							,					_lowerCAmelCase      )


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:List[Any] =							[B'\x37\x7A\xBC\xAF\x27\x1C']







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		if not config.PY7ZR_AVAILABLE:
			raise ImportError("""Please pip install py7zr"""      )
		import pyazr

		os.makedirs(_lowerCAmelCase							,					exist_ok=_lowerCAmelCase      )
		with pyazr.SevenZipFile(_lowerCAmelCase							,					"""r"""      ) as archive:
			archive.extractall(_lowerCAmelCase      )


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Any =							[B'\x04\x22\x4D\x18']







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]      )		->			None:
		"""simple docstring"""







		if not config.LZ4_AVAILABLE:
			raise ImportError("""Please pip install lz4"""      )
		import lza.frame

		with lza.frame.open(_lowerCAmelCase							,					"""rb"""      ) as compressed_file:
			with open(_lowerCAmelCase							,					"""wb"""      ) as extracted_file:
				shutil.copyfileobj(_lowerCAmelCase							,					_lowerCAmelCase      )


class 							__UpperCamelCase     :
	#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
	__snake_case						:Dict[str, Type[BaseExtractor]] =							{
	    "tar": TarExtractor,
	    "gzip": GzipExtractor,
	    "zip": ZipExtractor,
	    "xz": XzExtractor,
	    "rar": RarExtractor,
	    "zstd": ZstdExtractor,
	    "bz2": BzipaExtractor,
	    "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
	    "lz4": LzaExtractor,  # <Added version="2.4.0"/>
	}







	@classmethod
	def 			_a (	cls   :				Tuple      )		->			Any:
		"""simple docstring"""







		return max(
		    len(_lowerCAmelCase      )
		    for extractor in cls.extractors.values()
		    if issubclass(_lowerCAmelCase							,					_lowerCAmelCase      )
		    for extractor_magic_number in extractor.magic_numbers      )







	@staticmethod
	def 			_a (	_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				int      )		->			Union[str, Any]:
		"""simple docstring"""







		try:
			return MagicNumberBaseExtractor.read_magic_number(_lowerCAmelCase							,					magic_number_length=_lowerCAmelCase      )
		except OSError:
			return b""







	@classmethod
	def 			_a (	cls   :				List[str]							,					_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				bool = False      )		->			bool:
		"""simple docstring"""







		warnings.warn(
		    """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
		    """Use 'infer_extractor_format' instead."""							,					category=_lowerCAmelCase							,					)
		__lowercase   							=	cls.infer_extractor_format(_lowerCAmelCase      )
		if extractor_format:
			return True if not return_extractor else (True, cls.extractors[extractor_format])
		return False if not return_extractor else (False, None)







	@classmethod
	def 			_a (	cls   :				int							,					_lowerCAmelCase   :				Union[Path, str]      )		->			str:  # <Added version="2.4.0"/>
		"""simple docstring"""







		__lowercase   							=	cls._get_magic_number_max_length()
		__lowercase   							=	cls._read_magic_number(_lowerCAmelCase							,					_lowerCAmelCase      )
		for extractor_format, extractor in cls.extractors.items():
			if extractor.is_extractable(_lowerCAmelCase							,					magic_number=_lowerCAmelCase      ):
				return extractor_format







	@classmethod
	def 			_a (	cls   :				Tuple							,					_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Union[Path, str]							,					_lowerCAmelCase   :				Optional[str] = None							,					_lowerCAmelCase   :				Optional[BaseExtractor] = "deprecated"							,					)		->			None:
		"""simple docstring"""







		os.makedirs(os.path.dirname(_lowerCAmelCase      )							,					exist_ok=_lowerCAmelCase      )
		# Prevent parallel extractions
		__lowercase   							=	str(Path(_lowerCAmelCase      ).with_suffix(""".lock"""      )      )
		with FileLock(_lowerCAmelCase      ):
			shutil.rmtree(_lowerCAmelCase							,					ignore_errors=_lowerCAmelCase      )
			if extractor_format or extractor != "deprecated":
				if extractor != "deprecated" or not isinstance(_lowerCAmelCase							,					_lowerCAmelCase      ):  # passed as positional arg
					warnings.warn(
					    """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
					    """Use 'extractor_format' instead."""							,					category=_lowerCAmelCase							,					)
					__lowercase   							=	extractor if extractor != """deprecated""" else extractor_format
				else:
					__lowercase   							=	cls.extractors[extractor_format]
				return extractor.extract(_lowerCAmelCase							,					_lowerCAmelCase      )
			else:
				warnings.warn(
				    """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """
				    """exception in 3.0.0."""							,					category=_lowerCAmelCase							,					)
				for extractor in cls.extractors.values():
					if extractor.is_extractable(_lowerCAmelCase      ):
						return extractor.extract(_lowerCAmelCase							,					_lowerCAmelCase      )






from datetime import datetime

import requests

def        __a			(   __lowerCAmelCase   )     ->     bytes:
					SCREAMING_SNAKE_CASE							:     int						=				'https://downloadgram.net/wp-json/wppress/video-downloader/video?url='
					SCREAMING_SNAKE_CASE							:     Any						=				requests.get(base_url + url   ).json()[0]['urls'][0]['src']
					return requests.get(__lowerCAmelCase   ).content


if __name__ == "__main__":
			_lowerCamelCase    :		List[Any]		      =    input("""Enter Video/IGTV url: """).strip()
			_lowerCamelCase    :		int		      =    f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4"""
			with open(file_name, """wb""") as fp:
						fp.write(download_video(url))
			print(f"""Done. Video saved to disk as {file_name}.""")