U
    =eT                     @   s^   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ejej dS )    N)Response)*c                       s   e Z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jddddd  Zed!d" Z  ZS )&CmfPluginGitc              
   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parseZquoteplugintokenvaluewebhookcode)selfZ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                 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 qtj| |d'}| D ]"\}
}|
|jkrt||
| qt  |  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}|sRt|  d:|  tj$| ||d;}d<|_%| D ]"\}
}|
|jkr`t||
| q`t  |  W 5 Q R X q W 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_pluginr(   c                 S   s   i | ]}|j j|qS r   r&   r	   .0branchr   r   r   
<dictcomp>1   s     z-CmfPluginGit.webhook_call.<locals>.<dictcomp>deletedurlr+   r%   fieldsZbranchesz .webhook_call:   add new Branch r+   r%   r&   Zcommitsshar+   r6   r+   r%   git_commitsr4   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)r+   r%   r(   r4   z'.webhook_call:   add new Merge Request r+   r%   r(   F)&gdebugload_fields_get_driverZprocess_webhook_request	ExceptionprintZrequestZheadersdatagetcmfutilCmfLockr   models
CmfGitRepoCmfGitBranchlistitemsr4   setattrdisable_aclsaveCmfGitCommitsgetfind_related_taskstextr	   
setdefaultr9   appendr6   lenvaluesCmfAutomationCrudTrigger	crud_hookCmfGitMergeRequestr1   )r   _kwargsdriverZrequest_datar   r%   local_branchesbranch_datar&   r/   keyr	   task_to_saveZcommits_datacommit_datacommittaskmr_datar(   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)r&   systemZ
user_localF)Zalert u.   Интеграция с Git сервером (z).)Z	hook_typero   
token_userr&   rZ   )rO   	CmfPersonr   r   Zrg_member_ofr\   Z
CmfWebhookZwebhook_person_groupZgenerate_webhook_tokenrV   r   r   r
   )r   rq   r   r   r   r   _init_webhookp   s"      
   zCmfPluginGit._init_webhookc                 C   s0   | j j}|s,tjd| jdd}|  || _ d S )Ngit  )r   r&   sync_period)r   r	   rO   Z	CmfPluginr&   rV   )r   r   r   r   r   _calc_plugin   s
    zCmfPluginGit._calc_pluginc                 C   s   | j r| js|   d S r   )Zis_newr
   rs   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   rz      s    z CmfPluginGit.save_preload_fieldsc                    s:   |    |   | js,dtjddd| _t jf |S )Nr   Z>qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890   )k)rw   rx   r   joinrandomchoicesry   rV   )r   kwargsr{   r   r   rV      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 )r2   Z
