a
    NbP                     @   sL   d dl Z d dl mZ d dlZd dlmZ d dlZd dlZG dd deZ	dS )    N)	text_type)parse_timestampc                   @   s"  e Zd ZdFddZdd Zdd Zdd	 Zd
d Zedd Z	edd Z
dd ZdGddZdHddZdd ZdIddZdJddZdKd d!Zd"d# Zd$d% Zd&d' ZdLd(d)ZdMd*d+Zd,d- ZdNd/d0ZdOd1d2ZdPd3d4Zd5d6 ZdQd7d8Zd9d: Zd;d< ZdRd=d>ZdSdBdCZ dTdDdEZ!dS )UPageNc                 C   s  t |t | u r"| j|j d S || _|| _i | _|s|rpddt| }g }t	|D ]}|
| q^nd}d}t |tu r| jjdg|R ||dd}n| jjdg|R ||dd}tt	|d d	 }|| _d
|v rtj|d|dd| _|dd| _| jr.| | j| _n| j| _| jdd | _| jdd | _t|d| _|dd| _d|v| _|d| _dd |ddD | _d|v | _|dd | _|dd | _ |dd | _!|dd | _"d | _#d | _$d S )Nzinfo||info query
protection)propZpageidsinprop)r
   titlesr   ZpagesinvalidZinvalidreasonnsr   title /touchedZ	lastrevidmissinglengthc                 S   s&   i | ]}|r|d  |d |d fqS )typelevelZexpiryr   ).0ir   r   J/var/www/html/diaryflask/venv/lib/python3.9/site-packages/mwclient/page.py
<dictcomp>7   s   z!Page.__init__.<locals>.<dictcomp>redirectpageidcontentmodelpagelanguagerestrictiontypes)%r   __dict__updatesitename
_textcachejoinsixiterkeys
itervaluesextendintgetnext_infomwclienterrorsZInvalidPageTitle	namespacestrip_namespaceZ
page_titlesplitZ
base_title	base_namer   r   revisionexistsr   r	   r   r   r   r   r   last_rev_time	edit_time)selfr"   r#   r   Zextra_propertiesr
   Zextra_propsZ
extra_propr   r   r   __init__   sd    





zPage.__init__c                 C   sb   | j jdd| jdd}d|d v rZ|d d D ]&}|d | jkr.t| j |d   S q.dS dS dS )	zE Get the redirect target page, or None if the page is not a redirect.r   Z	pagepropsr   )r
   r   	redirectsr:   fromtoN)r"   r+   r#   r   )r8   r   pager   r   r   redirects_toE   s    zPage.redirects_toc                 C   s   |   }|du r| S |S dS )zI Get the redirect target page, or the current page if its not a redirect.N)r>   )r8   Ztarget_pager   r   r   resolve_redirectP   s    zPage.resolve_redirectc                 C   s   d| j d| jf S )Nz<Page object '%s' for %s>zutf-8)r#   encoder"   r8   r   r   r   __repr__X   s    zPage.__repr__c                 C   s   | j S )N)r#   rA   r   r   r   __unicode__[   s    zPage.__unicode__c                 C   s.   | d dkr| dd  } | |  dd d  S )Nr   :   )findr   r   r   r   r1   ^   s    zPage.strip_namespacec                 C   sH   |   } | d dkr | dd  } | d  | dd   } | dd} | S )Nr   rD   rE    _)stripupperreplacerG   r   r   r   normalize_titled   s    zPage.normalize_titlec                 C   s,   | j ||fd }|dkr d}|| jjv S )zCheck if the current user has the right to carry out some action
        with the current page.

        Example:
            >>> page.can('edit')
            True

        r   ZsysopZeditprotected)r	   r+   r"   Zrights)r8   actionr   r   r   r   cann   s    	zPage.canFc                 C   s   | j j||| jdS )NrG   )r"   	get_tokenr#   )r8   r   forcer   r   r   rP   }   s    zPage.get_tokenTmainc           	      C   s   |  dstj| | js dS |dur0t|}t||f}|rT|| jv rT| j| S | jdd||d}z8t	|}d|v r|d | d }n|d }|d	 | _
