
    iR                         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 d dlZd dl	m
Z
  e
       ZdZdZdZdZdZd	Zd
ZdZdZ G d d      Z G d d      Z e       Zy)    N)AnyListDict)Consoleconfig.json
login.jsonzdomains.jsonz.github/script/domains.jsonremote_cdm.jsonz]https://raw.githubusercontent.com/Arrowar/StreamingCommunity/refs/heads/main/conf/config.jsonz\https://raw.githubusercontent.com/Arrowar/StreamingCommunity/refs/heads/main/conf/login.jsonzQhttps://raw.githubusercontent.com/Arrowar/SC_Domains/refs/heads/main/domains.jsonzahttps://raw.githubusercontent.com/Arrowar/StreamingCommunity/refs/heads/main/conf/remote_cdm.jsonc                      e Zd ZddedededefdZedfdeded	ed
edef
dZ	ded	edefdZ
ddeded
edefdZddeded
edefdZddeded
edefdZddeded
ee   dee   fdZddeded
edefdZdedededdfdZy)ConfigAccessorconfig_dictcachecache_prefixcache_enabledc                 <    || _         || _        || _        || _        y N)_config_dict_cache_cache_prefix_cache_enabled)selfr   r   r   r   s        T/home/nidran/Documenti/script/streaming-community/StreamingCommunity/utils/config.py__init__zConfigAccessor.__init__   s!    ')+    Nsectionkey	data_typedefaultreturnc           	         | j                    d| d| }| j                  r|| j                  v r| j                  |   S || j                  vr ||S t	        d| d| j                    d      || j                  |   vr#||S t	        d| d| d| j                    d      | j                  |   |   }| j                  ||      }| j                  r|| j                  |<   |S )a  
        Read a value from the configuration with caching.
        
        Args:
            section (str): Section in the configuration
            key (str): Key to read
            data_type (type, optional): Expected data type. Default: str
            default (Any, optional): Default value if key is not found. Default: None
            
        Returns:
            Any: The key value converted to the specified data type, or default if not found
        .z	Section 'z' not found in z configurationzKey 'z' not found in section '' of )r   r   r   r   
ValueError_convert_to_data_type)r   r   r   r   r   	cache_keyvalueconverted_values           r   getzConfigAccessor.get$   s    ))*!G9AcU;	 9#;;;y)) $+++"y	ASAS@TTbcddd''00"uSE)A'%PTPbPbOccqrss !!'*3/44UIF %4DKK	"r   r%   c           	         	 |t         u rt        |      S |t        u rt        |      S |t        u r-t        |t              r|j                         dv S t        |      S |t        u rRt        |t              r|S t        |t              r-|j                  d      D cg c]  }|j                          c}S |gS |t        u r4t        |t              r|S t        dt        |      j                   d      |S c c}w # t        $ rP}d|j                   d| d| }t        j                  d|        t        d|j                   d| d|       d	}~ww xY w)
z
        Convert the value to the specified data type.
        
        Args:
            value (Any): Value to convert
            data_type (type): Target data type
            
        Returns:
            Any: Converted value
        )yestruet1,zCannot convert z to dictzError converting: z to value 'z' with error: [red]N)intfloatbool
