
    soja?                     0   d dl Z d dlZd dlmZmZ d dlmZ d dlmZmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dl m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z) d dl*m+Z+ d dl,m-Z-m.Z. dede/fdZ0dede)de/fdZ1dede2fdZ3	 	 d1de)de4e         de4e         de4e         fdZ5	 	 	 	 d2de
j6        de)d e2d!e4e4e+                  de4e         d"ede4e         ddfd#Z7	 	 	 	 d2de
j6        de)d e2d!e4e4e+                  de4e         d"ede4e         ddfd$Z8de
j6        d%e4e         ddfd&Z9de
j6        d%e4e         ddfd'Z:d3d(Z;d3d)Z<ded*e2ddfd+Z=de
j6        ddfd,Z>de
j6        d-eddfd.Z?ded/e@de/fd0ZAdS )4    N)datetime	timedelta)Message)TelegramError
RetryAfter)ContextTypes)phrases)	BaseModel)Group)	GroupChat)GroupChatAutoDelete)GroupChatEnabledDisabledFeature)GroupChatEnabledFeaturePin)GroupChatFeaturePinMessage)	GroupUser)Leaderboard)
Prediction)PredictionGroupChatMessage)User)Feature)Keyboard)full_message_senddelete_message
group_chatreturnc                     t           j                                        }|dS | j        }t	          |j                  t	          |          k    S )z
    Checks if the update is from the main group_chat
    :param group_chat: The group chat
    :return: True if the message is from the main group_chat, False otherwise
    NF)EnvMAIN_GROUP_IDgetgroupinttg_group_id)r   main_group_idr    s      !/app/src/service/group_service.pyis_main_groupr%      sI     %))++Mu#Eu !!S%7%777    featurec                     t          j        t           j        | k    t           j        |k    z            }||                                n|                                 S )z
    Checks if a feature is enabled
    :param group_chat: The group chat
    :param feature: The feature
    :return: True if the feature is enabled, False otherwise
    )r   get_or_noner   r'   is_enabled_by_default)r   r'   #group_chat_enabled_disabled_features      r$   feature_is_enabledr,   +   sf     +J*U	(	3z	A*2g=	?+ +' /6 	%%'''..000r&   c                 @    | j         t          j        S t          j        S )z
    Gets the group chat or group_chat text
    :param group_chat: The group chat
    :return: The group chat or group_chat text
    )tg_topic_idr	   
TEXT_TOPIC
TEXT_GROUPr   s    r$   get_group_or_topic_textr2   ?   s     )!!!!r&   filter_by_groupsexcluded_group_chatsc                    |g }t          |          dk    r t          j                            |          }nd}|g }t	          j                                        t          j        | k              }|                                 rd |D             }nhd t          j                                        t          j	        dk    t          j
                            d |D                       z            D             }t          j                                                                        t          t          j
        t          j        k                                  t          j	        dk    t          j	        dk    z  |z  t          j
                            d |D                       z  t          j
                            d	 |D                       z            S )
a  
    Gets the group chats with a feature enabled
    :param feature: The feature
    :param filter_by_groups: The groups to filter by
    :param excluded_group_chats: The group chats to exclude from the result
    :return: The list of group chats with the feature enabled
    Nr   Tc                     g | ]	}|j         
S  r1   .0gcfs     r$   
<listcomp>z8get_group_chats_with_feature_enabled.<locals>.<listcomp>l   s'     >
 >
 >
"CN>
 >
 >
r&   c                     g | ]}|S r7   r7   )r9   gcs     r$   r;   z8get_group_chats_with_feature_enabled.<locals>.<listcomp>p   s(     
>
 
>
 
>
 
>
 
>
 
>
r&   c                 &    g | ]}|j         j        S r7   )r   idr8   s     r$   r;   z8get_group_chats_with_feature_enabled.<locals>.<listcomp>v   s    [[[s*[[[r&   )onc                     g | ]	}|j         
S r7   r?   )r9   egcs     r$   r;   z8get_group_chats_with_feature_enabled.<locals>.<listcomp>   s    #K#K#KsCF#K#K#Kr&   c                     g | ]	}|j         
S r7   rB   )r9   cs     r$   r;   z8get_group_chats_with_feature_enabled.<locals>.<listcomp>   s    #T#T#TQAD#T#T#Tr&   )lenr   r    in_r   selectwherer'   r*   	is_activer?   not_indistinctjoinr   )r'   r3   r4   group_filter$group_chats_enabled_disabled_feature!group_chats_with_feature_disableds         r$   $get_group_chats_with_feature_enabledrQ   L   s    
q   **+;<<#!
 	(.0066'/7:	 	 ) $$&& 
>
 >
&J>
 >
 >
))
>
 
