
    chc                     ~    d dl Z d dlZd dlZd dlmZ d dlT d dlZ G d dej	        j
        j        j                  ZdS )    N)Response)*c                   R    e Zd Zej        j        j        j        j        ddgz   Zd Z	d Z
d Zd Zd Zd Zd	 Z fd
Z fdZd Zd Zd ZddZedd            Ze                    dej                  ZddZe eddd          dd                        Zdd fd
Z  xZ!S )CmfPluginGitsyncsync_repo_listc           
      4   t           j        }d| dt          j                            | j        j        j                   dt          j                            | j        j	        j                   dt          j                            | j	        j                   S )Nzhttps://z/pub/webhook?token=z&name=z&plugin=)
configAPP_FQDNurllibparsequoteplugintokenvaluewebhookcode)selfhostnames     &./modules/git/models/cmf_plugin_git.pywebhook_urlzCmfPluginGit.webhook_url   s    ?=( = =l(():)@AA= =\''(9(?@@= = |))$)/::= = 	=    c                     | j         j        S N)idr   r   s    r   webhook_ext_namezCmfPluginGit.webhook_ext_name   s    w}r   c                 V   |                                 D ]\  }}||j        v r	 |dk    r|                    dd          }t          |||           =# t          $ rI}|dk    r7dt          |          v r&t          ||d            t          |  d|            n|Y d }~d }~ww xY w|S )Nauthor_emailz@@@u6   Неправильный формат ввода emailuN   ::sync: author_email. Неправильный формат ввода email: )itemsfieldsreplacesetattrCmfValidationErrorstrprint)r   commitcommit_datakeyr   es         r   _set_commit_datazCmfPluginGit._set_commit_data   s    %++-- 	  	 JCfm##
 n,, %dC 8 8FC////)      n,,1impqrmsms1s1sT222||uz||}}}} ~}}}}  $ s   -A
