A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

655 lines
26 KiB

  1. # -*- coding: utf-8 -*-
  2. from hashlib import md5
  3. import re
  4. from time import gmtime, strftime
  5. from urllib import quote
  6. from wiki.exceptions import *
  7. class Page(object):
  8. """
  9. EarwigBot's Wiki Toolset: Page Class
  10. Represents a Page on a given Site. Has methods for getting information
  11. about the page, getting page content, and so on. Category is a subclass of
  12. Page with additional methods.
  13. Public methods:
  14. title -- returns the page's title, or pagename
  15. exists -- returns whether the page exists
  16. pageid -- returns an integer ID representing the page
  17. url -- returns the page's URL
  18. namespace -- returns the page's namespace as an integer
  19. protection -- returns the page's current protection status
  20. creator -- returns the page's creator (first user to edit)
  21. is_talkpage -- returns True if the page is a talkpage, else False
  22. is_redirect -- returns True if the page is a redirect, else False
  23. toggle_talk -- returns a content page's talk page, or vice versa
  24. get -- returns page content
  25. get_redirect_target -- if the page is a redirect, returns its destination
  26. edit -- replaces the page's content or creates a new page
  27. add_section -- add a new section at the bottom of the page
  28. """
  29. def __init__(self, site, title, follow_redirects=False):
  30. """Constructor for new Page instances.
  31. Takes three arguments: a Site object, the Page's title (or pagename),
  32. and whether or not to follow redirects (optional, defaults to False).
  33. As with User, site.get_page() is preferred. Site's method has support
  34. for a default `follow_redirects` value in our config, while __init__
  35. always defaults to False.
  36. __init__ will not do any API queries, but it will use basic namespace
  37. logic to determine our namespace ID and if we are a talkpage.
  38. """
  39. self._site = site
  40. self._title = title.strip()
  41. self._follow_redirects = self._keep_following = follow_redirects
  42. self._exists = 0
  43. self._pageid = None
  44. self._is_redirect = None
  45. self._lastrevid = None
  46. self._protection = None
  47. self._fullurl = None
  48. self._content = None
  49. self._creator = None
  50. # Attributes used for editing/deleting/protecting/etc:
  51. self._token = None
  52. self._basetimestamp = None
  53. self._starttimestamp = None
  54. # Try to determine the page's namespace using our site's namespace
  55. # converter:
  56. prefix = self._title.split(":", 1)[0]
  57. if prefix != title: # ignore a page that's titled "Category" or "User"
  58. try:
  59. self._namespace = self._site.namespace_name_to_id(prefix)
  60. except NamespaceNotFoundError:
  61. self._namespace = 0
  62. else:
  63. self._namespace = 0
  64. # Is this a talkpage? Talkpages have odd IDs, while content pages have
  65. # even IDs, excluding the "special" namespaces:
  66. if self._namespace < 0:
  67. self._is_talkpage = False
  68. else:
  69. self._is_talkpage = self._namespace % 2 == 1
  70. def __repr__(self):
  71. """Returns the canonical string representation of the Page."""
  72. res = "Page(title={0!r}, follow_redirects={1!r}, site={2!r})"
  73. return res.format(self._title, self._follow_redirects, self._site)
  74. def __str__(self):
  75. """Returns a nice string representation of the Page."""
  76. return '<Page "{0}" of {1}>'.format(self.title(), str(self._site))
  77. def _force_validity(self):
  78. """Used to ensure that our page's title is valid.
  79. If this method is called when our page is not valid (and after
  80. _load_attributes() has been called), InvalidPageError will be raised.
  81. Note that validity != existence. If a page's title is invalid (e.g, it
  82. contains "[") it will always be invalid, and cannot be edited.
  83. """
  84. if self._exists == 1:
  85. e = "Page '{0}' is invalid.".format(self._title)
  86. raise InvalidPageError(e)
  87. def _force_existence(self):
  88. """Used to ensure that our page exists.
  89. If this method is called when our page doesn't exist (and after
  90. _load_attributes() has been called), PageNotFoundError will be raised.
  91. It will also call _force_validity() beforehand.
  92. """
  93. self._force_validity()
  94. if self._exists == 2:
  95. e = "Page '{0}' does not exist.".format(self._title)
  96. raise PageNotFoundError(e)
  97. def _load_wrapper(self):
  98. """Calls _load_attributes() and follows redirects if we're supposed to.
  99. This method will only follow redirects if follow_redirects=True was
  100. passed to __init__() (perhaps indirectly passed by site.get_page()).
  101. It avoids the API's &redirects param in favor of manual following,
  102. so we can act more realistically (we don't follow double redirects, and
  103. circular redirects don't break us).
  104. This will raise RedirectError if we have a problem following, but that
  105. is a bug and should NOT happen.
  106. If we're following a redirect, this will make a grand total of three
  107. API queries. It's a lot, but each one is quite small.
  108. """
  109. self._load_attributes()
  110. if self._keep_following and self._is_redirect:
  111. self._title = self.get_redirect_target()
  112. self._keep_following = False # don't follow double redirects
  113. self._content = None # reset the content we just loaded
  114. self._load_attributes()
  115. def _load_attributes(self, result=None):
  116. """Loads various data from the API in a single query.
  117. Loads self._title, ._exists, ._is_redirect, ._pageid, ._fullurl,
  118. ._protection, ._namespace, ._is_talkpage, ._creator, ._lastrevid,
  119. ._token, and ._starttimestamp using the API. It will do a query of
  120. its own unless `result` is provided, in which case we'll pretend
  121. `result` is what the query returned.
  122. Assuming the API is sound, this should not raise any exceptions.
  123. """
  124. if result is None:
  125. params = {"action": "query", "rvprop": "user", "intoken": "edit",
  126. "prop": "info|revisions", "rvlimit": 1, "rvdir": "newer",
  127. "titles": self._title, "inprop": "protection|url"}
  128. result = self._site._api_query(params)
  129. res = result["query"]["pages"].values()[0]
  130. # Normalize our pagename/title thing:
  131. self._title = res["title"]
  132. try:
  133. res["redirect"]
  134. except KeyError:
  135. self._is_redirect = False
  136. else:
  137. self._is_redirect = True
  138. self._pageid = result["query"]["pages"].keys()[0]
  139. if int(self._pageid) < 0:
  140. try:
  141. res["missing"]
  142. except KeyError:
  143. # If it has a negative ID and it's invalid, then break here,
  144. # because there's no other data for us to get:
  145. self._exists = 1
  146. return
  147. else:
  148. # If it has a negative ID and it's missing; we can still get
  149. # data like the namespace, protection, and URL:
  150. self._exists = 2
  151. else:
  152. self._exists = 3
  153. self._fullurl = res["fullurl"]
  154. self._protection = res["protection"]
  155. try:
  156. self._token = res["edittoken"]
  157. except KeyError:
  158. pass
  159. else:
  160. self._starttimestamp = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
  161. # We've determined the namespace and talkpage status in __init__()
  162. # based on the title, but now we can be sure:
  163. self._namespace = res["ns"]
  164. self._is_talkpage = self._namespace % 2 == 1 # talkpages have odd IDs
  165. # These last two fields will only be specified if the page exists:
  166. self._lastrevid = res.get("lastrevid")
  167. try:
  168. self._creator = res['revisions'][0]['user']
  169. except KeyError:
  170. pass
  171. def _load_content(self, result=None):
  172. """Loads current page content from the API.
  173. If `result` is provided, we'll pretend that is the result of an API
  174. query and try to get content from that. Otherwise, we'll do an API
  175. query on our own.
  176. Don't call this directly, ever - use .get(force=True) if you want to
  177. force content reloading.
  178. """
  179. if result is None:
  180. params = {"action": "query", "prop": "revisions", "rvlimit": 1,
  181. "rvprop": "content|timestamp", "titles": self._title}
  182. result = self._site._api_query(params)
  183. res = result["query"]["pages"].values()[0]
  184. try:
  185. self._content = res["revisions"][0]["*"]
  186. self._basetimestamp = res["revisions"][0]["timestamp"]
  187. except KeyError:
  188. # This can only happen if the page was deleted since we last called
  189. # self._load_attributes(). In that case, some of our attributes are
  190. # outdated, so force another self._load_attributes():
  191. self._load_attributes()
  192. self._force_existence()
  193. def _edit(self, params=None, text=None, summary=None, minor=None, bot=None,
  194. force=None, section=None, captcha_id=None, captcha_word=None,
  195. tries=0):
  196. """Edit the page!
  197. If `params` is given, we'll use it as our API query parameters.
  198. Otherwise, we'll build params using the given kwargs via
  199. _build_edit_params().
  200. We'll then try to do the API query, and catch any errors the API raises
  201. in _handle_edit_errors(). We'll then throw these back as subclasses of
  202. EditError.
  203. """
  204. # Try to get our edit token, and die if we can't:
  205. if not self._token:
  206. self._load_attributes()
  207. if not self._token:
  208. e = "You don't have permission to edit this page."
  209. raise PermissionsError(e)
  210. # Weed out invalid pages before we get too far:
  211. self._force_validity()
  212. # Build our API query string:
  213. if not params:
  214. params = self._build_edit_params(text, summary, minor, bot, force,
  215. section, captcha_id, captcha_word)
  216. else: # Make sure we have the right token:
  217. params["token"] = self._token
  218. # Try the API query, catching most errors with our handler:
  219. try:
  220. result = self._site._api_query(params)
  221. except SiteAPIError as error:
  222. if not hasattr(error, "code"):
  223. raise # We can only handle errors with a code attribute
  224. result = self._handle_edit_errors(error, params, tries)
  225. # If everything was successful, reset invalidated attributes:
  226. if result["edit"]["result"] == "Success":
  227. self._content = None
  228. self._basetimestamp = None
  229. self._exists = 0
  230. return
  231. # If we're here, then the edit failed. If it's because of AssertEdit,
  232. # handle that. Otherwise, die - something odd is going on:
  233. try:
  234. assertion = result["edit"]["assert"]
  235. except KeyError:
  236. raise EditError(result["edit"])
  237. self._handle_assert_edit(assertion, params, tries)
  238. def _build_edit_params(self, text, summary, minor, bot, force, section,
  239. captcha_id, captcha_word):
  240. """Given some keyword arguments, build an API edit query string."""
  241. hashed = md5(text).hexdigest() # Checksum to ensure text is correct
  242. params = {"action": "edit", "title": self._title, "text": text,
  243. "token": self._token, "summary": summary, "md5": hashed}
  244. if section:
  245. params["section"] = section
  246. if captcha_id and captcha_word:
  247. params["captchaid"] = captcha_id
  248. params["captchaword"] = captcha_word
  249. if minor:
  250. params["minor"] = "true"
  251. else:
  252. params["notminor"] = "true"
  253. if bot:
  254. params["bot"] = "true"
  255. if not force:
  256. params["starttimestamp"] = self._starttimestamp
  257. if self._basetimestamp:
  258. params["basetimestamp"] = self._basetimestamp
  259. if self._exists == 2:
  260. # Page does not exist; don't edit if it already exists:
  261. params["createonly"] = "true"
  262. else:
  263. params["recreate"] = "true"
  264. return params
  265. def _handle_edit_errors(self, error, params, tries):
  266. """If our edit fails due to some error, try to handle it.
  267. We'll either raise an appropriate exception (for example, if the page
  268. is protected), or we'll try to fix it (for example, if we can't edit
  269. due to being logged out, we'll try to log in).
  270. """
  271. if error.code in ["noedit", "cantcreate", "protectedtitle",
  272. "noimageredirect"]:
  273. raise PermissionsError(error.info)
  274. elif error.code in ["noedit-anon", "cantcreate-anon",
  275. "noimageredirect-anon"]:
  276. if not all(self._site._login_info):
  277. # Insufficient login info:
  278. raise PermissionsError(error.info)
  279. if tries == 0:
  280. # We have login info; try to login:
  281. self._site._login(self._site._login_info)
  282. self._token = None # Need a new token; old one is invalid now
  283. return self._edit(params=params, tries=1)
  284. else:
  285. # We already tried to log in and failed!
  286. e = "Although we should be logged in, we are not. This may be a cookie problem or an odd bug."
  287. raise LoginError(e)
  288. elif error.code in ["editconflict", "pagedeleted", "articleexists"]:
  289. # These attributes are now invalidated:
  290. self._content = None
  291. self._basetimestamp = None
  292. self._exists = 0
  293. raise EditConflictError(error.info)
  294. elif error.code in ["emptypage", "emptynewsection"]:
  295. raise NoContentError(error.info)
  296. elif error.code == "contenttoobig":
  297. raise ContentTooBigError(error.info)
  298. elif error.code == "spamdetected":
  299. raise SpamDetectedError(error.info)
  300. elif error.code == "filtered":
  301. raise FilteredError(error.info)
  302. raise EditError(": ".join((error.code, error.info)))
  303. def _handle_assert_edit(self, assertion, params, tries):
  304. """If we can't edit due to a failed AssertEdit assertion, handle that.
  305. If the assertion was 'user' and we have valid login information, try to
  306. log in. Otherwise, raise PermissionsError with details.
  307. """
  308. if assertion == "user":
  309. if not all(self._site._login_info):
  310. # Insufficient login info:
  311. e = "AssertEdit: user assertion failed, and no login info was provided."
  312. raise PermissionsError(e)
  313. if tries == 0:
  314. # We have login info; try to login:
  315. self._site._login(self._site._login_info)
  316. self._token = None # Need a new token; old one is invalid now
  317. return self._edit(params=params, tries=1)
  318. else:
  319. # We already tried to log in and failed!
  320. e = "Although we should be logged in, we are not. This may be a cookie problem or an odd bug."
  321. raise LoginError(e)
  322. elif assertion == "bot":
  323. e = "AssertEdit: bot assertion failed; we don't have a bot flag!"
  324. raise PermissionsError(e)
  325. # Unknown assertion, maybe "true", "false", or "exists":
  326. e = "AssertEdit: assertion '{0}' failed.".format(assertion)
  327. raise PermissionsError(e)
  328. def title(self, force=False):
  329. """Returns the Page's title, or pagename.
  330. This won't do any API queries on its own unless force is True, in which
  331. case the title will be forcibly reloaded from the API (normalizing it,
  332. and following redirects if follow_redirects=True was passed to
  333. __init__()). Any other methods that do API queries will reload title on
  334. their own, however, like exists() and get().
  335. """
  336. if force:
  337. self._load_wrapper()
  338. return self._title
  339. def exists(self, force=False):
  340. """Returns information about whether the Page exists or not.
  341. The returned "information" is a tuple with two items. The first is a
  342. bool, either True if the page exists or False if it does not. The
  343. second is a string giving more information, either "invalid", (title
  344. is invalid, e.g. it contains "["), "missing", or "exists".
  345. Makes an API query if force is True or if we haven't already made one.
  346. """
  347. cases = {
  348. 0: (None, "unknown"),
  349. 1: (False, "invalid"),
  350. 2: (False, "missing"),
  351. 3: (True, "exists"),
  352. }
  353. if self._exists == 0 or force:
  354. self._load_wrapper()
  355. return cases[self._exists]
  356. def pageid(self, force=False):
  357. """Returns an integer ID representing the Page.
  358. Makes an API query if force is True or if we haven't already made one.
  359. Raises InvalidPageError or PageNotFoundError if the page name is
  360. invalid or the page does not exist, respectively.
  361. """
  362. if self._exists == 0 or force:
  363. self._load_wrapper()
  364. self._force_existence() # missing pages do not have IDs
  365. return self._pageid
  366. def url(self, force=False):
  367. """Returns the page's URL.
  368. Like title(), this won't do any API queries on its own unless force is
  369. True. If the API was never queried for this page, we will attempt to
  370. determine the URL ourselves based on the title.
  371. """
  372. if force:
  373. self._load_wrapper()
  374. if self._fullurl is not None:
  375. return self._fullurl
  376. else:
  377. slug = quote(self._title.replace(" ", "_"), safe="/:")
  378. path = self._site._article_path.replace("$1", slug)
  379. return ''.join((self._site._base_url, path))
  380. def namespace(self, force=False):
  381. """Returns the page's namespace ID (an integer).
  382. Like title(), this won't do any API queries on its own unless force is
  383. True. If the API was never queried for this page, we will attempt to
  384. determine the namespace ourselves based on the title.
  385. """
  386. if force:
  387. self._load_wrapper()
  388. return self._namespace
  389. def protection(self, force=False):
  390. """Returns the page's current protection status.
  391. Makes an API query if force is True or if we haven't already made one.
  392. Raises InvalidPageError if the page name is invalid. Will not raise an
  393. error if the page is missing because those can still be protected.
  394. """
  395. if self._exists == 0 or force:
  396. self._load_wrapper()
  397. self._force_validity() # invalid pages cannot be protected
  398. return self._protection
  399. def creator(self, force=False):
  400. """Returns the page's creator (i.e., the first user to edit the page).
  401. Makes an API query if force is True or if we haven't already made one.
  402. Normally, we can get the creator along with everything else (except
  403. content) in self._load_attributes(). However, due to a limitation in
  404. the API (can't get the editor of one revision and the content of
  405. another at both ends of the history), if our other attributes were only
  406. loaded from get(), we'll have to do another API query. This is done
  407. by calling ourselves again with force=True.
  408. Raises InvalidPageError or PageNotFoundError if the page name is
  409. invalid or the page does not exist, respectively.
  410. """
  411. if self._exists == 0 or force:
  412. self._load_wrapper()
  413. self._force_existence()
  414. if not self._creator and not force:
  415. self.creator(force=True)
  416. return self._creator
  417. def is_talkpage(self, force=False):
  418. """Returns True if the page is a talkpage, else False.
  419. Like title(), this won't do any API queries on its own unless force is
  420. True. If the API was never queried for this page, we will attempt to
  421. determine the talkpage status ourselves based on its namespace ID.
  422. """
  423. if force:
  424. self._load_wrapper()
  425. return self._is_talkpage
  426. def is_redirect(self, force=False):
  427. """Returns True if the page is a redirect, else False.
  428. Makes an API query if force is True or if we haven't already made one.
  429. We will return False even if the page does not exist or is invalid.
  430. """
  431. if self._exists == 0 or force:
  432. self._load_wrapper()
  433. return self._is_redirect
  434. def toggle_talk(self, force=False, follow_redirects=None):
  435. """Returns a content page's talk page, or vice versa.
  436. The title of the new page is determined by namespace logic, not API
  437. queries. We won't make any API queries on our own unless force is True,
  438. and the only reason then would be to forcibly update the title or
  439. follow redirects if we haven't already made an API query.
  440. If `follow_redirects` is anything other than None (the default), it
  441. will be passed to the new Page's __init__(). Otherwise, we'll use the
  442. value passed to our own __init__().
  443. Will raise InvalidPageError if we try to get the talk page of a special
  444. page (in the Special: or Media: namespaces), but we won't raise an
  445. exception if our page is otherwise missing or invalid.
  446. """
  447. if force:
  448. self._load_wrapper()
  449. if self._namespace < 0:
  450. ns = self._site.namespace_id_to_name(self._namespace)
  451. e = "Pages in the {0} namespace can't have talk pages.".format(ns)
  452. raise InvalidPageError(e)
  453. if self._is_talkpage:
  454. new_ns = self._namespace - 1
  455. else:
  456. new_ns = self._namespace + 1
  457. try:
  458. body = self._title.split(":", 1)[1]
  459. except IndexError:
  460. body = self._title
  461. new_prefix = self._site.namespace_id_to_name(new_ns)
  462. # If the new page is in namespace 0, don't do ":Title" (it's correct,
  463. # but unnecessary), just do "Title":
  464. if new_prefix:
  465. new_title = ':'.join((new_prefix, body))
  466. else:
  467. new_title = body
  468. if follow_redirects is None:
  469. follow_redirects = self._follow_redirects
  470. return Page(self._site, new_title, follow_redirects)
  471. def get(self, force=False):
  472. """Returns page content, which is cached if you try to call get again.
  473. Use `force` to forcibly reload page content even if we've already
  474. loaded some. This is good if you want to edit a page multiple times,
  475. and you want to get updated content before you make your second edit.
  476. Raises InvalidPageError or PageNotFoundError if the page name is
  477. invalid or the page does not exist, respectively.
  478. """
  479. if force or self._exists == 0:
  480. # Kill two birds with one stone by doing an API query for both our
  481. # attributes and our page content:
  482. params = {"action": "query", "rvlimit": 1, "titles": self._title,
  483. "prop": "info|revisions", "inprop": "protection|url",
  484. "intoken": "edit", "rvprop": "content|timestamp"}
  485. result = self._site._api_query(params)
  486. self._load_attributes(result=result)
  487. self._force_existence()
  488. self._load_content(result=result)
  489. # Follow redirects if we're told to:
  490. if self._keep_following and self._is_redirect:
  491. self._title = self.get_redirect_target()
  492. self._keep_following = False # don't follow double redirects
  493. self._content = None # reset the content we just loaded
  494. self.get(force=True)
  495. return self._content
  496. # Make sure we're dealing with a real page here. This may be outdated
  497. # if the page was deleted since we last called self._load_attributes(),
  498. # but self._load_content() can handle that:
  499. self._force_existence()
  500. if self._content is None:
  501. self._load_content()
  502. return self._content
  503. def get_redirect_target(self, force=False):
  504. """If the page is a redirect, returns its destination.
  505. Use `force` to forcibly reload content even if we've already loaded
  506. some before. Note that this method calls get() for page content.
  507. Raises InvalidPageError or PageNotFoundError if the page name is
  508. invalid or the page does not exist, respectively. Raises RedirectError
  509. if the page is not a redirect.
  510. """
  511. content = self.get(force)
  512. regexp = "^\s*\#\s*redirect\s*\[\[(.*?)\]\]"
  513. try:
  514. return re.findall(regexp, content, flags=re.IGNORECASE)[0]
  515. except IndexError:
  516. e = "The page does not appear to have a redirect target."
  517. raise RedirectError(e)
  518. def edit(self, text, summary, minor=False, bot=True, force=False):
  519. """Replaces the page's content or creates a new page.
  520. `text` is the new page content, with `summary` as the edit summary.
  521. If `minor` is True, the edit will be marked as minor. If `bot` is true,
  522. the edit will be marked as a bot edit, but only if we actually have a
  523. bot flag.
  524. Use `force` to push the new content even if there's an edit conflict or
  525. the page was deleted/recreated between getting our edit token and
  526. editing our page. Be careful with this!
  527. """
  528. self._edit(text=text, summary=summary, minor=minor, bot=bot,
  529. force=force)
  530. def add_section(self, text, title, minor=False, bot=True, force=False):
  531. """Adds a new section to the bottom of the page.
  532. The arguments for this are the same as those for edit(), but instead of
  533. providing a summary, you provide a section title.
  534. Likewise, raised exceptions are the same as edit()'s.
  535. This should create the page if it does not already exist, with just the
  536. new section as content.
  537. """
  538. self._edit(text=text, summary=title, minor=minor, bot=bot, force=force,
  539. section="new")