W n ty   d}d| _
Y n0 |st | _n| j|}|r|| j|< |S )
at  Get the current wikitext of the page, or of a specific section.

        If the page does not exist, an empty string is returned. By
        default, results will be cached and if you call text() again
        with the same section and expandtemplates the result will come
        from the cache. The cache is stored on the instance, so it
        lives as long as the instance does.

        Args:
            section (int): Section number, to only get text from a single section.
            expandtemplates (bool): Expand templates (default: `False`)
            cache (bool): Use in-memory caching (default: `True`)
        readr   Nzcontent|timestamprE   )r
   limitsectionslotsrV   *	timestamp)rO   r.   r/   InsufficientPermissionr5   r   hashr$   	revisionsr,   r6   StopIterationtimegmtimer7   r"   expandtemplates)	r8   rU   r_   cacheZslotkeyrevsrevtextr   r   r   rd      s6    



z	Page.textc                 O   s   | j |i |S )z8Alias for edit, for maintaining backwards compatibility.)edit)r8   argskwargsr   r   r   save   s    z	Page.saver   c                 K   s   | j ||||fd|i|S )zXUpdate the text of a section or the whole page by performing an edit operation.
        rd   _editr8   rd   summaryminorbotrU   rg   r   r   r   re      s    z	Page.editc                 K   s   | j ||||fd|i|S )zTAppend text to a section or the whole page by performing an edit operation.
        Z
appendtextri   rk   r   r   r   append   s    zPage.appendc                 K   s   | j ||||fd|i|S )zUPrepend text to a section or the whole page by performing an edit operation.
        Zprependtextri   rk   r   r   r   prepend   s    zPage.prependc           
         s  j jsj jrtj j jr2tjj jdsHtj	j j
s\tji  |rld d< |sxd d< jrtdj d< jrtdj d< |rd d< |d ur| d	<  | j jrd
 d<  fdd}z
| }W n tjjy } zv|jdkrljddd z
| }W n6 tjjyh } z| W Y d }~n
d }~0 0 n| W Y d }~n
d }~0 0 d|d  v rt|d d_j jjD ],}	d|	jv rj jj|	j|	j|	j qi _|d S )Nre   1rm   Znotminorz%Y%m%d%H%M%SZbasetimestampZstarttimestamprn   rU   userassertc                     sN   j jdjdd } | d d dkrJtj| d | S )Nre   )r   rl   tokenresultZfailure)re   )	r"   postr#   rP   r+   lowerr.   r/   	EditError)ru   datar8   rl   r   r   do_edit   s    zPage._edit.<locals>.do_editZbadtokenT)rQ   ZnewtimestampZPostEditRevision)r"   Z	logged_inZforce_loginr.   r/   AssertUserFailedErrorZblockedZUserBlockedrO   ProtectedPageErrorwriteapi
NoWriteApir6   r]   strftimer7   r!   ZAPIErrorcoderP   handle_edit_errorkeysr   r+   
connectioncookiesr#   cleardomainpathr$   )
r8   rl   rm   rn   rU   rg   r{   ru   ecookier   ry   r   rj      sX    




$"z
Page._editc                 C   s\   |j dkrtj| ||jn:|j dv r>tj| |j |jn|j dkrTtj n|d S )NZeditconflict>   zcantcreate-anonZcascadeprotectedzprotectednamespace-interfaceZnoimageredirectznoedit-anonZprotectednamespaceZprotectedpageznoimageredirect-anonZ
cantcreateZcustomcssjsprotectedZprotectedtitleZnoeditZassertuserfailed)r   r.   r/   rx   r   r}   r|   )r8   r   rl   r   r   r   r     s    


