U
    ܌f,X                     @   sP   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 dej	j
jjZdS )    N)Response)*c                       s   e Zd Zejjjjjdg Zdd Z	dd Z
dd Zdd	 Zd
d Zdd Zdd Z fddZ fddZdd Zdd Zd)ddZed*ddZedejZd+ddZeed d d!d"d#d$ Zd%d& fd'd(
Z  Z S ),CmfPluginGitsyncc              
   C   sJ   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=)
ZconfigZAPP_FQDNurllibparsequoteplugintokenvaluewebhookcode)selfhostname r   &./modules/git/models/cmf_plugin_git.pywebhook_url   s    zCmfPluginGit.webhook_urlc                 C   s   | j jS N)idr   r   r   r   r   webhook_ext_name   s    zCmfPluginGit.webhook_ext_namec                 C   s   |  D ]\}}||jkrz$|dkr0|dd}t||| W q tk
r } z<|dkrdt|krt||d  t|  d|  n|W 5 d }~X Y qX q|S )NZauthor_emailz@@@u6   Неправильный формат ввода emailuN   ::sync: author_email. Неправильный формат ввода email: )itemsfieldsreplacesetattrZCmfValidationErrorstrprint)r   commitcommit_datakeyr   er   r   r   _set_commit_data   s    
zCmfPluginGit._set_commit_datac                 K   s  t |  d | dddddddd	d
dg
 |  }z| }W n6 tk
rx   td ttj ttj	dd  Y nX |
dd}tj| j dddd t |  d|d d  d|d d  d tjj
| |d d d}dd tjj| |ddgd D }|
d!g D ]}|d }|
|}	|	sPt|  d"|  tj| ||d#}	| D ]"\}
}|
|	jkrXt|	|
| qXt  |	  W 5 Q R X qi }|
d$}|r|D ]}tjj| |d% d&r qltj| |d'}| ||}t  |  W 5 Q R X | j|jjd(gd)D ]H}||jj|}|j| t|  d*|j jd d+  d,| d- qqt|  d.t!| d- |" D ]F}tj#$|d/d0 t  |jdd1 W 5 Q R X tj#$|d/d2 q|
d3g D ]}|d }tj%j
| ||d4d5d6d7d8gd9}|s2t|  d:|  tj%| ||d;}d<|_&| D ]"\}
}|
|jkr@t||
| q@t  |  W 5 Q R X qW 5 Q R X |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,     timeoutZblocking_timeoutz$.webhook_call: update data for repo reponame(ext_id))
git_pluginr7   c                 S   s   i | ]}|j j|qS r   r5   r   .0branchr   r   r   
<dictcomp>E   s     z-CmfPluginGit.webhook_call.<locals>.<dictcomp>deletedurlr9   r4   r   Zbranchesz .webhook_call:   add new Branch r9   r4   r5   Zcommitsshar9   rC   r9   r4   git_commitsr   z.webhook_call:   add bind    z to z new commits.z.webhook_call:   add new updatebefore_saveZ	only_data
after_saveZmerge_requestsr   head_branchbase_branchauthor	merged_by)r9   r4   r7   r   z'.webhook_call:   add new Merge Request r9   r4   r7   F)'gdebugload_fields_get_driverZprocess_webhook_request	Exceptionr   ZrequestZheadersdatagetcmfutilCmfLockr   models
CmfGitRepoCmfGitBranchlistr   r   r   disable_aclsaveCmfGitCommitsgetr"   find_related_taskstextr   
setdefaultrF   appendrC   lenvaluesCmfAutomationCrudTrigger	crud_hookCmfGitMergeRequestr?   )r   _kwargsdriverZrequest_datar-   r4   local_branchesbranch_datar5   r=   r    r   task_to_saveZcommits_datar   r   taskmr_datar7   mrr   r   r   webhook_call*   s            
$  



.
  
 zCmfPluginGit.webhook_callc              
   C   s   t jd| j d| j ddd}|jt j  |jdd}|	  || j
_| j
	  t j| jd|| j d| j d| j d| j d	d
	 | _d S )Nu   Интеграция :T)r5   systemZ