B%?B  B%c                 
   t                               |  d           |                     g d           |                                 }	 |                                }nR# t
          $ rE t          d           t          t          j                   t          t          j	        d            w xY w|
                    dd          }t                              | j         dd	d
          5  t                               |  d|d         d          d|d         d          d           t          j        
                    | |d         d                   }d t          j                            | |ddg          D             }|
                    dg           D ]}|d         }|
                    |          }	|	s1t          |  d|            t                              | ||          }	|                                D ]\  }
}|
|	j        v rt)          |	|
|            t                                          5  |	                                 d d d            n# 1 swxY w Y   i }|
                    d          }|rS|D ]-}t          j                            | |d                   r nt                              | |          }|                     ||          }t                                          5  |                                 d d d            n# 1 swxY w Y   |                     |j        j        dg          D ]f}|                    |j        j        |          }|j                            |           t          |  d |j         j        d d!          d"| d#           g/t          |  d$tC          |           d#           |"                                D ]}t          j#        $                    |d%d&           t                                          5  |                    d'           d d d            n# 1 swxY w Y   t          j#        $                    |d%d(           |
                    d)g           D ]}|d         }t          j%        
                    | ||g d*+          }|s1t          |  d,|            t          %                    | ||-          }d.|_&        |                                D ]\  }
}|
|j        v rt)          ||
|            t                                          5  |                                 d d d            n# 1 swxY w Y   	 d d d            n# 1 swxY w Y   |S )/Nz.webhook_call: start)
projectsplugin.ext_tokenplugin.tokenplugin.ext_urlplugin.verify_ssltyper   webhook_ext_idwebhook_insecure_sslwebhook_secretzWebhook error, call params:T)flushresponse ::lock::sync,     timeoutblocking_timeoutz$.webhook_call: update data for repo reponame(ext_id))
git_pluginrC   c                 (    i | ]}|j         j        |S  rA   r   .0branchs     r   
<dictcomp>z-CmfPluginGit.webhook_call.<locals>.<dictcomp>E   s2     L L L.4!6L L Lr   deletedurlrE   r@   r"   branchesz .webhook_call:   add new Branch rE   r@   rA   commitssharE   rS   rE   r@   git_commitsr"   z.webhook_call:   add bind    z to z new commits.z.webhook_call:   add new updatebefore_save	only_data
after_savemerge_requestsr   head_branchbase_branchauthor	merged_by)rE   r@   rC   r"   z'.webhook_call:   add new Merge Request rE   r@   rC   F)'gdebugload_fields_get_driverprocess_webhook_request	Exceptionr'   requestheadersdatagetcmfutilCmfLockr   models
CmfGitRepoCmfGitBranchlistr!   r"   r$   disable_aclsaveCmfGitCommitsgetr,   find_related_taskstextr   
setdefaultrV   appendrS   lenvaluesCmfAutomationCrudTrigger	crud_hookCmfGitMergeRequestrM   )r   _kwargsdriverrequest_datar8   r@   local_branchesbranch_datarA   rK   r*   r   task_to_savecommits_datar)   r(   taskmr_datarC   mrs                       r   webhook_callzCmfPluginGit.webhook_call*   si   	4---... [ [ [ 	\ 	\ 	\ !!##	!99;;LL 	 	 	/000'/"""',d++++	  ##J33 __555sUW_XX @	 @	GG U U (0U U3?3G3QU U UV V V $((DfAUV^A_(``DL L8>8K8P8P#$	57I 9Q 9K 9KL L LN  ,//
B?? 
" 
""6*'++D11 XTII4IIJJJ#00DtRV0WWF"-"3"3"5"5 4 4JCfm++U333((** " "KKMMM" " " " " " " " " " " " " " " L'++I66L Z#/ p pK *//4[QVEW/XX #00Dt0LLF!226;GGF ,,.. & && & & & & & & & & & & & & & & $ 7 78IS`Ra 7 b b p p+66tw}dKK(//777nnAQRTSTRTAUnn[_nnnoooop XXL8I8IXXXYYY$++-- X X/99$-XXX((** . .III---. . . . . . . . . . . . . . ./99$,WWWW (++,<bAA   *.22#$vUUU 3 W W  ^TRR&RRSSS22dV\2]]B"
")--// 0 0JCbi''C///((**  GGIII              g@	 @	 @	 @	 @	 @	 @	 @	 @	 @	 @	 @	 @	 @	 @	B s   
A AB.,EU88IU8IU8 I!BU89LU8LU8!L"D U8"Q9U8Q		U8Q	C1U8>UU8U##U8&U#'U88U<?U<c                     t                               d| j         d| j         dd          }|j                            t           j                                                   |                    d          }|	                                 || j
        _        | j
        	                                 t                               | j        d|| j         d| j         d| j         d| j         d	
          	                                | _        d S )Nu   Интеграция :T)rA   system
user_localF)alert u.   Интеграция с Git сервером (z).)	hook_typer   
token_userrA   rz   )rq   	CmfPersonr3   r   rg_member_ofr|   
CmfWebhookwebhook_person_groupgenerate_webhook_tokenrv   r   r   r   )r   r   r   s      r   _init_webhookzCmfPluginGit._init_webhook   s#   %%@@@TY@@Z^ & ` `
&&v'8'M'M'O'OPPP111>>! ((iI++	++2|cgcl2|2|osox2|2|2| ) ~ ~ C  C  E  E 	r   c                     | j         j        }|s?t                              d| j        d          }|                                 || _         d S d S )Ngit  )r3   rA   sync_period)r   r   rq   	CmfPluginrA   rv   r   r   s     r   _calc_pluginzCmfPluginGit._calc_plugin   sR    " 	!%%5tyd%SSFKKMMM DKKK		! 	!r   c                 R    | j         r| j        s|                                  d S d S d S r   )is_newr   r   r   s    r   _calc_webhookzCmfPluginGit._calc_webhook   sA    ; 	!t| 	!     	! 	! 	! 	!r   c                 N    t                                                      g dz   S )N)r   r3   r   )supersave_preload_fields)r   	__class__s    r   r   z CmfPluginGit.save_preload_fields   s%    ww**,,/L/L/LLLr   c                     |                                   |                                  | j        s.d                    t	          j        dd                    | _         t                      j        di |S )Nr9   >qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890   )krG   )r   r   r6   joinrandomchoicesr   rv   )r   kwargsr   s     r   rv   zCmfPluginGit.save   s    " 	"$''&. 	+ + + # #D
 uww|%%f%%%r   c           
         d }| j         dk    r| j        j        st          d|  dd           ddlm} t                                          5  | j        j                                        }d d d            n# 1 swxY w Y    ||          }n| j         d	k    r| j        j        st          d