isinstancestrlowerlistsplitstripdictr"   type__name__	Exceptionconsoleprint)r   r%   r   iteme	error_msgs         r   r#   z$ConfigAccessor._convert_to_data_typeL   sW   	kC5z!e#U|#d"eS) ;;=,EEEE{"d"eT* LeS)5:[[5EFTDJJLFFwd"eT* L ?4;3G3G2H!QRR G  	k,Y-?-?,@E7R`ab`cdIMME)-.1)2D2D1E[QVPWWefgehijj	ksX   C: C: )C: 
C: C: 7#C: C51C: 4C: 7C: #C: 5C: :	EAEEc                 4    | j                  ||t        |      S )z'Read an integer from the configuration.r   )r'   r/   r   r   r   r   s       r   get_intzConfigAccessor.get_intw   s    xxc7x;;r   c                 4    | j                  ||t        |      S )z$Read a float from the configuration.rB   )r'   r0   rC   s       r   	get_floatzConfigAccessor.get_float{   s    xxeWx==r   c                 4    | j                  ||t        |      S )z&Read a boolean from the configuration.rB   )r'   r1   rC   s       r   get_boolzConfigAccessor.get_bool       xxdGx<<r   c                 4    | j                  ||t        |      S )z#Read a list from the configuration.rB   )r'   r5   rC   s       r   get_listzConfigAccessor.get_list   rI   r   c                 4    | j                  ||t        |      S )z)Read a dictionary from the configuration.rB   )r'   r8   rC   s       r   get_dictzConfigAccessor.get_dict   rI   r   c           	      6   	 || j                   vri | j                   |<   || j                   |   |<   | j                   d| d| }|| j                  |<   y# t        $ r:}d| d| d| j                   d| }t        j                  d|        Y d}~yd}~ww xY w)z
        Set a key in the configuration and update cache.
        
        Args:
            section (str): Section in the configuration
            key (str): Key to set
            value (Any): Value to associate with the key
        r    zError setting key 'z' in section 'r!   z configuration: r.   N)r   r   r   r;   r<   r=   )r   r   r   r%   r$   r?   r@   s          r   set_keyzConfigAccessor.set_key   s    	/d///-/!!'*.3Dg&s+  --.ay#?I%*DKK	" 	/-cU.	tOaOaNbbrstruvIMME)-..	/s   AA 	B0BB)Tr   )r:   
__module____qualname__r   r3   r1   r   r9   r   r'   r#   r/   rD   r0   rF   rH   r   rK   r8   rM   rO    r   r   r   r      sE   ,D , ,S ,Y] , =@PT &3 &S &T &# &Y\ &P)k3 )k4 )kC )kV<s < <s <c <> >3 > >% >= =# = = == =# =S	 =TRUY == =# = = =/s / /S /T /r   r   c                       e Zd ZddZddZddZddZddZddZdd	Z	dd
Z
dedededdfdZddZddZddZddZddZddZddZddZy)ConfigManagerr   Nc                 
   d| _         t        t        dd      r3t        j                  j                  t        j                        | _         nt        j                         | _         t        j                  j                  | j                   d      | _	        t        j                  j                  | j                        sCt        j                  | j                  d       t        j                  d| j                          t        j                  j                  | j                  t              | _        t        j                  j                  | j                  t               | _        t        j                  j                  | j                  t$              | _        t        j                  j                  | j                   t(              | _        t        j                  j                  | j                  t,              | _        i | _        i | _        i | _        i | _        i | _        d| _        t=        | j0                  | j8                  d| j:                        | _        t=        | j2                  | j8                  d	| j:                        | _         t=        | j4                  | j8                  d
| j:                        | _!        t=        | j6                  | j8                  d| j:                        | _"        d| _#        | jI                          y)z*Initialize the ConfigManager with caching.NfrozenFconfT)exist_okz[green]Created conf directory: configlogindomain
remote_cdm)%	base_pathgetattrsysospathdirname
executablegetcwdjoin	conf_pathexistsmakedirsr<   r=   CONFIG_FILENAMEconfig_file_pathLOGIN_FILENAMElogin_file_pathDOMAINS_FILENAMEdomains_pathGITHUB_DOMAINS_PATHgithub_domains_pathREMOTE_CDM_PATHremote_cdm_path_config_data_login_data_domains_data_remote_cdm_datar   r   r   rY   rZ   r[   r\   fetch_domain_onlineload_all_configsr   s    r   r   zConfigManager.__init__   s    3%(WW__S^^<DNYY[DN dnnf= ww~~dnn-KK6MM;DNN;KLM !#T^^_ M!ww||DNNNKGGLL9IJ#%77<<@S#T !ww||DNNOL  " &(
" %T%6%6

HdNaNab#D$4$4djj'4K^K^_
$T%7%7XtObObc()>)>

LZ^ZmZmn $( r   c                     | j                          | j                          | j                          | j                          | j	                          y)zLoad all configuration files.N)_load_config_load_login_update_settings_from_config_load_site_data_load_remote_cdmry   s    r   rx   zConfigManager.load_all_configs   s>    ))+r   c                 4   t         j                  j                  | j                        sXt        j                  d| j                          t        j                  d       | j                  t        | j                  d       	 t        | j                  d      5 }| j                  j                          | j                  j                  t        j                  |             ddd       | j                          y# 1 sw Y   xY w# t        j                  $ r;}t        j                  dt!        |              | j#                          Y d}~yd}~wt$        $ r;}t        j                  dt!        |              | j#                          Y d}~yd}~ww xY w)z!Load the main configuration file.z,[red]WARNING: Configuration file not found: &[yellow]Downloading from repository...r   rNz [red]Error parsing config JSON: z"[red]Error loading configuration: )r`   ra   rg   rj   r<   r=   _download_fileCONFIG_DOWNLOAD_URLopenrs   clearupdatejsonload_precache_config_valuesJSONDecodeErrorr3   _handle_config_errorr;   r   fr?   s      r   r{   zConfigManager._load_config   s/   ww~~d334MMHI^I^H_`aMMBC 3T5J5JMZ	(d++S1 7Q!!'')!!((167
 ((*7 7 ## 	(MM<SVHEF%%'' 	(MM>s1vhGH%%''	(s=   D A	C;"D ;D D F1EF1FFc                 
   t         j                  j                  | j                        sYt        j                  d| j                          t        j                  d       	 | j                  t        | j                  d       	 t        | j                  d      5 }| j                  j                          | j                  j                  t        j                  |             ddd       y# t        $ rZ}t        j                  dt        |              t        j                  d       | j                  j                          Y d}~yd}~ww xY w# 1 sw Y   yxY w# t        j                   $ rE}t        j                  dt        |              | j                  j                          Y d}~yd}~wt        $ rE}t        j                  d	t        |              | j                  j                          Y d}~yd}~ww xY w)
"Load the login configuration file.z'[yellow]WARNING: Login file not found: r   r   z'[yellow]Could not download login.json: z-[yellow]Creating empty login configuration...Nr   z[red]Error parsing login JSON: z([red]Error loading login configuration: )r`   ra   rg   rl   r<   r=   r   CONFIG_LOGIN_DOWNLOAD_URLr;   r3   rt   r   r   r   r   r   r   r   r?   r   s      r   r|   zConfigManager._load_login   s   ww~~d223MMCDDXDXCYZ[MMBC##$=t?S?SUab	%d**C0 6A  &&(  ''		!56 6   GAxPQMN  &&(	6 6 ## 	%MM;CF8DE""$$ 	%MMDSVHMN""$$	%\   "!C, E A	E#E ,	E5AE

EEE E H1;F11H=;G==Hc                 
   t         j                  j                  | j                        sYt        j                  d| j                          t        j                  d       	 | j                  t        | j                  d       	 t        | j                  d      5 }| j                  j                          | j                  j                  t        j                  |             ddd       y# t        $ rZ}t        j                  dt        |              t        j                  d       | j                  j                          Y d}~yd}~ww xY w# 1 sw Y   yxY w# t        j                   $ rE}t        j                  dt        |              | j                  j                          Y d}~yd}~wt        $ rE}t        j                  d	t        |              | j                  j                          Y d}~yd}~ww xY w)