zPage.handle_edit_errorc                 C   s   | j s
dS | d dS )aL  Perform a "null edit" on the page to update the wiki's cached data of it.
        This is useful in contrast to purge when needing to update stored data on a wiki,
        for example Semantic MediaWiki properties or Cargo table values, since purge
        only forces update of a page's displayed values and not its store.
        Nr   )r5   ro   rA   r   r   r   touch  s    z
Page.touchc                 C   sx   |  dstj| | jjs*tj| i }|r:d|d< |rFd|d< | jjdd| jff|| 	d|d|}|d S )a  Move (rename) page to new_title.

        If user account is an administrator, specify no_redirect as True to not
        leave a redirect.

        If user does not have permission to move page, an InsufficientPermission
        exception is raised.

        moverq   ZmovetalkZ
noredirectr;   )r<   rt   reason
rO   r.   r/   rY   r"   r~   r   rv   r#   rP   )r8   Z	new_titler   Z	move_talkZno_redirectrz   ru   r   r   r   r     s    


z	Page.movec                 C   s|   |  dstj| | jjs*tj| i }|r:d|d< |rFd|d< |rR||d< | jjd| j| 	d|d|}|d S )zDelete page.

        If user does not have permission to delete page, an InsufficientPermission
        exception is raised.

        deleterq   watchunwatcholdimage)r   rt   r   )r   r   )r8   r   r   r   r   rz   ru   r   r   r   r   8  s$    
zPage.deletec                 C   s   | j jd| jd dS )zkPurge server-side cache of page. This will re-render templates and other
        dynamic content.

        purge)r   N)r"   rv   r#   rA   r   r   r   r   Q  s    z
Page.purgeallc                 C   sl   t jjd|}tt jjj|||d}|r8d|d| < | j||d < t jj|| jddf|dd|S )zList pages that link to the current page, similar to Special:Whatlinkshere.

        API doc: https://www.mediawiki.org/wiki/API:Backlinks

        blr0   filterredirrq   z
%sredirectr   	backlinksrT   return_values	r.   listingList
get_prefixdictgenerate_kwargsr#   Zget_listr"   )r8   r0   r   r   rT   	generatorprefixrg   r   r   r   r   [  s    
zPage.backlinksc                 C   sb   t jjd|}tt jjj||d}|rBt jj| ddfi |S t jj| ddfddi|S dS )a  List categories used on the current page.

        API doc: https://www.mediawiki.org/wiki/API:Categories

        Args:
            generator (bool): Return generator (Default: True)
            show (str): Set to 'hidden' to only return hidden categories
                or '!hidden' to only return non-hidden ones.

        Returns:
            mwclient.listings.PagePropertyGenerator
        Zcl)show
categoriesr   r   Nr.   r   r   r   r   r   PagePropertyGeneratorPageProperty)r8   r   r   r   rg   r   r   r   r   o  s"    
zPage.categoriesc                 C   s\   t jjd|}tt jjj|||d}| j||d < t jj|| jddf|dd|S )a   List pages that transclude the current page.

        API doc: https://www.mediawiki.org/wiki/API:Embeddedin

        Args:
            namespace (int): Restricts search to a given namespace (Default: None)
            filterredir (str): How to filter redirects, either 'all' (default),
                'redirects' or 'nonredirects'.
            limit (int): Maximum amount of pages to return per request
            generator (bool): Return generator (Default: True)

        Returns:
            mwclient.listings.List: Page iterator
        eir   r   
