Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
prompt=False)
else:
localImagePage.delete(
comment + ' [[:commons:Image:{0}]]'
.format(filenameOnCommons),
prompt=False)
else:
pywikibot.output('The image is not identical to '
'the one on Commons.')
except (pywikibot.NoPage, pywikibot.IsRedirectPage) as e:
pywikibot.output('{0}'.format(e[0]))
continue
else:
self._treat_counter += 1
if not self._treat_counter:
pywikibot.output('No transcluded files found for {0}.'
.format(self.ncTemplates()[0]))
self.exit()
that the page is categorized so skip the page.
If we found a template which is in the ignore list, skip the page.
"""
pywikibot.output(u'Working on ' + page.title())
for category in page.categories():
if category not in ignoreCategories:
pywikibot.output(u'Got category ' + category.title())
return False
for templateWithTrail in page.templates():
# Strip of trailing garbage
template = templateWithTrail.title().rstrip('\n').rstrip()
if template in skipTemplates:
# Already tagged with a template, skip it
pywikibot.output(u'Already tagged, skip it')
return False
elif template in ignoreTemplates:
# template not relevant for categorization
pywikibot.output(u'Ignore ' + template)
else:
pywikibot.output(u'Not ignoring ' + template)
return False
return True
if section and not does_text_contain_section(target.text,
section):
pywikibot.warning(
'Section #{0} not found on page {1}'.format(
section, target.title(as_link=True,
with_section=False)))
continue
else:
continue
# no fix to user namespaces
if target.namespace() in [2, 3] and page.namespace() not in [2, 3]:
continue
newtext = self.replace_links(newtext, page, target)
if i is None:
pywikibot.output('Nothing left to do.')
else:
self.put_current(newtext)
@raises NoUsername: Username is not recognised by the site.
"""
if not self.password:
# First check that the username exists,
# to avoid asking for a password that will not work.
if not autocreate:
self.check_user_exists()
# As we don't want the password to appear on the screen, we set
# password = True
self.password = pywikibot.input(
'Password for user %(name)s on %(site)s (no characters will '
'be shown):' % {'name': self.login_name, 'site': self.site},
password=True)
pywikibot.output('Logging in to %(site)s as %(name)s'
% {'name': self.login_name, 'site': self.site})
try:
cookiedata = self.getCookie()
except pywikibot.data.api.APIError as e:
error_code = e.code
pywikibot.error('Login failed ({}).'.format(error_code))
if error_code in self._api_error:
error_msg = 'Username "{}" {} on {}'.format(
self.login_name, self._api_error[error_code], self.site)
if error_code == 'Failed':
error_msg += '\n.{}'.format(e.info)
raise NoUsername(error_msg)
# TODO: investigate other unhandled API codes (bug T75539)
if retry:
self.password = None
translatedMsg = self.getOption('summary')
else:
translatedMsg = i18n.twtranslate(
self.site, 'clean_sandbox-cleaned')
subst = 'subst:' in translatedContent
pos = text.find(translatedContent.strip())
if text.strip() == translatedContent.strip():
pywikibot.output(
u'The sandbox is still clean, no change necessary.')
elif subst and sandboxPage.userName() == self.site.user():
pywikibot.output(
u'The sandbox might be clean, no change necessary.')
elif pos != 0 and not subst:
sandboxPage.put(translatedContent, translatedMsg)
pywikibot.showDiff(text, translatedContent)
pywikibot.output(u'Standard content was changed, '
u'sandbox cleaned.')
else:
edit_delta = (datetime.datetime.utcnow() -
sandboxPage.editTime())
delta = self.getOption('delay_td') - edit_delta
# Is the last edit more than 'delay' minutes ago?
if delta <= datetime.timedelta(0):
sandboxPage.put(translatedContent, translatedMsg)
pywikibot.showDiff(text, translatedContent)
pywikibot.output(u'Standard content was changed, '
u'sandbox cleaned.')
else: # wait for the rest
pywikibot.output(
u'Sandbox edited %.1f minutes ago...'
% (edit_delta.seconds / 60.0))
pywikibot.output(u'Sleeping for %d minutes.'
end = None
short_text = rep_text[rep_text.find('[['):end].strip()
reported = True
# Skip if the message is already there.
if short_text in text_get:
pywikibot.output('{} is already in the report page.'
.format(image_to_report))
reported = False
elif len(text_get) >= self.logFulNumber:
if self.logFullError:
raise LogIsFull(
'The log page ({}) is full! Please delete the old files '
'reported.'.format(another_page.title()))
else:
pywikibot.output(
'The log page ({}) is full! Please delete the old files '
' reported. Skip!'.format(another_page.title()))
# Don't report, but continue with the check
# (we don't know if this is the first time we check this file
# or not)
else:
# Adding the log
another_page.put(text_get + rep_text, summary=com, force=True,
minor=False)
pywikibot.output('...Reported...')
return reported
skip = False
# Do the actual upload
# Would be nice to check before I upload if the file is already at
# Commons. Not that important for this program, but maybe for
# derived programs
if not skip:
bot = UploadRobot(photoUrl,
description=newPhotoDescription,
useFilename=newFilename,
keepFilename=True,
verifyDescription=False)
bot.upload_image(debug=False)
return 1
else:
pywikibot.output('Invalid license')
return 0
pywikibot.output('Execution time: %d seconds' % delta.seconds)
if self._treat_counter:
pywikibot.output('Read operation time: %d seconds'
% (seconds / self._treat_counter))
if self._save_counter:
pywikibot.output('Write operation time: %d seconds'
% (seconds / self._save_counter))
# exc_info contains exception from self.run() while terminating
exc_info = sys.exc_info()
pywikibot.output('Script terminated ', newline=False)
# Python 2 also needs QuitKeyboardInterrupt
# to be compared with exc_info[0] (T195687)
if exc_info[0] is None or exc_info[0] in (KeyboardInterrupt,
QuitKeyboardInterrupt):
pywikibot.output('successfully.')
else:
pywikibot.output('by exception:\n')
pywikibot.exception()
def treat(self, photo):
"""Process each page."""
duplicates = photo.findDuplicateImages()
if duplicates:
pywikibot.output('Skipping duplicate of {!r}'
.format(duplicates))
return duplicates[0]
title = photo.getTitle(self.titlefmt)
description = photo.getDescription(self.pagefmt)
bot = UploadRobot(url=photo.URL,
description=description,
useFilename=title,
keepFilename=True,
verifyDescription=False,
targetSite=self.site)
bot._contents = photo.downloadPhoto().getvalue()
bot._retrieved = True
bot.run()
alternatives.append(arg[5:])
elif arg == '-just':
getAlternatives = False
elif arg == '-dnskip':
dnSkip = True
elif arg == '-main':
main_only = True
elif arg.startswith('-min:'):
minimum = int(arg[5:])
elif arg.startswith('-start'):
try:
generator = pagegenerators.CategorizedPageGenerator(
pywikibot.Site().disambcategory(),
start=arg[7:], namespaces=[0])
except pywikibot.NoPage:
pywikibot.output(
'Disambiguation category for your wiki is not known.')
raise
else:
generator_factory.handleArg(arg)
site = pywikibot.Site()
generator = generator_factory.getCombinedGenerator(generator)
if not generator:
pywikibot.bot.suggest_help(missing_generator=True)
return False
site.login()
bot = DisambiguationRobot(always, alternatives, getAlternatives, dnSkip,