|  dd           ddl	m} t                                          5  | j        j                                        }d d d            n# 1 swxY w Y    || j        j
        j        | j        j        j        |          }|sIt          d| j         j         d| j         j         dd                    | j         j                             |S )Ngithubu.   У плагина интеграции Github uX    не указан токен доступа в конфигурации плагина.Tabortr   )Driver)r   gitlabu.   У плагина интеграции Gitlab )rN   
ssl_verifyr   u#   Не правильно задан rB   u)   ): допустимые значения r9   )r3   r   	ext_token	cmf_alertmodules.git.githubr   ro   ru   decryptmodules.git.gitlabext_urlr   
verify_sslCmfErrorcaptionr   r   )r   r   r   r   s       r   rh   zCmfPluginGit._get_driver   s   9  ;( q dT  d  d  d  lpq q q q111111$$&& 8 8-55778 8 8 8 8 8 8 8 8 8 8 8 8 8 8V%(((FFY("";( q dT  d  d  d  lpq q q q111111$$&& 8 8-55778 8 8 8 8 8 8 8 8 8 8 8 8 8 8VK'-$+:P:V  F  	XWdi6G W W$)/ W W:<''$)BS:T:TW WX X X s$   A99A= A=DDDc                     | j                                         j        }d |_        |                                 t          | j        ddi           t          d           d S )N	is_manualT)r   u   Синхронизация запущена, она может выполняться длительное время. После завершения вы получите уведомление)r   loadr   sync_last_datetimerv   schedule_deferred_jobsync_all_pluginsr   r   s     r   r   zCmfPluginGit.sync   sz    !!##)$(!!;*=	
 	
 	
 	
 	  X  	Y  	Y  	Y  	Y  	Yr   c           	      l   t          |  d           |                     g d           |                                 }d t          j                            | g d          D             }t          |  d           	 |                                }n=# t          $ r0 t          j	        d| j
                    t          dd	
           Y nw xY w|D ]}|d         }|                    |d           }|s<t          |  d|d                     t                              | || j                  }d|_        |                                D ]\  }}||j        v rt#          |||            |                                 |j        rX|                    ||                                 |                                 | j        j        | j        | j        j                   |                                D ]>}|j        r
t          |  d|j                    d	|_        |                                 ?d S )Nz::sync: start)r/   r0   r1   r2   plugin.sync_enabledr.   r3   r   r4   r5   r6   c                 (    i | ]}|j         j        |S rG   rC   r   )rJ   r@   s     r   rL   z/CmfPluginGit.sync_repo_list.<locals>.<dictcomp>   s/     
 
 
 Kt
 
 
r   rC   rN   default_branchr   rM   	last_syncr3   rE   r"   z::sync: load reposu&   Ошика синхронизации u   Не удалось подключиться к репозиторию. Проверьте настройки подключения и повторите попытку.Tr   rC   z::sync:   add new Repo rA   )rE   rC   r3   F)r   webhook_namer4   insecure_sslsecretz::sync:   del Repo )r'   rg   rh   rq   rr   rt   available_reposCmfAuthErrorlogging	exceptionr   r   popr3   rM   r!   r"   r$   rv   r   setup_webhookr   r   r4   r   r5   r6   r~   rA   )	r   r   local_reposavalilable_repos	repo_datarC   r@   r*   r   s	            r   r   zCmfPluginGit.sync_repo_list   s   $$$%%% g g g 	h 	h 	h !!##

 
)..bbb /  
 
 
 	)))***	J%5577 	J 	J 	JPtwPPQQQ } EIJ J J J J J	J * 	^ 	^Ix(F??6400D YIIi6GIIJJJ((Ddi(XX DL'oo// . .
U$+%%D#u---IIKKKy ^$$ $ 0 0 2 2!%!6!6!8!8I\Ib!%!:4CVC\	 % ^ ^ ^  &&(( 	 	D| T99di99:::DLIIKKKK	 	s   >B 7CCNc                 	   i }d t           j                            | |ddg          D             }|                    |j        j                  D ]}|d         }|                    |d           }|s1t          |  d|            t                               | ||          }d|_        |	                                D ]\  }}	||j
        v rt          |||	            |j        r|                                 t           j                            | |d	         
          rd}
|                    |j        j        |          D ]}t           j                            | |d	         
          r n|
dz  }
t                               | |          }|                     ||          }|                                 |                     |j        j        dg          D ]<}|                    |j        j        |          }|j                            |           =|
rt          |  d|
 d|            |                                D ]Z}t           j                            |dd           |                    d           t           j                            |dd           [|                                D ]>}|j        r