>
&((..$,L''[[6Z[[[  
>
 
>
 
>
) 			eY_4	6	6	_$"d*, |""#K#K6J#K#K#KLLN |""#T#T2S#T#T#TUU	W

 

	r&   contexttextinline_keyboardexternal_itemc                 f   K   | j                             t          | ||||||                     dS )  
    Broadcasts a message to all the chats with a feature enabled
    :param context: The context
    :param feature: The feature
    :param text: The message
    :param inline_keyboard: The outbound keyboard
    :param excluded_group_chats: The chats to exclude from the broadcast
    :param external_item: The external item to save the group chat message
    :param filter_by_groups: The groups to filter by
    )rT   r4   rU   r3   N)applicationcreate_task'broadcast_to_chats_with_feature_enabled)rR   r'   rS   rT   r4   rU   r3   s          r$   0broadcast_to_chats_with_feature_enabled_dispatchr[      sT      ( ##/+!5'-	
 	
 	

 
 
 
 
r&   c                   K   |t           j        t           j        fv r&|$t          d|                                z             |g }t          |||          }|                                }|rWt          t          j	                    
                    t          j        |k                        }	t          | |	           d{V  |D ]}
|
}
	 t          | |||
           d{V }|t           j        u r?t                      }|}||_        |
|_        |j        |_        |                                 n0|t           j        u r"|}|j        |_        |                                 nh# t&          $ r[}t)          j        d|                                 d|
j         d|            t/          |
t1          |                     Y d}~d}~ww xY w|s	t3          j        t2          j        |
k    t2          j        |k    z            du}|r|                                 n|                                }|smt9          d          D ]}	 |                    d	
           d{V  t                      }|
|_        ||_        |j        |_        |                                  n1# t<          $ r}|dk    r^t)          j        d|                                 d|
j         d|j         d           tA          j!        |j                   d{V  Y d}~t)          j        d|                                 d|
j         d|            t/          |
t1          |                     Y d}~$d}~wt&          $ r\}t)          j        d|                                 d|
j         d|            t/          |
t1          |                     Y d}~ nd}~ww xY wdS )rW   Nz/External item cannot be None if the feature is )r4   r3   )keyboardr   zFailed to send z message to group chat z:    T)disable_notificationr   zRate limited while pinning z message in group chat z, retrying in szFailed to pin z after retrying: )"r   
PREDICTIONLEADERBOARD
ValueErrorget_descriptionrQ   is_pinnablelistr   rH   rI   r'   unpin_feature_messages_dispatchr   r   
predictionr   
message_idsaver   loggingwarningr?   save_group_chat_errorstrr   r)   is_pinned_by_defaultrangepinr   retry_afterasynciosleep)rR   r'   rS   rT   r4   rU   r3   group_chatsfeature_is_pinnablemessages_to_unpinr   messageprediction_group_chat_messagetehas_pin_record
should_pinattemptpin_messageras                      r$   rZ   rZ      s%     ( 7%w':;;;@U=@W@W@Y@YY
 
 	
 #G&:M]$ $ $K "--//  J ?C&-//55*2g= ?
 ?

 .g7HIIIIIIIII! L L
 *
	%6J& & &            G ',,,.00 . -:;H-8;E-8;B;M-8-224444G///-:+2+=(""$$$ 	 	 	O)'"9"9";"; ) )=) )$&) )   "*c"gg666HHHH	 # 	 '2+6*D-5@B  	 	 3Ad,,....gFbFbFdFd 	  	
 Qxx 	 	Gkktk<<<<<<<<<:T:V:V)3&&-#)0);&  """ ; ; ;a<<OUg6M6M6O6O U U&0mU UCE>U U U   "-777777777HHHH<W%<%<%>%> < <!}< <79< <   &j#b''::::::::    -W%<%<%>%> - -!}- -(*- -   &j#b'':::ML LsH   BE%%
