Ejemplo n.º 1
0
    def save_claim(self, claim, summary=None, bot=True):
        """
        Save the whole claim to the wikibase site.

        :param claim: The claim to save
        :type claim: pywikibot.Claim
        :param bot: Whether to mark the edit as a bot edit
        :type bot: bool
        :param summary: Edit summary
        :type summary: str
        """
        if claim.isReference or claim.isQualifier:
            raise NotImplementedError
        if not claim.snak:
            # We need to already have the snak value
            raise NoPageError(claim)
        params = {
            'action': 'wbsetclaim',
            'claim': json.dumps(claim.toJSON()),
            'token': self.tokens['edit'],
            'baserevid': claim.on_item.latest_revision_id,
            'summary': summary,
            'bot': bot,
        }

        req = self._simple_request(**params)
        data = req.submit()
        claim.on_item.latest_revision_id = data['pageinfo']['lastrevid']
        return data
Ejemplo n.º 2
0
    def changeClaimTarget(self, claim, snaktype='value',
                          bot=True, summary=None):
        """
        Set the claim target to the value of the provided claim target.

        :param claim: The source of the claim target value
        :type claim: pywikibot.Claim
        :param snaktype: An optional snaktype. Default: 'value'
        :type snaktype: str ('value', 'novalue' or 'somevalue')
        :param bot: Whether to mark the edit as a bot edit
        :type bot: bool
        :param summary: Edit summary
        :type summary: str
        """
        if claim.isReference or claim.isQualifier:
            raise NotImplementedError
        if not claim.snak:
            # We need to already have the snak value
            raise NoPageError(claim)
        params = {'action': 'wbsetclaimvalue', 'claim': claim.snak,
                  'snaktype': snaktype, 'summary': summary, 'bot': bot,
                  'token': self.tokens['edit']}

        if snaktype == 'value':
            params['value'] = json.dumps(claim._formatValue())

        params['baserevid'] = claim.on_item.latest_revision_id
        req = self._simple_request(**params)
        return req.submit()
Ejemplo n.º 3
0
 def page_restrictions(self, page):
     """Return a dictionary reflecting page protections."""
     if not self.page_exists(page):
         raise NoPageError(page)
     if not hasattr(page, '_protection'):
         page._protection = {'edit': ('steward', 'infinity'),
                             'move': ('steward', 'infinity'),
                             'delete': ('steward', 'infinity'),
                             'upload': ('steward', 'infinity'),
                             'create': ('steward', 'infinity')}
     return page._protection
Ejemplo n.º 4
0
    def append_text(self, page, apptext):
        """Append apptext to the page."""
        if page.isRedirectPage():
            page = page.getRedirectTarget()
        if page.exists():
            text = page.text
        else:
            if page.isTalkPage():
                text = ''
            else:
                raise NoPageError(page)

        text += apptext
        self.current_page = page
        self.put_current(text)
Ejemplo n.º 5
0
    def __init__(self, page: 'Topic', uuid: str) -> None:
        """
        Initializer.

        :param page: Flow topic
        :param uuid: UUID of a Flow post

        :raises TypeError: incorrect types of parameters
        """
        if not isinstance(page, Topic):
            raise TypeError('Page must be a Topic object')
        if not page.exists():
            raise NoPageError(page, 'Topic must exist: %s')
        if not isinstance(uuid, str):
            raise TypeError('Post UUID must be a string')

        self._page = page
        self._uuid = uuid

        self._content = {}  # type: Dict[str, Any]
Ejemplo n.º 6
0
def main(*args: Tuple[str, ...]):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    :param args: command line arguments
    """
    index = None
    djvu_path = '.'  # default djvu file directory
    pages = '1-'
    options = {}

    # Parse command line arguments.
    local_args = pywikibot.handle_args(args)
    for arg in local_args:
        opt, _, value = arg.partition(':')
        if opt == '-index':
            index = value
        elif opt == '-djvu':
            djvu_path = value
        elif opt == '-pages':
            pages = value
        elif opt == '-summary':
            options['summary'] = value
        elif opt in ('-force', '-always'):
            options[opt[1:]] = True
        else:
            pywikibot.output('Unknown argument ' + arg)

    # index is mandatory.
    if not index:
        pywikibot.bot.suggest_help(missing_parameters=['-index'])
        return

    # If djvu_path is not a file, build djvu_path from dir+index.
    djvu_path = os.path.expanduser(djvu_path)
    djvu_path = os.path.abspath(djvu_path)
    if not os.path.exists(djvu_path):
        pywikibot.error('No such file or directory: ' + djvu_path)
        return

    if os.path.isdir(djvu_path):
        djvu_path = os.path.join(djvu_path, index)

    # Check the djvu file exists and, if so, create the DjVuFile wrapper.
    djvu = DjVuFile(djvu_path)

    if not djvu.has_text():
        pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
        return

    # Parse pages param.
    pages = pages.split(',')
    for i, page in enumerate(pages):
        start, sep, end = page.partition('-')
        start = 1 if not start else int(start)
        if not sep:
            end = start
        else:
            end = int(end) if end else djvu.number_of_images()
        pages[i] = (start, end)

    site = pywikibot.Site()
    if not site.has_extension('ProofreadPage'):
        pywikibot.error(
            'Site {} must have ProofreadPage extension.'.format(site))
        return

    index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)

    if not index_page.exists():
        raise NoPageError(index)

    pywikibot.output('uploading text from {} to {}'.format(
        djvu.file, index_page.title(as_link=True)))

    bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
    bot.run()