
    gB&                        d Z ddlZddlZddlZddlZddlZddlZddlZddlm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ  ej&                  e      Z G d d      Zded	ed
edefdZd!dededefdZej6                  dfdedee   ddfdZ ed      Zde
def   defdZdede
fdZd"dee   defdZ deeef   ddfdZ!dedefdZ"d Z#deee	f   fd Z$y)#z/Various helper functions implemented by pytube.    N)AnyCallableDictListOptionalTypeVar)request)RegexMatchErrorc                   ^    e Zd ZdZd Zd ZdefdZd ZdefdZ	de
fdZdefd	Zd
 Zd Zy)DeferredGeneratorLista   A wrapper class for deferring list generation.

    Pytube has some continuation generators that create web calls, which means
    that any time a full list is requested, all of those web calls must be
    made at once, which could lead to slowdowns. This will allow individual
    elements to be queried, so that slowdowns only happen as necessary. For
    example, you can iterate over elements in the list without accessing them
    all simultaneously. This should allow for speed improvements for playlist
    and channel interactions.
    c                      || _         g | _        y)a  Construct a :class:`DeferredGeneratorList <DeferredGeneratorList>`.

        :param generator generator:
            The deferrable generator to create a wrapper for.
        :param func func:
            (Optional) A function to call on the generator items to produce the list.
        N)gen	_elements)self	generators     W/var/www/it7/html/youtubeDownloader/venv/lib/python3.12/site-packages/pytube/helpers.py__init__zDeferredGeneratorList.__init__   s         c                     t        |       |k(  S )z.We want to mimic list behavior for comparison.)list)r   others     r   __eq__zDeferredGeneratorList.__eq__'   s    DzU""r   returnc                    t        |t        t        f      st        d      |}t        |t              rt        ||dz   d      }t	        | j
                        |j                  k  rT	 t        | j                        }| j
                  j                  |       t	        | j
                        |j                  k  rT| j
                  |   S # t        $ r t        w xY w)z)Only generate items as they're asked for.z"Key must be either a slice or int.   )
isinstanceintslice	TypeErrorlenr   stopnextr   appendStopIteration
IndexError)r   key	key_slice	next_items       r   __getitem__z!DeferredGeneratorList.__getitem__+   s     #U|,@AA 	c3c37A.I $..!INN21 N	
 %%i0 $..!INN2 ~~c"" ! !  !s   'C	 	Cc              #   N   K   d}	 	 | |   }| |dz  }# t         $ r Y yw xY ww)z/Custom iterator for dynamically generated list.r   r   N)r%   )r   
iter_index	curr_items      r   __iter__zDeferredGeneratorList.__iter__B   sE     
  ,	  a
   s   % 
%	"%"%c                 v    	 | | j                      }| xj                   dz  c_         |S # t        $ r t        w xY w)zFetch next element in iterator.r   )r+   r%   r$   )r   curr_elements     r   __next__zDeferredGeneratorList.__next__N   sB    	 0L 	1  	 	 s   ( 8c                 L    | j                          t        | j                        S )z#Return length of list of all items.)generate_allr    r   r   s    r   __len__zDeferredGeneratorList.__len__W       4>>""r   c                 L    | j                          t        | j                        S )z#String representation of all items.)r2   strr   r3   s    r   __repr__zDeferredGeneratorList.__repr__\   r5   r   c                 F    | j                          | j                  d d d   S )N)r2   r   r3   s    r   __reversed__z"DeferredGeneratorList.__reversed__a   s!    ~~dd##r   c                     	 	 t        | j                        }| j                  j                  |       2# t        $ r Y yw xY w)zGenerate all items.N)r"   r   r   r#   r$   )r   r(   s     r   r2   z"DeferredGeneratorList.generate_alle   sD    1 N	 %%i0  ! s   4 	A A N)__name__
__module____qualname____doc__r   r   r   r)   r-   r0   r   r4   r7   r8   r;   r2    r   r   r   r      sP    		### #.
 # # #
## #
$1r   r   patternstringgroupr   c                     t        j                  |       }|j                  |      }|st        d|       t        j                  d|        |j                  |      S )a?  Shortcut method to search a string for a given pattern.

    :param str pattern:
        A regular expression pattern.
    :param str string:
        A target string to search.
    :param int group:
        Index of group to return.
    :rtype:
        str or tuple
    :returns:
        Substring pattern matches.
    regex_search)callerrB   zmatched regex search: %s)recompilesearchr
   loggerdebugrD   )rB   rC   rD   regexresultss        r   rF   rF   p   sN     JJwEll6"G^WEE
LL+W5==r   s
max_lengthc                    t        dd      D cg c]  }t        |       }}g d}dj                  ||z         }t        j                  |t        j
                        }|j                  d|       }|d| j                  dd      d   S c c}w )at  Sanitize a string making it safe to use as a filename.

    This function was based off the limitations outlined here:
    https://en.wikipedia.org/wiki/Filename.

    :param str s:
        A string to make safe for use as a file name.
    :param int max_length:
        The maximum filename character length.
    :rtype: str
    :returns:
        A sanitized string.
    r      )"z\#z\$z\%'z\*z\,z\.z\/z\:rS   z\;z\<z\>z\?z\\z\^z\|z\~z\\\\| N )rangechrjoinrH   rI   UNICODEsubrsplit)rO   rP   intfs_characters
