
    yf{:                         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e      Z G d	 d
e      Z G d de      Z G d de      Zy)    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                   $    e Zd ZdZdZdZd Zd Zy)FunimationBaseIE
funimationNc           	          | j                  d      j                  d      }|r|j                  n| j                  d      }|xs$ t	        | j                  dd ddd      d      xs d	S )
Nzhttps://www.funimation.comregiongeo_bypass_countryz=https://geo-service.prd.funimationsvc.com/geo/v1/region/checkFzChecking geo-locationz(Unable to fetch geo-location information)fatalnoteerrnoteUS)_get_cookiesgetvalue	get_paramr   _download_json)selfregion_cookier   s      =/usr/lib/python3/dist-packages/yt_dlp/extractor/funimation.py_get_regionzFunimationBaseIE._get_region   s}    ))*FGKKHU(5$$4>>J^;_ OQU]b,6`   b 	  		    c           
         | j                   ry 	 | j                  dd dt        ||d            }|d   t        _         y # t        $ r}t        |j                  t              rk|j                  j                  dk(  rR| j                  |j                  j                  j                         j                         d       d   }t	        |d	       d }~ww xY w)
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,   s         r$   _perform_loginzFunimationBaseIE._perform_login%   s    ;;	&&Pl); ( (= * ' D '+7m# 	!''9-!''..C2G(()9)9)>)>)@)G)G)I4PQXY$UT::		s   /? 	CBCC)__name__
__module____qualname___NETRC_MACHINE_REGIONr.   r%   r7    r&   r$   r   r      s    !NGFr&   r   c                   ^    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 Zd Zy)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m3u8
Funimation)url	info_dictparamsadd_iez4https://www.funimation.com/shows/hacksign/role-play/T)rI   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                 P    | j                   s| j                         t        _         y y Nr<   r%   r   r"   s    r$   _real_initializez!FunimationPageIE._real_initializeW        ||'+'7'7'9$ r&   c           
         | j                  |      j                  ddd      \  }}}t        | j                  d| d| | d| d| j                  |xs dd	
      dd      }| j                  d| t        j                         |      S )Nlangshowepisodez1https://title-api.prd.funimationsvc.com/v1/shows/z
/episodes/_weben)
deviceTyper   locale)query)	videoList.rC   F)get_all"https://www.funimation.com/player/)_match_valid_urlgroupr   r!   r<   
url_resultFunimationIEie_key)r"   rI   r\   rV   rW   video_ids         r$   _real_extractzFunimationPageIE._real_extract[   s     $ 5 5c : @ @QZ [g 3 3?vZPWyYfAgY#,, .D( !4 ! )%9 !CH:NP\PcPcPegoppr&   Nr8   r9   r:   IE_NAME
_VALID_URL_TESTSrR   rg   r=   r&   r$   r?   r?   7   s    G JJ e,
 V
  . F I
 \ a/F8:qr&   r?   c                       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        ZddZd Zd Z	y)rd   z5https?://(?:www\.)?funimation\.com/player/(?P<id>\d+)z(https://www.funimation.com/player/210051r@   zbroadcast-dub-previewrA   rB   zre:https?://.*\.(?:jpg|png)Extras166038c   zAttack on Titan: Junior High    )rC   
display_idrD   rE   	thumbnailrW   
episode_idseason	season_idseason_numberseriesdescriptiondurationrF   rG   )rI   rJ   rK   z:player_id should be extracted with the relevent compat-opt210051seperate-video-versions)rF   compat_opts)r   rI   rJ   rK   c              #      K   | j                  di       j                         D ]G  \  }}|j                         D ]/  }|j                         D ]  \  }}||j                         |f  1 I y w)N	languages)r   itemsvaluesrE   )rW   rU   	lang_data
video_dataversionfs         r$   _get_experienceszFunimationIE._get_experiences   st     &{{;;AAC 	3OD)'..0 3
","2"2"4 3JGQ2233	3s   A,A.Nc                    | j                  | j                  d|d|      |t        |      xs g }|j                  dg       D ]{  }|j                  dg       D ]d  }|'t	        |j                  d            |k(  r	|||fc c S ,| j                  |      D ]%  \  }}}	|	j                  d      |k(  s|||fc c c S  f } |rt        d	      | j                  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   )transform_sourcer   seasonsepisodes	episodePkexperienceIdz"Unable to find episode information)r2   _search_regexr   r   strr   r   report_warning)
r"   webpageexperience_idrt   r   rV   ru   rW   rX   r   s
             r$   _get_episodezFunimationIE._get_episode   s   )7Ku  NJe   E K IK 	 hhy"- 	5F!::j"5 5)7;;{34
B&44#44W= 5GAq!uu^,=&4455	5  !EFF DE2rzr&   c                    | j                  |      }| j                  ||d|       }| j                  |t        |            \  }}}t	        |d         }|j                  d      xs |}g i g df\  }	}
}}| j                  d      | j                  d      }}t        |xs d	gd d d
         }t        |xs ddgd d d
         }d| j                  dg       v }| j                  |      D ]  \  }}}t	        |d         }|r||k7  s(|r|j                         |vs|r|j                         |vrF|j                  d|j                  d      i       t        ||j                  dd            }|d|d|d}| j                  |