G
/AGG
AJ##
O-AM(AM((O5AOOrw   c                 Z   K   | j                             t          | |                     dS zy
    Unpins the feature messages
    :param context: The context
    :param messages_to_unpin: The messages to unpin
    N)rX   rY   unpin_feature_messages)rR   rw   s     r$   rg   rg   &  s1       ##$:7DU$V$VWWWWWr&   c                   K   |D ]}|j         }|j        }	 | j                            |j        |j                   d{V  n4# t          $ r'}t          |t          |                     Y d}~nd}~ww xY w|	                                 dS r   )
r   r    botunpin_chat_messager"   ri   r   rm   rn   delete_instance)rR   rw   r~   r   r    rz   s         r$   r   r   2  s       ) & & + 6
!'	7+001BKDZ[[[[[[[[[[ 	7 	7 	7!*c"gg66666666	7 	##%%%%& &s   +A
A3A..A3c                     t           j                                        } t          j        d                              t          j        t          j                    t          |           z
  k               
                                 t          j        d                              t          j        t          j                    t          |           z
  k               
                                 t                       dS )z9
    Deactivates the inactive groups and group chats
    FrJ   daysN)r   INACTIVE_GROUP_DAYSget_intr   updaterI   last_message_dater   nowr   executer   deactivate_inactive_group_usersinactive_dayss    r$   deactivate_inactive_group_chatsr   F  s    
 +3355M 	u%%%	u&):W:W:W)WW	X	X	 	5)))	y*X\^^i]>[>[>[-[[	\	\	 $%%%%%r&   c                     t           j                                        } t          j        d                              t          j        t          j                    t          |           z
  k               
                                 t          j        d                              t          j        t          j                    t          |           z
  k               
                                 dS )z.
    Deactivates the inactive group users
    Fr   r   N)r   INACTIVE_GROUP_USER_DAYSr   r   r   rI   r   r   r   r   r   r   r   s    r$   r   r   ]  s    
 088::M 	5)))	y*X\^^i]>[>[>[-[[	\	\	 	e$$$	t%9V9V9V(VV	W	W	r&   errorc                     t          j                    | _        || _        |                                  | j        }t          j                    |_        ||_        |                                 dS )zn
    Saves the error for the group chat
    :param group_chat: The group chat
    :param error: The error
    N)r   r   last_error_datelast_error_messagerj   r    )r   r   r    s      r$   rm   rm   q  sY     "*J$)J!OO#E$LNNE$E	JJLLLLLr&   c                   K   t          j                                        t           j        t	          j                    k                                   d          }|D ]*}| j                            t          | |                     +dS )z>
    Auto delete messages
    :param context: The context
       N)
r   rH   rI   delete_dater   r   limitrX   rY   auto_delete_process)rR   auto_deletesauto_delete_items      r$   auto_deleter     s       	"$$	".?	@	@	r  ) X X''(;GEU(V(VWWWWX Xr&   r   c                   K   |j         }t          ||j                  r?t          j                    t          d          z   |_        |                                 dS 	 t          | ||j        d           d{V  n4# t          $ r'}t          |t          |                     Y d}~nd}~ww xY w|                                 dS )zf
    Auto delete process
    :param context: The context
    :param auto_delete_item: The message
       )minutesNT)rR   r   ri   is_auto_delete)r    _is_message_for_active_challengeri   r   r   r   r   rj   r   r   rm   rn   r   )rR   r   r   rz   s       r$   r   r     s      -7J'
4D4OPP  (0|~~	!8L8L8L'L$3!'2	
 
 
 	
 	
 	
 	
 	
 	
 	
 	
  3 3 3j#b''222222223 $$&&&&&s   A> >
B/B**B/ri   c                     ddl m} |                    |j        | k    |j        |k    z            }|dS |                                rdS |j        dS dS )a  
    Check if a message is the group invite for a challenge that shouldn't be auto-deleted yet:
    still waiting to be accepted/rejected (or its 30-second confirmation window to expire), or
    still being actively played.

    An open/global challenge (no specific opponent, "Challenge anyone") is the one exception:
    once the challenger uses "Start immediately as global", the game moves to being played in
    private chat, so this group message is safe to delete right away without waiting for that
    game to finish - global_challenger_start_date is only ever set by that action, so its
    presence is used as the signal here
    :param group_chat: The group chat the message is in
    :param message_id: The message id
    :return: True if the message should NOT be auto-deleted yet
    r   )GameNFT)src.model.Gamer   r)   r   ri   is_finishedglobal_challenger_start_date)r   ri   r   games       r$   r   r     sy      $#####((	J	&4?j+HI D |u u(4u4r&   )NN)NNNN)r   N)Brs   rk   r   r   src.tg_compatr   src.tg_compat.errorr   r   src.tg_compat.extr   resources.EnvironmentEnvironmentr   	resourcesr	   src.model.BaseModelr
   src.model.Groupr   src.model.GroupChatr   src.model.GroupChatAutoDeleter   )src.model.GroupChatEnabledDisabledFeaturer   $src.model.GroupChatEnabledFeaturePinr   $src.model.GroupChatFeaturePinMessager   src.model.GroupUserr   src.model.Leaderboardr   src.model.Predictionr   $src.model.PredictionGroupChatMessager   src.model.Userr   src.model.enums.Featurer   src.model.pojo.Keyboardr   src.service.message_servicer   r   boolr%   r,   rn   r2   rf   rQ   DEFAULT_TYPEr[   rZ   rg   r   r   r   rm   r   r   r!   r   r7   r&   r$   <module>r      s     ( ( ( ( ( ( ( ( ! ! ! ! ! ! 9 9 9 9 9 9 9 9 * * * * * * # # # # # #       ) ) ) ) ) ) ! ! ! ! ! ! ) ) ) ) ) ) = = = = = = U U U U U U K K K K K K K K K K K K ) ) ) ) ) ) - - - - - - + + + + + + K K K K K K       + + + + + + , , , , , , I I I I I I I I8i 8D 8 8 8 89 w 4    (
"	 
"c 
" 
" 
" 
" %),0; ;;5k; y/; 
)_	; ; ; ;D -1,0#$( &  $x.)	
 y/  5k 
   J -1,0#$(x x&xx x $x.)	x
 y/x x 5kx 
x x x xv	X&	X;?@Z;[	X		X 	X 	X 	X&&&;?@Z;[&	& & & &(& & & &.   (i      "X|8 XT X X X X"'&':M'	' ' ' '@  PT      r&   