ssl_verifyr   u#   Не правильно задан r'   u)   ): допустимые значения r   )r   r   Z	ext_tokenZ	cmf_alertZmodules.git.githubr   rM   rU   ZdecryptZmodules.git.gitlabZext_urlr	   Z
verify_sslZCmfErrorZcaptionr   r   )r   rc   r   r   r   r   r   rH      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h dd tjj| ddddddgdD }g }t |  d |	 D ]}|d }|
|d }|st |  d|d   tj| |d}d|_| D ]\}}||jkrt||| q|  |jr|| |j||  |  | jj| j| jjd q| D ](}t |  d |j  d!|_|  qJ|D ]:}t |  d"|  | || |j  |jd!d# qxW 5 Q R X | jjj rt!"|  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    r!      r#   c                 S   s   i | ]}|j j|qS r   r(   r	   )r.   r%   r   r   r   r0      s    z%CmfPluginGit.sync.<locals>.<dictcomp>r(   r2   Zdefault_branchsyncr1   	last_sync)r+   r4   z::sync: load reposz::sync:   add new Repo r&   r*   F)r   Zwebhook_namer   Zinsecure_sslZsecretz::sync:   del Repo Tz::sync: repo r>   z& first sync Success, enable auto sync!)#rJ   rG   rH   rM   rN   r   rO   rP   rR   Zavailable_repospopr1   rS   r4   rT   rV   r   r\   Zsetup_webhookr   r   r   r	   r   r   r^   r&   	sync_repor   set_nowr   sync_enabledZis_nullrE   rF   )	r   rc   Zlocal_reposZto_sync_reposZ	repo_datar(   r%   rf   r	   r   r   r   r      st             

  
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}|	 D ]"\}}	||j
krt|||	 q|  | j|jjdgdD ]"}||jj|}|j| qPq|
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rt|||	 q|  q:| D ]}|jd$krԐq|j|jj|jjd%}|r8t|  d&|j  d	|_|	 D ]"\}}	||j
krt|||	 qnt|  d'|j  d|_|  qd S )(Nc                 S   s   i | ]}|j j|qS r   r,   r-   r   r   r   r0      s     z*CmfPluginGit.sync_repo.<locals>.<dictcomp>r1   r2   r3   r&   z::sync:   add new Branch r5   Fr6   r7   r   )r6      r8   r9   r:   z::sync:   add z new commits from Branch r<   r=   Tr>   r?   z::sync:   del Branch c                 S   s   i | ]}|j j|qS r   r   )r.   rl   r   r   r   r0   1  s     r   r@   rA   rB   rC   )Z	only_openr(   z ::sync:   add new Merge Request rD   open)numberz::sync:   close Merge Request z::sync:   del Merge Request )rO   rQ   rR   Zget_branchesr(   r	   r   rJ   r1   rS   r4   rT   rV   rW   rX   Ziter_commitsrY   rZ   r[   r   r9   r\   r^   r_   r`   r&   ra   Zget_merge_requestsstatusZget_merge_requestr   )r   r%   rc   rg   rd   re   r&   r/   rf   r	   Zcommits_countrh   ri   rj   Z	local_mrsrk   r(   rl   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)rO   rr   rL   )clsr+   Zgit_idZ	git_loginZ	git_emailZgit_nameZpersonr   r   r   find_personS  s     zCmfPluginGit.find_personz(?P<code>[A-Z\d]+-\d+)c                 C   sF   | j |}dd|g}| jr6|dddd | jD gg}tjj||dS )u  
        Нужно в тексте найти все потенциальные коды. Можно просто все слова...
        Какие сложности:
            - код может быть практически любым max_len = 64
            - в имени ветки нельзя пробелы
        ОСВ: код вначале, и содержит ^([A-Z0-9]+-[0-9]+).*
        r   INZroot_parentc                 S   s   g | ]
}|j qS r   )r   )r.   Zprojectr   r   r   
<listcomp>g  s     z3CmfPluginGit.find_related_tasks.<locals>.<listcomp>)r   r4   )_TASK_CODE_SEARCH_REfindallr   rO   ZCmfTaskrR   )r   rZ   r4   ZcodesZfilter_r   r   r   rY   \  s
    
zCmfPluginGit.find_related_tasksT)Z	only_onceZsystem_taskc                  K   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.*r:   z!.sync_all_plugins: !!! Skip sync z die no plugin configured.Zdisabledru   z.sync_all_plugins: Try sync successzSync %s errorerror)rO   r   rR   r   rE   rF   
class_namer	   r   Zsync_statusrV   Zcommit_with_eventrv   Zsync_last_datetimeZager   r   
SystemExitKeyboardInterruptrI   loggingZ	exceptionZrollback_purge_eventZsync_last_error_datetimestrZsync_last_error_message)rb   r+   r   Zperioder   r   r   sync_all_pluginsj  s>    
zCmfPluginGit.sync_all_pluginsc                 C   s   t | j d S r   )Zcmf_deferred_taskr   )r   r   r   r   	cron_sync  s    zCmfPluginGit.cron_sync)N)NNNNN)N)__name__
__module____qualname__r   r   rm   rs   rw   rx   rz   rV   rH   r   r   classmethodr   recompileASCIIr   rY   staticmethodZ
celery_apprj   r   r   __classcell__r   r   r{   r   r      s(   Z>
`
%r   )r   Zurllib.parser   r   Zflaskr   Zcmf.includeZ!modules.git.fields.cmf_plugin_gitmodulesrt   r4   Zcmf_plugin_gitr   ZAPPZHOOK_CRON_MINUTELYr\   r   r   r   r   r   <module>   s      