|||||k(  r|n|       i }| j                  rd| j                  z  |d<   | j                  d|z  ||ddd	j!                  t#        j$                  t&        j(                  t&        j*                  z   d            id| d       }|j                  d!      xs g }|szt-        |d" t.              }|rU| j1                  | j2                  d#|j                  d$      d%|j                  d&      xs |j                  d'             n| j1                  d(       g }|D ]  }|j                  d)      }|j                  d*      xs t5        |      }|d+k(  r0|j7                  | j9                  ||d,|d-d.d/d| d01             n|j                  |d-||d2       |D ]@  }|j;                  || ||j                                ||j                               d3       B |	j7                  |         |	s|s|r| j=                  d4d5|6       | j?                  |	       i d7|d8tA        | |      gd9|d|d'|d:   d;|j                  d<      d=|j                  d:      d>tC        |j                  d?            d@|dA|j                  dB      dCtC        |j                  dD            dEtE        |j                  dF            dG|j                  dH      dI|	dJ|dK|
dLdMS )NNDownloading player webpage for )r   )r   r   slugr   languager   rp   uncut	simulcastr|   r}   r   rI   posterrz    z ())rr   format_namerW   zToken %sAuthorizationz1https://www.funimation.com/api/showexperience/%s/i  pinst_id   )kzDownloading z JSON)headersexpected_statusr]   r   r   c                     | d   d   S )Nerrorsr   r=   xs    r$   <lambda>z,FunimationIE._real_extract.<locals>.<lambda>   s    (A r&   z said: Error codez - detailrE   zNo sources found for formatsrc	videoTyperG   rA   -hlsFz m3u8 information)m3u8_idr   r   )	format_idrI   )r   format_notesource_preferencelanguage_preferencezDThere are no video formats matching the requested languages/versionsT)r-   rf   rC   _old_archive_idsrr   episodeTitlery   episodeSummaryrW   episode_number	episodeIdrt   ru   seasonTitlerw   seasonIdrv   seasonPkrx   	showTitleformats
thumbnails	subtitles_format_sort_fields)rU   source)#	_match_id_download_webpager   intr   r   _configuration_argr   r    r   lowerappendmaxextract_subtitlesr.   r!   joinrandomchoicesstringdigitsascii_lettersr   dictr   ri   r   extend_extract_m3u8_formatsupdateraise_no_formats_remove_duplicate_formatsr   r	   r   ) r"   rI   initial_experience_idr   rW   ru   rV   rt   rr   r   r   r   rz   requested_languagesrequested_versionsr   r   only_initial_experiencerU   r   fmtr   r   r   pagesourcesr,   current_formatsr   
source_urlsource_typer   s                                    r$   rg   zFunimationIE._real_extract   s5    $s 3((&/NOdNe-f ) h $ 1 1'MbIc 1 d-.
[[(6J
35r2q=0J262I2I*2UW[WnWnoxWy/')<)Ddd(KL%'9'Sg{=SUYWYUY&Z[";t~~m]_?`"`"&"7"7"@ 3	0D'3N 34M'M=R,R*tzz|CV/V)gmmoEW.Wucggh&7898SWWZ%;<H*14GK""=Z[#04I#Iz # [ G{{+5+C(&&CmSGSv}}vG[G[7[_`(a bI&{m59	 ' ;D
 hhw'-2G&>E''eii&789L9bPUPYPYZaPb9b)d e ''(EF O! 0#ZZ.
$jj5Rz9R&(#**4+E+E"J-Y^?_gl+K=8IJ ,F ,L M $**0={%K),  ) AHH$('.->w}}-O/B4::</P	  /)0?3	0h /3E!!Vaepz " |&&w/
*
7L!M N
 *
 	

 W^,
 7;;'78
 w{{>2
 k'++k*BC
 *
 fjj/
 [J)?@
 VZZ
%;<
 dhh{+
 w
 *
  !
" "#5#
 	
r&   c           
         t        |t              r4| j                  d| d|dd|       }| j                  ||d      \  }}}| j	                  |      D ]  \  }}}	|	j                  d      D ]  }