r   z,[yellow]WARNING: Remote cdm file not found: r   r	   z,[yellow]Could not download remote_cdm.json: z2[yellow]Creating empty remote cdm configuration...Nr   z$[red]Error parsing remote cdm JSON: z-[red]Error loading remote cdm configuration: )r`   ra   rg   rr   r<   r=   r   REMOTE_CDM_DOWNLOAD_URLr;   r3   rv   r   r   r   r   r   r   r   s      r   r   zConfigManager._load_remote_cdm	  s   ww~~d223MMHI]I]H^_`MMBC##$;T=Q=QSde	*d**C0 ;A%%++-%%,,TYYq\:; ;   LSQRVHUVRS%%++-	; ; ## 	*MM@QIJ!!'')) 	*MMI#a&RS!!''))	*r   c                 .   ddt         fddt         fddt        fddt        fddt        fddt        fdd	t        fdd
t        fddt        fddt         fddt         fddt        fddt        fg}d}|D ]p  \  }}}	 d| d| }|| j                  v rS|| j                  |   v rB| j                  |   |   }| j
                  j                  ||      }|| j                  |<   |dz  }r y# t        $ r(}	t        j                  d| d| d|	        Y d}	~	d}	~	ww xY w)z-Pre-cache commonly used configuration values.M3U8_DOWNLOADthread_countretry_countconcurrent_downloadcleanup_tmp_folderM3U8_CONVERSIONuse_gpuparam_videoparam_audioparam_finalREQUESTSverifytimeout	max_retry	use_proxyproxyr   zconfig.r       zFailed to precache z: N)r/   r1   r3   r8   rs   rY   r#   r   r;   loggingwarning)
