U
    g:                     @   s   d dl Z d dlZd dlZddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZ G dd deZG d	d
 d
eZG dd deZG dd deZdS )    N   )InfoExtractor   )	HTTPError)ExtractorErrordetermine_extint_or_nonejoin_nonempty
js_to_jsonmake_archive_id
orderedSet	qualitiesstr_or_nonetraverse_objtry_geturlencode_postdatac                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )FunimationBaseIEZ
funimationNc                 C   sF   |  dd}|r|jn| d}|pDt| jdd dddddpDd	S )
Nzhttps://www.funimation.comregionZgeo_bypass_countryz=https://geo-service.prd.funimationsvc.com/geo/v1/region/checkFzChecking geo-locationz(Unable to fetch geo-location information)fatalnoteZerrnoteZUS)Z_get_cookiesgetvalue	get_paramr   _download_json)selfZregion_cookier    r   ?/tmp/pip-unpacked-wheel-q5ljy6pj/yt_dlp/extractor/funimation.py_get_region   s       zFunimationBaseIE._get_regionc              
   C   s   | j r
d S z*| jdd dt||dd}|d t_ W nd tk
r } zFt|jtr|jjdkr| 	|jj
  d d }t|dd	 W 5 d }~X Y nX d S )
Nz>https://prod-api-funimationnow.dadcdigital.com/api/auth/login/z
Logging in)usernamepassword)datatokeni  errorT)expected)_TOKENr   r   r   r   
isinstancecauser   status_parse_jsonresponsereaddecode)r   r   r   r    er"   r   r   r   _perform_login%   s$      zFunimationBaseIE._perform_login)__name__
__module____qualname__Z_NETRC_MACHINE_REGIONr$   r   r-   r   r   r   r   r      s
   	r   c                   @   sb   e Zd ZdZdZddddddd	id
gdddddddddddddgZdd Zdd ZdS )FunimationPageIEzfunimation:pagezuhttps?://(?:www\.)?funimation(?:\.com|now\.uk)/(?:(?P<lang>[^/]+)/)?(?:shows|v)/(?P<show>[^/]+)/(?P<episode>[^/?#&]+)zShttps://www.funimation.com/shows/attack-on-titan-junior-high/broadcast-dub-preview/210050mp4Broadcast Dub Preview)idexttitleskip_downloadm3u8Z
Funimation)url	info_dictparamsZadd_iez4https://www.funimation.com/shows/hacksign/role-play/T)r;   Zonly_matchingz7https://www.funimation.com/en/shows/hacksign/role-play/zJhttps://www.funimationnow.uk/shows/puzzle-dragons-x/drop-impact/simulcast/zOhttps://www.funimation.com/v/a-certain-scientific-railgun/super-powered-level-5c                 C   s   | j s|  t_ d S Nr1   r   r   r   r   r   r   _real_initializeW   s    z!FunimationPageIE._real_initializec                 C   sp   |  |ddd\}}}t| jd| d| | d| d| j|pFdd	d
ddd}| d| t |S )Nlangshowepisodez1https://title-api.prd.funimationsvc.com/v1/shows/z
/episodes/_Zweben)Z
deviceTyper   locale)query)Z	videoList.r6   F)get_all"https://www.funimation.com/player/)_match_valid_urlgroupr   r   r1   
url_resultFunimationIEie_key)r   r;   rG   rC   rD   video_idr   r   r   _real_extract[   s     zFunimationPageIE._real_extractNr.   r/   r0   IE_NAME
_VALID_URL_TESTSrA   rQ   r   r   r   r   r2   7   s6    r2   c                   @   s   e Zd ZdZdddddddddd	d
ddddddidddddddddddd	d
ddddddgddgZedd Zd!ddZdd Zdd  Z	dS )"rN   z5https?://(?:www\.)?funimation\.com/player/(?P<id>\d+)z(https://www.funimation.com/player/210051r3   zbroadcast-dub-previewr4   r5   zre:https?://.*\.(?:jpg|png)ZExtrasZ166038c   zAttack on Titan: Junior High    )r6   
display_idr7   r8   Z	thumbnailrD   
episode_idseason	season_idseason_numberseriesdescriptiondurationr9   r:   )r;   r<   r=   z:player_id should be extracted with the relevent compat-optZ210051seperate-video-versions)r9   compat_opts)r   r;   r<   r=   c                 c   sN   |  di  D ]8\}}| D ]&}| D ]\}}|| |fV  q,q qd S )N	languages)r   itemsvaluesr8   )rD   rB   Z	lang_dataZ
video_dataversionfr   r   r   _get_experiences   s    zFunimationIE._get_experiencesNTc           
      C   s   | j | jd|d|d|t|dp"g }|dg D ]~}|dg D ]l}|dk	rrt|d|kr@|||f    S q@| |D ].\}}}	|	d	|kr||||f      S q|q@q0|rtd
n
| d
 i i i fS )zQ Extract the episode, season and show objects given either episode/experience id zshow\s*=\s*({.+?})\s*;z	show data)r   )Ztransform_sourcer   ZseasonsZepisodesN	episodePkexperienceIdz"Unable to find episode information)r(   Z_search_regexr
   r   strrh   r   report_warning)
r   webpageexperience_idrZ   r   rC   r[   rD   rE   rg   r   r   r   _get_episode   s4         

zFunimationIE._get_episodec                  C   s  |  |}| j||d| d}| j|t|d\}}}t|d }|dpP|}g i g df\}	}
}}| d| d }}t|pd	gd d d
 }t|pddgd d d
 }d| dg k}| 	|D ]&\}}}t|d }|r||ks| r|
 |ks|r|
 |krq|d|di t||dd}| d| d| d}| j|