|
j                  d      D ]  }|j                  d	      s|j                  d
      j                         }|dk7  r|nd }|d	   t        ||j                  d      |d      d}t        |j                  dd      |dk7  r|nd |d      }||j                  |g       vs|j                  |g       j                  |          |S )Nr`   /Fr   )r   r   )rt   r   r   
textTracksr   typeFULLlabelr   )delim)rI   namer   und	SimulcastrX   )
r/   r   r   r   r   r   upperr
   
setdefaultr   )r"   r   r   rW   rr   r   r   rX   r   r   r   
text_tracksub_typecurrent_subrU   s                  r$   _get_subtitleszFunimationIE._get_subtitles  sr   gs#,,4]O1Ez$CK="Q - SG !--g'QV-WMGQ!227; 	KMAw%%	* K"(**\": KJ%>>%0 )~~f5;;=H+3v+=x4H)%0 -gz~~g7NPX`c d#K )
E)J4;{4JPT)1>D #)--b*AA!,,T26==kJKK	K  r&   )NNT)
r8   r9   r:   rj   rk   staticmethodr   r   rg   r   r=   r&   r$   rd   rd   i   s    IJ :1,7."!4
  V
#* M91,7."!4
  $56
%)*FX 3 3*Y
vr&   rd   c                   P    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 Zd Zy)FunimationShowIEzfunimation:showzn(?P<url>https?://(?:www\.)?funimation(?:\.com|now\.uk)/(?P<locale>[^/]+)?/?shows/(?P<id>[^/?#&]+))/?(?:[?#]|$)z4https://www.funimation.com/en/shows/sk8-the-infinity1315000zSK8 the Infinity)rC   rE      rF   T)rI   rJ   playlist_countrK   z=https://www.funimation.com/shows/ouran-high-school-host-club/39643zOuran High School Host Club   c                 P    | j                   s| j                         t        _         y y rO   rP   rQ   s    r$   rR   z!FunimationShowIE._real_initializeD  rS   r&   c           
      r     j                  |      j                         \  }} j                  d|d j                  d|xs d|      } j                  d|j	                  d      z  |      }t        |ddd	 d
f      }dt        |d         |d   t         fdt        |d       D              dS )Nz1https://title-api.prd.funimationsvc.com/v2/shows/z?region=z&deviceType=web&locale=rZ   z_https://prod-api-funimationnow.dadcdigital.com/api/funimation/episodes/?limit=99999&title_id=%srC   r   .c                 .    t        j                  d|       S )Nz(?i)mostRecent[AS]vod)rematch)r   rX   s     r$   r   z0FunimationShowIE._real_extract.<locals>.<lambda>R  s    RjlmIn r&   itemplaylistr   c           	   3      K   | ]\  }j                  d |j                  d      t        j                         |j                  d      |j                  d             ^ yw)r   episodeSlugr   episodeNameN)rc   r   r?   re   ).0vod_itembase_urlr"   s     r$   	<genexpr>z1FunimationShowIE._real_extract.<locals>.<genexpr>X  s[      "\  'm)DEGWG^G^G`LL-x||M/JL"\s   A"A%c                 &    | j                  dd      S )NepisodeOrderr   )r   r   s    r$   r   z0FunimationShowIE._real_extract.<locals>.<lambda>\  s    nVX@Y r&   )key)_typerC   rE   entries)	ra   groupsr!   r<   r   r   r   r   sorted)r"   rI   r\   rr   	show_info
items_info	vod_itemsr  s   `      @r$   rg   zFunimationShowIE._real_extractH  s    '+'<'<S'A'H'H'J$&*''4<<49:DF	 ((mmmD!"#-/
 !gs<npv-wx	  io.v&! "\ !'y6Y Z	"\ \		
 		
r&   Nrh   r=   r&   r$   r   r   )  sj    G CJ F'
 T

 O2
 T
F.:
r&   r   )r   r   r   commonr   networking.exceptionsr   utilsr   r   r	   r
   r   r   r   r   r   r   r   r   r   r?   rd   r   r=   r&   r$   <module>r     sb     	  ! -    } @/q' /qd}# }@4
' 4
r&   