r   common_keyscached_countr   r   r   r$   r%   r&   r?   s
             r   r   z%ConfigManager._precache_config_values#  sa    nc2mS13T:2D9	40s3s3s34(C(c*d+$'
  '2 	L#GS)
L%gYau5	d///C4;L;LW;U4U --g6s;E&*kk&G&Gy&YO,;DJJy) A%L	L  L"5gYauBqc JKKLs   7A)C##	D,DDc                    t         j                  d       | j                  t        | j                  d       	 t        | j                  d      5 }| j                  j                          | j                  j                  t        j                  |             ddd       | j                          | j                          t         j                  d       y# 1 sw Y   ?xY w# t        $ rU}t         j                  dt        |              t         j                  d       t        j                   d       Y d}~yd}~ww xY w)	zAHandle configuration errors by downloading the reference version.z9[yellow]Attempting to retrieve reference configuration...r   r   Nz2[green]Reference configuration loaded successfullyz#[red]Critical configuration error: z7[red]Unable to proceed. The application will terminate.r   )r<   r=   r   r   rj   r   rs   r   r   r   r   r   r}   r;   r3   r_   exitr   s      r   r   z"ConfigManager._handle_config_errorC  s    QR/1F1FV	d++S1 7Q!!'')!!((167
 ((*--/MMNO7 7  	MM?AxHIMMSTHHQKK	s1   C! A	C=C! CC! !	D?*AD::D?c                 j    | j                   j                  di       }|j                  dd      | _        y)z4Update internal settings from loaded configurations.DEFAULTrw   TN)rs   r'   rw   )r   default_sections     r   r}   z*ConfigManager._update_settings_from_configX  s2    ++//	2> $3#6#67Ld#S r   url	file_path	file_namec                 *   	 t        j                  |dddi      }|j                  dk(  rft        |d      5 }|j	                  |j
                         ddd       t        |j
                        dz  }t        j                  d	| d