t          |  d|j                    d|_        |                                 ?d t           j                            | |g d          D             }|                    |j        j        d          D ]}|d         }|                    |d           }|s1t          |  d|            t                               | ||          }d|_        |	                                D ]\  }}	||j
        v rt          |||	            |j        r|                                 |                                D ]}|j        dk    r|                    |j        j        |j         j                   }|rUt          |  d!|j                    d|_        |	                                D ]\  }}	||j
        v rt          |||	            n t          |  d"|j                    d|_        |j        r|                                 d S )#Nc                 (    i | ]}|j         j        |S rG   rH   rI   s     r   rL   z*CmfPluginGit.sync_repo.<locals>.<dictcomp>  s2     H H H*0FKvH H Hr   rM   rN   rO   rA   z::sync:   add new Branch rQ   FrS   rT   r   )rS      rU   rV   rW   z::sync:   add z new commits from Branch rY   rZ   Tr[   r]   z::sync:   del Branch c                 (    i | ]}|j         j        |S rG   r   )rJ   r   s     r   rL   z*CmfPluginGit.sync_repo.<locals>.<dictcomp>H  s1     p p p$&BIORp p pr   r_   )	only_openrC   z ::sync:   add new Merge Request rd   open)numberz::sync:   close Merge Request z::sync:   del Merge Request )!rq   rs   rt   get_branchesrC   r   r   r'   rM   r!   r"   r$   
is_changedrv   rw   rx   iter_commitsr,   ry   rz   r{   r   rV   r|   r~   r   r   rA   r   get_merge_requestsstatusget_merge_requestr   )r   r@   r   r   r   r   rA   rK   r*   r   commits_countr)   r(   r   	local_mrsr   rC   r   s                     r   	sync_repozCmfPluginGit.sync_repo	  s    H H4:4G4L4LdIu3E 5M 5G 5GH H H "..t{/@AA %	] %	]Kv&D#''d33F T>>>>???,,4d,SS"FN)//11 0 0
U&-''FC///   "''4[=O'PP M%224;3D$2OO 4 4 &++tUAS+TT E",,4,HH..v{CC 33FK4E}o3^^ 4 4D'2247=$GGD$++F33334
  ][[][[UY[[\\\ !'')) 	T 	TD+55dHmTTTIII%%%+55dHlSSSS %++-- 	 	F~ T====>>>!FNKKMMMMp p*0*C*H*Hd3m3m3m +I +o +op p p	 001Bd0SS 	 	GX&Fvt,,B ZGGvGGHHH..$TRX.YYBJ%mmoo , ,
U")##BU+++} 			 ""$$ 	 	ByF""..t{/@.YYG "JJT[JJKKK"
")--// 0 0JCbi''C///0 HH4;HHIII!
} 			!	 	r   c                 `    d }|r)t           j                            ddd|gdd|gg          }|S )NORlogin=email)filter)rq   r   rn   )clsrE   git_id	git_login	git_emailgit_namepersons          r   find_personzCmfPluginGit.find_personl  sF     	o%))$#y8QT[]`bkSl1m)nnFr   z(?P<code>[A-Z\d]+-\d+)c                 P    t           j                            ||| j                  S )u   
        Нужно в тексте найти все потенциальные коды. Можно просто все слова...
        )r"   r.   )rq   CmfTaskry   r.   )r   rz   r"   s      r   ry   zCmfPluginGit.find_related_tasksu  s#     ~00ft}0]]]r   Tz	@minutely)	only_once