embeddedinr   r   )r8   r0   r   rT   r   r   rg   r   r   r   r     s    zPage.embeddedinc                 C   s   t jj| ddddS )zrList external links from the current page.

        API doc: https://www.mediawiki.org/wiki/API:Extlinks

        extlinkselrW   r   r.   r   r   rA   r   r   r   r     s    zPage.extlinksc                 C   s,   |rt j| ddS t jj| ddddS dS )zuList files/images embedded in the current page.

        API doc: https://www.mediawiki.org/wiki/API:Images

        imagesr   r   r   N)r.   r   r   r   )r8   r   r   r   r   r     s
    zPage.imagesc                 C   s   t jj| ddddS )zrList interwiki links from the current page.

        API doc: https://www.mediawiki.org/wiki/API:Iwlinks

        iwlinksiw)r   rW   r   r   rA   r   r   r   r     s    zPage.iwlinksc                 K   s   t jj| ddfddi|S )zxList interlanguage links from the current page.

        API doc: https://www.mediawiki.org/wiki/API:Langlinks

        	langlinksZllr   )langrW   r   )r8   rg   r   r   r   r     s
    zPage.langlinksc                 C   sn   t jjd|}tt jjj||d}|r2d|d< |rNt jj| ddfi |S t jj| ddfddi|S dS )	zuList links to other pages from the current page.

        API doc: https://www.mediawiki.org/wiki/API:Links

        plr0   rq   r:   linksr   r   Nr   )r8   r0   r   r:   r   rg   r   r   r   r     s    z
Page.linksolder2    ids|timestamp|flags|comment|userc                 C   s   t tjjjd||||||||d	}| jjdd dk rFd|v rF|d= ||d< |	|d< ||d	< |
rjd
|d< |durz||d< tjj| ddfd|i|S )a  List revisions of the current page.

        API doc: https://www.mediawiki.org/wiki/API:Revisions

        Args:
            startid (int): Revision ID to start listing from.
            endid (int): Revision ID to stop listing at.
            start (str): Timestamp to start listing from.
            end (str): Timestamp to end listing at.
            dir (str): Direction to list in: 'older' (default) or 'newer'.
            user (str): Only list revisions made by this user.
            excludeuser (str): Exclude revisions made by this user.
            limit (int): The maximum number of revisions to return per request.
            prop (str): Which properties to get for each revision,
                default: 'ids|timestamp|flags|comment|user'
            expandtemplates (bool): Expand templates in rvprop=content output
            section (int): Section number. If rvprop=content is set, only the contents
                of this section will be retrieved.
            diffto (str): Revision ID to diff each revision to. Use "prev", "next" and
                "cur" for the previous, next and current revision respectively.
            slots (str): The content slot (Mediawiki >= 1.32) to retrieve content from.
            uselang (str): Language to use for parsed edit comments and other localized
                messages.

        Returns:
            mwclient.listings.List: Revision iterator
        rv)startidendidstartendrr   excludeuserdifftorV   N   )rE       ZrvslotsZrvdirZrvpropuselangrq   ZrvexpandtemplatesZ	rvsectionr[   rT   )r   r.   r   r   r   r"   versionZRevisionsIterator)r8   r   r   r   r   dirrr   r   rT   r
   r_   rU   r   rV   r   rg   r   r   r   r[     s      
zPage.revisionsc                 C   sb   t jjd|}tt jjj||d}|rBt jj| d|fi |S t jj| d|fddi|S dS )zqList templates used on the current page.

        API doc: https://www.mediawiki.org/wiki/API:Templates

        tlr   	templatesr   r   Nr   )r8   r0   r   r   rg   r   r   r   r     s    zPage.templates)NN)F)NFTrR   )r   FTN)r   FTN)r   FTN)r   TF)r   FFF)Nr   FNT)TN)Nr   NT)T)NTF)NNNNr   NNr   r   FNNNN)NT)"__name__
__module____qualname__r9   r>   r?   rB   rC   staticmethodr1   rM   rO   rP   rd   rh   re   ro   rp   rj   r   r   r   r   r   r   r   r   r   r   r   r   r   r[   r   r   r   r   r   r   	   sN   
:

	

1


A



  



	

     
4r   )
r&   r   r]   Zmwclient.utilr   Zmwclient.listingr.   Zmwclient.errorsobjectr   r   r   r   r   <module>   s   