charactersrB   rM   filenames           r   safe_filenamerb      s     (-Q|4!s1v4O4J, hh34GJJw

+EyyQHKZ ''Q/225 5s   B	levellog_filenamec                 f   d}d}t        j                  ||      }t        j                  d      }|j                  |        t        j                         }|j                  |       |j                  |       |8t        j                  |      }|j                  |       |j                  |       yy)z~Create a configured instance of logger.

    :param int level:
        Describe the severity level of the logs to handle.
    z6[%(asctime)s] %(levelname)s in %(module)s: %(message)sz%H:%M:%S)datefmtpytubeN)logging	Formatter	getLoggersetLevelStreamHandlersetFormatter
addHandlerFileHandler)rc   rd   fmtdate_fmt	formatterrK   stream_handlerfile_handlers           r   setup_loggerru      s     CCH!!#x8I x(F
OOE**,N	*
n%**<8!!),,'  r   GenericTypefunc.c                 6     t        j                         |       S )z1 mypy compatible annotation wrapper for lru_cache)	functools	lru_cache)rw   s    r   cacher{      s     9 &&r   reasonc                       fd}|S )z
    This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used.
    c                 N     dt        j                          fd       }|S )Nz.Call to deprecated function {name} ({reason}).c                      t        j                  dt               t        j                  j	                  j
                        t        d       t        j                  dt                | i |S )Nalways)namer|      )category
stackleveldefault)warningssimplefilterDeprecationWarningwarnformatr=   )argskwargsfunc1messager|   s     r   	new_func1z0deprecated.<locals>.decorator.<locals>.new_func1   s]    !!(,>?MMENN6B+
 !!)-?@$)&))r   )ry   wraps)r   r   r   r|   s   ` @r   	decoratorzdeprecated.<locals>.decorator   s+    B			* 
 	* r   rA   )r|   r   s   ` r   
deprecatedr      s      r   output_pathc                    | rRt         j                  j                  |       sGt         j                  j                  t        j                         |       } nt        j                         } t        j
                  | d       | S )a4  
    Function for determining target directory of a download.
    Returns an absolute path (if relative one given) or the current
    path (if none given). Makes directory if it does not exist.

    :type output_path: str
        :rtype: str
    :returns:
        An absolute directory path as a string.
    T)exist_ok)ospathisabsrZ   getcwdmakedirs)r   s    r   target_directoryr      sP     ww}}[)'',,ryy{K@KiikKKd+r   proxy_handlerc                     t        j                  |       }t        j                  |      }t        j                  |       y N)r	   ProxyHandlerbuild_openerinstall_opener)r   proxy_supportopeners      r   install_proxyr     s0    ((7M!!-0F6"r   
duped_listc                 R    i }g }| D ]  }||v rd||<   |j                  |        |S )zRemove duplicate items from a list, while maintaining list order.

    :param List duped_list
        List to remove duplicates from

    :return List result
        De-duplicated list
    T)r#   )r   seenresultitems       r   	uniqueifyr     sC     DF 4<T
d	
 Mr   c                  0    g d} | D ]  }t        |        y)zRegenerate the video mock json files for all current test videos.

    This should automatically output to the test/mocks directory.
    )2lAe1cqCOXo5YceQ8YqYMcirauhITDrsEm8uHb5jIGN8QRS8MkLhQmMWXxV9g7lsFEN)create_mock_html_json)test_vid_idsvid_ids     r   generate_all_html_json_mocksr     s"    
L  &f%&r   c                    ddl m} d| z  }t        j                  j	                  t        j                  j                  t        j                  j                  t              t        j                  j                              }t        j                  j                  |dd      }t        j                  j                  ||      } |d|        }|j                  |j                  |j                  |j                  |j                  d}t        j                  d|        t!        j"                  |d	      5 }|j%                  t'        j(                  |      j+                  d
             ddd       |S # 1 sw Y   |S xY w)zGenerate a json.gz file with sample html responses.

    :param str vid_id
        YouTube video id

    :return dict data
        Dict used to generate the json.gz file
    r   )YouTubezyt-video-%s-html.json.gztestsmocksz https://www.youtube.com/watch?v=)urljs
embed_html
watch_htmlvid_infozOutputing json.gz file to wbzutf-8N)rg   r   r   r   abspathrZ   dirname__file__pardir	watch_urlr   r   r   r   rK   infogzipopenwritejsondumpsencode)	r   r   gzip_filenamepytube_dir_pathpytube_mocks_pathgzip_filepathyt	html_datafs	            r   r   r   ,  s     .7M ggoo
GGOOH%GGNN	
O _gwGGGLL!2MBM	3F8<	=B||eemmmmKKI KK,]O<=	=$	' 71	

9%,,W567 7 s   64E44E>)   r   )%r@   ry   r   r   rh   r   rH   r   typingr   r   r   r   r   r   urllibr	   pytube.exceptionsr
   rj   r=   rK   r   r7   r   rF   rb   ERRORru   rv   r{   r   r   r   r   r   r   rA   r   r   <module>r      sH   5     	 	  ? ?  -			8	$\1 \1~ #  s  3  3  0)3S )3c )3C )3X &mm4 ( (8C= (TX (0 m$'k)* '{ '
s x 4(3- 3 (#c3h #D #$ 4 &&"#T#s(^ #r   