user_localF)Zalert u.   Интеграция с Git сервером (z).)Z	hook_typerv   
token_userr5   rd   )r[   	CmfPersonr(   r   Zrg_member_ofrf   Z
CmfWebhookZwebhook_person_groupZgenerate_webhook_tokenr`   r	   r
   r   )r   rx   r
   r   r   r   _init_webhook   s"      
   zCmfPluginGit._init_webhookc                 C   s0   | j j}|s,tjd| jdd}|  || _ d S )Ngit  )r(   r5   sync_period)r	   r   r[   Z	CmfPluginr5   r`   )r   r	   r   r   r   _calc_plugin   s
    zCmfPluginGit._calc_pluginc                 C   s   | j r| js|   d S r   )Zis_newr   rz   r   r   r   r   _calc_webhook   s    zCmfPluginGit._calc_webhookc                    s   t   dddg S )Nr	   r(   r   )supersave_preload_fieldsr   	__class__r   r   r      s    z CmfPluginGit.save_preload_fieldsc                    s:   |    |   | js,dtjddd| _t jf |S )Nr.   Z>qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890   )k)r~   r   r+   joinrandomchoicesr   r`   )r   kwargsr   r   r   r`      s    
zCmfPluginGit.savec              	   C   s  d }| j dkrb| jjs*td|  ddd ddlm} t  | jj }W 5 Q R X ||d}nl| j d	kr| jjstd
|  ddd ddl	m} t  | jj }W 5 Q R X || jj
j| jjj|d}|std| j j d| j j dd| j j |S )NZgithubu.   У плагина интеграции Github uX    не указан токен доступа в конфигурации плагина.Tabortr   )Driver)r
   Zgitlabu.   У плагина интеграции Gitlab )r@   Z
ssl_verifyr
   u#   Не правильно задан r6   u)   ): допустимые значения r.   )r(   r	   Z	ext_token	cmf_alertZmodules.git.githubr   rY   r_   ZdecryptZmodules.git.gitlabZext_urlr   Z
verify_sslZCmfErrorZcaptionr   r   )r   rm   r   r
   r   r   r   rU      s<    

 


 
 &zCmfPluginGit._get_driverc           
      C   s>  t |  d | dddddddd	d
ddg |  }tj| j dddd dd tjj| dddddddgdD }g }t |  d z|	 }W n2 t
k
r   td| j  tddd Y nX |D ]}|d }||d }|st |  d|d    tj| || jd!}d"|_| D ]"\}}	||jkr$t|||	 q$|  |jr|| |j||  |  | jj| j| jjd# q| D ](}t |  d$|j  d|_|  q|D ]:}t |  d%|  |  || |j!"  |jdd& qW 5 Q R X | j#j$j%r:t&'|  d' d| j#_$| j#jjdd& d S )(Nz::sync: startr$   r%   r&   r'   zplugin.sync_enabledr#   r(   r   r)   r*   r+   r/   r0      r2   c                 S   s   i | ]}|j j|qS r   r7   r   )r<   r4   r   r   r   r>      s    z%CmfPluginGit.sync.<locals>.<dictcomp>r7   r@   Zdefault_branchr   r?   	last_sync)r9   r   z::sync: load reposu&   Ошика синхронизации u   Не удалось подключиться к репозиторию. Проверьте настройки подключения и повторите попытку.Tr   z::sync:   add new Repo r5   )r9   r7   r(   F)r   Zwebhook_namer)   Zinsecure_sslZsecretz::sync:   del Repo z::sync: repo rK   z& first sync Success, enable auto sync!)(r   rT   rU   rY   rZ   r   r[   r\   r^   Zavailable_reposZCmfAuthErrorlogging	exceptionr   popr(   r?   r   r   r   r`   r   rf   Zsetup_webhookr   r   r)   r   r*   r+   rh   r5   	sync_repor   set_nowr	   sync_enabledZis_nullrR   rS   )
r   rm   Zlocal_reposZto_sync_reposZavalilable_reposZ	repo_datar7   r4   r    r   r   r   r   r      s             
  
zCmfPluginGit.syncNc              	   C   sB  i }dd t jj| |ddgdD }||jjD ]>}|d }||d }|srt|  d|  t j| ||d}d	|_|	 D ]\}}	||j
krt|||	 q|  t jj| |d
 drq2d}
|j|jj|dD ]}t jj| |d
 dr qV|