|dd       yd|j                   d|j                  dd  }t        j                  d|        t        |      # 1 sw Y   xY w# t        $ r*}t        j                  dt        |       d|         d}~ww xY w)zDownload a file from a URL.       @
User-AgentMozilla/5.0r   headers   wbNi   z[green]Download complete: z (z.2fz KB)zHTTP Error: z, Response: d   z[red]Download failed: z[red]Download error: z
 for url: )httpxr'   status_coder   writecontentlenr<   r=   textr;   r3   )	r   r   r   r   responser   	file_sizer@   r?   s	            r   r   zConfigManager._download_file_  s   	yycL-;XYH##s*)T* .aGGH,,-. 0 01D8	 :9+R	RUVZ[\*8+?+?*@X]][_\_M`Lab	 6ykBC	**. .  	MM1#a&C5IJ	s5   5C C=C AC CC 	D(%DDc                 ^    | j                   r| j                          y| j                          y)z4Load site data based on fetch_domain_online setting.N)rw   _load_site_data_online_load_site_data_from_filery   s    r   r~   zConfigManager._load_site_datar  s#    ##'')**,r   c                    ddi}	 t        j                  t        d|      }|j                  dk(  rT| j                  j                          | j                  j                  |j                                | j                          yt        j                  d|j                   d|j                  dd	         | j                          y# t        j                  $ r;}t        j                  d
t        |              | j                          Y d}~yd}~wt        $ r;}t        j                  dt        |              | j                          Y d}~yd}~ww xY w)z>Load site data from GitHub and update local domains.json file.r   r   r   r   r   z![red]GitHub request failed: HTTP z, Nr   z%[red]Error parsing JSON from GitHub: z[red]GitHub connection error: )r   r'   DOMAINS_DOWNLOAD_URLr   ru   r   r   r   %_save_domains_to_appropriate_locationr<   r=   r   _handle_site_data_fallbackr   r3   r;   )r   r   r   r?   s       r   r   z$ConfigManager._load_site_data_onliney  s    -
	.yy!5sGTH##s*""((*""))(--/: ::<  A(BVBVAWWYZbZgZghlilZmYnop//1## 	.MMA#a&JK++-- 	.MM:3q6(CD++--	.s+   A>C AC E1DE1EEc                    	 t        | j                  dd      5 }t        j                  | j                  |dd       ddd       y# 1 sw Y   yxY w# t
        $ r+}t        j                  dt        |              Y d}~yd}~ww xY w)	z#Save domains to the conf directory.wutf-8encoding   Findentensure_asciiNz%[red]Could not save domains to file: )	r   rn   r   dumpru   r;   r<   r=   r3   )r   r   
save_errors      r   r   z3ConfigManager._save_domains_to_appropriate_location  sz    	Ud''w? O1		$,,aNO O O 	UMMA#j/ARSTT	Us3   A $AA AA A 	B!BBc                    	 t         j                  j                  | j                        rt	        | j                  dd      5 }| j
                  j                          | j
                  j                  t        j                  |             ddd       t        | j
                  t              rt        | j
                        nd}yt         j                  j                  | j                        rt        j                  d| j                          t	        | j                  dd      5 }| j
                  j                          | j
                  j                  t        j                  |             ddd       t        | j
                  t              rt        | j
                        nd}t        j                  d| d       yt        j                  d	       | j
                  j                          y# 1 sw Y   kxY w# 1 sw Y   xY w# t         $ rE}t        j                  d
t#        |              | j
                  j                          Y d}~yd}~ww xY w)z,Load site data from local domains.json file.r   r   r   Nr   z#[cyan]Fallback domain path: [green]z-[green]Domains loaded from GitHub structure: z streaming servicesz [cyan]Domain path: [red]Disabledz[red]Local domain file error: )r`   ra   rg   rn   r   ru   r   r   r   r   r2   r8   r   rp   r<   r=   r;   r3   )r   r   