|||||krj|n|d i }| jrd| j |d< | jd| d||ddd	tjtjtj ddid| d d!}|d"pg }|s6t|d#d$ t}|r,| d%| j|d&|d'p$|d( n
| d) g }|D ]}|d*}|d+p^t|}|d,kr|| j||d-d.|d/d0d| d1d2 n|| d3| |d4 |D ]*}|||||
 ||
 d5 q|	| q>q|	s|s|r| jd6d7|d8 |  |	 |t!| |g|||d9 |d:|d9t"|d;||d<t"|d=t#|d>|d?|	||
d@dAS )BNDownloading player webpage for )r   )rn   ri   Zslugr   languagerf   rW   ZuncutZ	simulcastra   rb   rj   r;   Zposterr`    z ())rY   format_namerD   zToken Authorizationz.https://www.funimation.com/api/showexperience//i  Zpinst_id   )kzDownloading z JSON)headersZexpected_statusrH   r   rd   c                 S   s   | d d S )Nerrorsr   r   xr   r   r   <lambda>       z,FunimationIE._real_extract.<locals>.<lambda>z{} said: Error {} - {}codeZdetailr8   zNo sources found for formatsrcZ	videoTyper:   r4   z{}-{}ZhlsFz m3u8 information)Zm3u8_idr   r   -)Z	format_idr;   )rq   Zformat_notesource_preferencelanguage_preferencezDThere are no video formats matching the requested languages/versionsT)r#   rP   ZepisodeTitleZepisodeSummary	episodeIdZseasonTitleZseasonIdZseasonPkZ	showTitle)rB   source)r6   Z_old_archive_idsrY   r`   r8   r_   rD   Zepisode_numberrZ   r[   r]   r\   r^   formats
thumbnails	subtitlesZ_format_sort_fields)$Z	_match_id_download_webpagero   intrk   r   Z_configuration_argr   r   rh   lowerappendmaxZextract_subtitlesr$   r   joinrandomchoicesstringdigitsascii_lettersr   dictrl   formatrS   r   extendZ_extract_m3u8_formatsupdateZraise_no_formatsZ_remove_duplicate_formatsr   r   r   ) r   r;   Zinitial_experience_idrm   rD   r[   rC   rZ   rY   r   r   r   r`   Zrequested_languagesZrequested_versionsr   r   Zonly_initial_experiencerB   rf   fmtrn   ru   rz   pagesourcesr"   Zcurrent_formatsr   
source_urlZsource_typerg   r   r   r   rQ      s    
  

   
   
  


   
 



  

zFunimationIE._real_extractc              
   C   s
  t |tr@| jd| d|dd| d}| j||dd\}}}| |D ]\}}}	|	dD ]}
|
dD ]}|d	s|ql|d
 }|dkr|nd }|d	 t||d|ddd}t|dd|dkr|nd |dd}|||g krl||g 	| qlq^qJ|S )NrJ   rw   Frp   )r   r   )rZ   r   r   Z
textTracksr   typeZFULLlabelrs   )delim)r;   namerq   ZundZ	SimulcastrE   )
r%   rk   r   ro   rh   r   upperr	   
setdefaultr   )r   r   rn   rD   rY   ru   rm   rE   rf   rg   r   Z
text_trackZsub_typeZcurrent_subrB   r   r   r   _get_subtitles  s4    

  
 zFunimationIE._get_subtitles)NNT)
r.   r/   r0   rT   rU   staticmethodrh   ro   rQ   r   r   r   r   r   rN   i   s\    ,

[rN   c                   @   sT   e Zd ZdZdZddddddd	id
ddddddd	id
gZdd Zdd ZdS )FunimationShowIEzfunimation:showzn(?P<url>https?://(?:www\.)?funimation(?:\.com|now\.uk)/(?P<locale>[^/]+)?/?shows/(?P<id>[^/?#&]+))/?(?:[?#]|$)z4https://www.funimation.com/en/shows/sk8-the-infinityZ1315000zSK8 the Infinity)r6   r8      r9   T)r;   r<   Zplaylist_countr=   z=https://www.funimation.com/shows/ouran-high-school-host-club/Z39643zOuran High School Host Club   c                 C   s   | j s|  t_ d S r>   r?   r@   r   r   r   rA   D  s    z!FunimationShowIE._real_initializec              	      s    | \ }}d|j|p(d|}d|d|}t|dddd d	f}d
t|d |d t fddt	|dd dD dS )NzVhttps://title-api.prd.funimationsvc.com/v2/shows/{}?region={}&deviceType=web&locale={}rF   z_https://prod-api-funimationnow.dadcdigital.com/api/funimation/episodes/?limit=99999&title_id={}r6   rd   .c                 S   s   t d| S )Nz(?i)mostRecent[AS]vod)rematch)ry   rE   r   r   r   r~   R  r   z0FunimationShowIE._real_extract.<locals>.<lambda>itemZplaylistr   c              	   3   s<   | ]4} d  |dt |d|dV  qdS )z{}/{}ZepisodeSlugr   ZepisodeNameN)rM   r   r   r2   rO   ).0Zvod_itembase_urlr   r   r   	<genexpr>X  s     z1FunimationShowIE._real_extract.<locals>.<genexpr>c                 S   s   |  ddS )NZepisodeOrderrr   )r   r|   r   r   r   r~   \  r   )key)_typer6   r8   entries)
rK   groupsr   r   r1   r   r   r   r   sorted)r   r;   rG   rY   Z	show_infoZ
items_infoZ	vod_itemsr   r   r   rQ   H  s.      
zFunimationShowIE._real_extractNrR   r   r   r   r   r   )  s.     r   )r   r   r   commonr   Znetworking.exceptionsr   utilsr   r   r   r	   r
   r   r   r   r   r   r   r   r   r2   rN   r   r   r   r   r   <module>   s   8 2 A