system_jobscheduleFc           	      h	   dd l }t          j                            g d          D ]}t                              d| t          j                   |j        s0t                              t          j        j	         d| d           c|j        j
        }|j        sU| sSt                              d| t          j                   d	|_        |                                 t                       |j        j
        pd
}|j        r8|j        j        |k     r(t                              dt          j                   t                              t          j        j	         d|            t                              | d           	 |                                 t                       n# t&          $ r}t          j        d|           t+                       d|_        |j                                         |j        |_        | d|                                 |_        |                                 t                       Y d }~&d }~ww xY w|                                }d}d }t6                              |j         ddd          5  t          j                            |g d          D ]}	t                              | d|	            |	j        s!t                              | d|	 d           J	 t                              d|	 t          j                   |                     |	|           |	j!                                         |	                    d           # t&          $ rI}d}| d|                                 }t          j        d|           t+                       Y d }~d }~ww xY w	 d d d            n# 1 swxY w Y   |j        j        j"        rIt                              | d           d|j        _        |j        j
                            d           |s!d |_        |j                                         n3d|_        |j                                         |j        |_        ||_        |                                 t                       d S )!Nr   )r   zplugin.*r/   r0   r1   r2   r   r.   r3   r   r4   r5   r6   rW   u   Синхронизируем )levelz!.sync_all_plugins: !!! Skip sync z die no plugin configured.u   Пропускаем disabledr   ue   С последней синхронизации прошло недостаточно времениz.sync_all_plugins: Try sync z::sync_all_plugins: startzsync_repo_list %s errorerror
Fr:   r;      r=   r   r   z::sync: repo z::sync: Skip repo z (sync=False)u;   Синхронизируем гит репозиторий Tr[   zSync %s errorz& first sync Success, enable auto sync!success)#	tracebackrq   r   rt   re   rf   r   INFOr   
class_namer   sync_enabledsync_statusrv   commit_with_eventr   r   ager   rj   r   rollback_purge_eventset_nowsync_last_error_datetime
format_excsync_last_error_messagerh   ro   rp   r   rr   r   r   r   is_null)
r   r  rE   r   periodr+   r   
has_errorsr   r@   s
             r   r   zCmfPluginGit.sync_all_plugins{  so    	 !-22 ;k ;k ;k2 l l R	  R	 JGG@J@@GUUU$ *5 M M&0M M MN N N &,F' 9 888w|LLL%/"!###'-5F( V-F-JV-S-S  A  IP  IU  V  V  VGGv*5__S]__```GGz<<<===))+++!#### 	 	 	!";VDDD$&&&%,")11333282K/451Q1Q9M9M9O9O1Q1Q.!###	  ++--FJE JM!?!?!?_abb % %"-22#-jjj 3   % %D : B BD B BCCC#y %GGz$X$XT$X$X$XYYY$%GG$hbf$h$h*1, $ 8 8 8&00v>>> N22444 III5555  ) % % %)-J'($D$DI,@,@,B,B$D$DE#-ovFFF0222$HHHH%!%% % % % % % % % % % % % % % %0  -5 =:MMMNNN15
!.!',,t,<<< 7%.")113333%,")11333282K/16.KKMMMeR	  R	 sW   "F..
I8BIIA.OA.M0/O0
O	:>N>	8O>O	OO	O	)forcec                    | j                                           | j         j        |ddi|  t                      j        |d|i|S )Nr  T)r   r   deleter   )r   r  argsr   r   s       r   r  zCmfPluginGit.delete  sV    T88888uww~t;5;F;;;r   r   )NNNNN)F)"__name__
__module____qualname__modulesr   r"   cmf_plugin_gitr   api_methodsr   r   r,   r   r   r   r   r   rv   rh   r   r   r   classmethodr   recompileASCII_TASK_CODE_SEARCH_REry   staticmethodcmf_deferred_jobr   r  __classcell__)r   s   @r   r   r      s       +$3@L$P
 
K= = =     V V VpE E E ! ! !! ! !M M M M M	& 	& 	& 	& 	&  6Y Y Y6 6 6pa a a aF    [ ::&?JJ^ ^ ^ ^ LLLV  V  V  ML \V p #( < < < < < < < < < < <r   r   )r   urllib.parser   r   flaskr   cmf.include!modules.git.fields.cmf_plugin_gitr  r   r"   r  r   rG   r   r   <module>r)     s                    ( ( ( (N< N< N< N< N<7;%4A N< N< N< N< N<r   