d7 }
t j| |d}| ||}|  | j|jjdgdD ]"}||jj|}|j| q0q|
r2t|  d|
 d|  q2| D ]2}t j|dd |jdd t j|dd q|| D ](}t|  d|j  d|_|  qdd t jj| |dddddgdD }|j|jjdd D ]|}|d! }||d }|sZt|  d"|  t j| ||d#}d	|_|	 D ]"\}}	||j
krht|||	 qh|  q| D ]}|jd$krq|j|jj|jjd%}|rt|  d&|j  d	|_|	 D ]"\}}	||j
krt|||	 qnt|  d'|j  d|_|  qd S )(Nc                 S   s   i | ]}|j j|qS r   r:   r;   r   r   r   r>     s     z*CmfPluginGit.sync_repo.<locals>.<dictcomp>r?   r@   rA   r5   z::sync:   add new Branch rB   FrC   rD   r   )rC      rE   rF   rG   z::sync:   add z new commits from Branch rI   rJ   TrK   rL   z::sync:   del Branch c                 S   s   i | ]}|j j|qS r   r   )r<   rs   r   r   r   r>   I  s     r   rM   rN   rO   rP   )Z	only_openr7   z ::sync:   add new Merge Request rQ   open)numberz::sync:   close Merge Request z::sync:   del Merge Request ) r[   r]   r^   Zget_branchesr7   r   r   r   r?   r   r   r   r`   ra   rb   Ziter_commitsr"   rc   rd   re   r   rF   rf   rh   ri   rj   r5   rk   Zget_merge_requestsstatusZget_merge_requestr   )r   r4   rm   rp   rn   ro   r5   r=   r    r   Zcommits_countr   r   rq   Z	local_mrsrr   r7   rs   r   r   r   r     s      
  zCmfPluginGit.sync_repoc                 C   s,   d }|r(t jjddd|gdd|ggd}|S )NORZlogin=Zemail)filter)r[   ry   rX   )clsr9   Zgit_idZ	git_loginZ	git_emailZgit_nameZpersonr   r   r   find_personk  s     zCmfPluginGit.find_personz(?P<code>[A-Z\d]+-\d+)c                 C   s   t jj||| jdS )u   
        Нужно в тексте найти все потенциальные коды. Можно просто все слова...
        )r   r#   )r[   ZCmfTaskrc   r#   )r   rd   r   r   r   r   rc   t  s    zCmfPluginGit.find_related_tasksTz	@minutely)Z	only_onceZ
system_jobZschedulec                  C   s8  t jjddgdD ]} | js:tt jj d|  d q| jj}|js^d|_	|
  t  q|jjphd}|jr~|jj|k r~qtt jj d|   z|   d	|_	|j  W np ttfk
r    Y nX tk
r" } z8td
| t  d|_	|j  |j|_t||_W 5 d }~X Y nX |
  t  qd S )Nr   zplugin.*rG   z!.sync_all_plugins: !!! Skip sync z die no plugin configured.Zdisabledr|   z.sync_all_plugins: Try sync successzSync %s errorerror)r[   r   r^   r	   rR   rS   
class_namer   r   Zsync_statusr`   Zcommit_with_eventr}   Zsync_last_datetimeZager   r   
SystemExitKeyboardInterruptrV   r   r   Zrollback_purge_eventZsync_last_error_datetimer   Zsync_last_error_message)r9   r	   Zperiodr!   r   r   r   sync_all_pluginsz  s>    
zCmfPluginGit.sync_all_pluginsF)forcec                   s6   | j   | j j|ddi| t j|d|i|S )Nr   T)r   loaddeleter   )r   r   argsr   r   r   r   r     s    
zCmfPluginGit.delete)N)NNNNN)N)!__name__
__module____qualname__modulesr{   r   cmf_plugin_gitr   Zapi_methodsr   r   r"   rt   rz   r~   r   r   r`   rU   r   r   classmethodr   recompileASCIIZ_TASK_CODE_SEARCH_RErc   staticmethodZcmf_deferred_jobr   r   __classcell__r   r   r   r   r      s.   XF
^
%r   )r   urllib.parser   r   Zflaskr   Zcmf.includeZ!modules.git.fields.cmf_plugin_gitr   r{   r   r   r   r   r   r   r   <module>   s   