site_countr?   s       r   r   z'ConfigManager._load_site_data_from_file  s   	'ww~~d//0$++S7C <q&&,,.&&--diil;< 9C4CUCUW[8\S!3!34bc
 8 89 CDD\D\C]^_$22C'J <a&&,,.&&--diil;< 9C4CUCUW[8\S!3!34bc
 Mj\Ylmn @A""((*#< << <  	'MM:3q6(CD$$&&	'sX   AH A	G59H A#H )A	H2AH /H 5G?:H HH 	I;IIc                 j   t         j                  j                  | j                        rt        j                  d       	 t        | j                  dd      5 }| j                  j                          | j                  j                  t        j                  |             ddd       t        j                  d       yt         j                  j                  | j                        rt        j                  d       	 t        | j                  dd      5 }| j                  j                          | j                  j                  t        j                  |             ddd       t        j                  d	       yt        j                  d       | j                  j                          y# 1 sw Y   xY w# t        $ r,}t        j                  dt        |              Y d}~+d}~ww xY w# 1 sw Y   xY w# t        $ r+}t        j                  d
t        |              Y d}~d}~ww xY w)z+Handle site data fallback in case of error.z8[yellow]Attempting fallback to conf domains.json file...r   r   r   Nz*[green]Fallback to conf domains successfulz#[red]Conf domains fallback failed: zD[yellow]Attempting fallback to GitHub structure domains.json file...z.[green]Fallback to GitHub structure successfulz'[red]GitHub structure fallback failed: z6[red]No local domains.json file available for fallback)r`   ra   rg   rn   r<   r=   r   ru   r   r   r   r   r;   r3   rp   )r   r   fallback_errors      r   r   z(ConfigManager._handle_site_data_fallback  s   77>>$++,MMTU[$++S7C <q&&,,.&&--diil;< JK 77>>$223MM`a_$22C'J <a&&,,.&&--diil;< NO 	NO  ")< <
  [ CCDWCXYZZ[< <
  _ GNH[G\]^^_sb    F: A	F-!F: >G> A	G2G> -F72F: :	G/!G**G/2G;7G> >	H2!H--H2c                     	 t        | j                  d      5 }t        j                  | j                  |d       ddd       y# 1 sw Y   yxY w# t
        $ r"}t        j                  d|        Y d}~yd}~ww xY w)z$Save the main configuration to file.r   r   r   Nz![red]Error saving configuration: )r   rj   r   r   rs   r;   r<   r=   r   s      r   save_configzConfigManager.save_config  sm    	Cd++S1 :Q		$++Qq9: : : 	CMM=aSABB	C3   A #AA A	A A 	A;A66A;c                     	 t        | j                  d      5 }t        j                  | j                  |d       ddd       y# 1 sw Y   yxY w# t
        $ r"}t        j                  d|        Y d}~yd}~ww xY w)z%Save the login configuration to file.r   r   r   Nz'[red]Error saving login configuration: )r   rl   r   r   rt   r;   r<   r=   r   s      r   
save_loginzConfigManager.save_login  sm    	Id**C0 9A		$**Aa89 9 9 	IMMCA3GHH	Ir   c                    	 | j                   }t        |dd      5 }t        j                  | j                  |dd       ddd       y# 1 sw Y   yxY w# t
        $ r"}t        j                  d|        Y d}~yd}~ww xY w)	z'Save the domains configuration to file.r   r   r   r   Fr   Nz)[red]Error saving domains configuration: )rn   r   r   r   ru   r;   r<   r=   )r   target_pathr   r?   s       r   save_domainszConfigManager.save_domains  s|    	K++Kk39 OQ		$,,aNO O O  	KMMEaSIJJ	Ks4   A $A	 A 	AA A 	B A;;B )r   N)r:   rP   rQ   r   rx   r{   r|   r   r   r   r}   r3   r   r~   r   r   r   r   r   r   r   rR   r   r   rT   rT      s{    * X (.%4*4L@*T# # # $ &-.6U'6#6CI	Kr   rT   )r`   r_   r   r   typingr   r   r   r   rich.consoler   r<   ri   rk   rm   ro   rq   r   r   r   r   r   rT   config_managerrR   r   r   <module>r      s    
 
   " "    )! 3 #u z j } C/ C/LHK HKX
 r   