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.

page.py 17 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. # -*- coding: utf-8 -*-
  2. import re
  3. from urllib import quote
  4. from wiki.exceptions import *
  5. class Page(object):
  6. """
  7. EarwigBot's Wiki Toolset: Page Class
  8. Represents a Page on a given Site. Has methods for getting information
  9. about the page, getting page content, and so on. Category is a subclass of
  10. Page with additional methods.
  11. Public methods:
  12. title -- returns the page's title, or pagename
  13. exists -- returns whether the page exists
  14. pageid -- returns an integer ID representing the page
  15. url -- returns the page's URL
  16. namespace -- returns the page's namespace as an integer
  17. protection -- returns the page's current protection status
  18. creator -- returns the page's creator (first user to edit)
  19. is_talkpage -- returns True if the page is a talkpage, else False
  20. is_redirect -- returns True if the page is a redirect, else False
  21. toggle_talk -- returns a content page's talk page, or vice versa
  22. get -- returns page content
  23. get_redirect_target -- if the page is a redirect, returns its destination
  24. """
  25. def __init__(self, site, title, follow_redirects=False):
  26. """Constructor for new Page instances.
  27. Takes three arguments: a Site object, the Page's title (or pagename),
  28. and whether or not to follow redirects (optional, defaults to False).
  29. As with User, site.get_page() is preferred. Site's method has support
  30. for a default `follow_redirects` value in our config, while __init__
  31. always defaults to False.
  32. __init__ will not do any API queries, but it will use basic namespace
  33. logic to determine our namespace ID and if we are a talkpage.
  34. """
  35. self._site = site
  36. self._title = title.strip()
  37. self._follow_redirects = self._keep_following = follow_redirects
  38. self._exists = 0
  39. self._pageid = None
  40. self._is_redirect = None
  41. self._lastrevid = None
  42. self._protection = None
  43. self._fullurl = None
  44. self._content = None
  45. self._creator = None
  46. # Try to determine the page's namespace using our site's namespace
  47. # converter:
  48. prefix = self._title.split(":", 1)[0]
  49. if prefix != title: # ignore a page that's titled "Category" or "User"
  50. try:
  51. self._namespace = self._site.namespace_name_to_id(prefix)
  52. except NamespaceNotFoundError:
  53. self._namespace = 0
  54. else:
  55. self._namespace = 0
  56. # Is this a talkpage? Talkpages have odd IDs, while content pages have
  57. # even IDs, excluding the "special" namespaces:
  58. if self._namespace < 0:
  59. self._is_talkpage = False
  60. else:
  61. self._is_talkpage = self._namespace % 2 == 1
  62. def _force_validity(self):
  63. """Used to ensure that our page's title is valid.
  64. If this method is called when our page is not valid (and after
  65. _load_attributes() has been called), InvalidPageError will be raised.
  66. Note that validity != existence. If a page's title is invalid (e.g, it
  67. contains "[") it will always be invalid, and cannot be edited.
  68. """
  69. if self._exists == 1:
  70. e = "Page '{0}' is invalid.".format(self._title)
  71. raise InvalidPageError(e)
  72. def _force_existence(self):
  73. """Used to ensure that our page exists.
  74. If this method is called when our page doesn't exist (and after
  75. _load_attributes() has been called), PageNotFoundError will be raised.
  76. It will also call _force_validity() beforehand.
  77. """
  78. self._force_validity()
  79. if self._exists == 2:
  80. e = "Page '{0}' does not exist.".format(self._title)
  81. raise PageNotFoundError(e)
  82. def _load_wrapper(self):
  83. """Calls _load_attributes() and follows redirects if we're supposed to.
  84. This method will only follow redirects if follow_redirects=True was
  85. passed to __init__() (perhaps indirectly passed by site.get_page()).
  86. It avoids the API's &redirects param in favor of manual following,
  87. so we can act more realistically (we don't follow double redirects, and
  88. circular redirects don't break us).
  89. This will raise RedirectError if we have a problem following, but that
  90. is a bug and should NOT happen.
  91. If we're following a redirect, this will make a grand total of three
  92. API queries. It's a lot, but each one is quite small.
  93. """
  94. self._load_attributes()
  95. if self._keep_following and self._is_redirect:
  96. self._title = self.get_redirect_target()
  97. self._keep_following = False # don't follow double redirects
  98. self._content = None # reset the content we just loaded
  99. self._load_attributes()
  100. def _load_attributes(self, result=None):
  101. """Loads various data from the API in a single query.
  102. Loads self._title, ._exists, ._is_redirect, ._pageid, ._fullurl,
  103. ._protection, ._namespace, ._is_talkpage, ._creator, and ._lastrevid
  104. using the API. It will do a query of its own unless `result` is
  105. provided, in which case we'll pretend `result` is what the query
  106. returned.
  107. Assuming the API is sound, this should not raise any exceptions.
  108. """
  109. if result is None:
  110. params = {"action": "query", "rvprop": "user", "rvdir": "newer",
  111. "prop": "info|revisions", "rvlimit": 1,
  112. "titles": self._title, "inprop": "protection|url"}
  113. result = self._site._api_query(params)
  114. res = result["query"]["pages"].values()[0]
  115. # Normalize our pagename/title thing:
  116. self._title = res["title"]
  117. try:
  118. res["redirect"]
  119. except KeyError:
  120. self._is_redirect = False
  121. else:
  122. self._is_redirect = True
  123. self._pageid = result["query"]["pages"].keys()[0]
  124. if int(self._pageid) < 0:
  125. try:
  126. res["missing"]
  127. except KeyError:
  128. # If it has a negative ID and it's invalid, then break here,
  129. # because there's no other data for us to get:
  130. self._exists = 1
  131. return
  132. else:
  133. # If it has a negative ID and it's missing; we can still get
  134. # data like the namespace, protection, and URL:
  135. self._exists = 2
  136. else:
  137. self._exists = 3
  138. self._fullurl = res["fullurl"]
  139. self._protection = res["protection"]
  140. # We've determined the namespace and talkpage status in __init__()
  141. # based on the title, but now we can be sure:
  142. self._namespace = res["ns"]
  143. self._is_talkpage = self._namespace % 2 == 1 # talkpages have odd IDs
  144. # These last two fields will only be specified if the page exists:
  145. self._lastrevid = res.get("lastrevid")
  146. try:
  147. self._creator = res['revisions'][0]['user']
  148. except KeyError:
  149. pass
  150. def _load_content(self, result=None):
  151. """Loads current page content from the API.
  152. If `result` is provided, we'll pretend that is the result of an API
  153. query and try to get content from that. Otherwise, we'll do an API
  154. query on our own.
  155. Don't call this directly, ever - use .get(force=True) if you want to
  156. force content reloading.
  157. """
  158. if result is None:
  159. params = {"action": "query", "prop": "revisions", "rvlimit": 1,
  160. "rvprop": "content", "titles": self._title}
  161. result = self._site._api_query(params)
  162. res = result["query"]["pages"].values()[0]
  163. try:
  164. content = res["revisions"][0]["*"]
  165. self._content = content
  166. except KeyError:
  167. # This can only happen if the page was deleted since we last called
  168. # self._load_attributes(). In that case, some of our attributes are
  169. # outdated, so force another self._load_attributes():
  170. self._load_attributes()
  171. self._force_existence()
  172. def title(self, force=False):
  173. """Returns the Page's title, or pagename.
  174. This won't do any API queries on its own unless force is True, in which
  175. case the title will be forcibly reloaded from the API (normalizing it,
  176. and following redirects if follow_redirects=True was passed to
  177. __init__()). Any other methods that do API queries will reload title on
  178. their own, however, like exists() and get().
  179. """
  180. if force:
  181. self._load_wrapper()
  182. return self._title
  183. def exists(self, force=False):
  184. """Returns information about whether the Page exists or not.
  185. The returned "information" is a tuple with two items. The first is a
  186. bool, either True if the page exists or False if it does not. The
  187. second is a string giving more information, either "invalid", (title
  188. is invalid, e.g. it contains "["), "missing", or "exists".
  189. Makes an API query if force is True or if we haven't already made one.
  190. """
  191. cases = {
  192. 0: (None, "unknown"),
  193. 1: (False, "invalid"),
  194. 2: (False, "missing"),
  195. 3: (True, "exists"),
  196. }
  197. if self._exists == 0 or force:
  198. self._load_wrapper()
  199. return cases[self._exists]
  200. def pageid(self, force=False):
  201. """Returns an integer ID representing the Page.
  202. Makes an API query if force is True or if we haven't already made one.
  203. Raises InvalidPageError or PageNotFoundError if the page name is
  204. invalid or the page does not exist, respectively.
  205. """
  206. if self._exists == 0 or force:
  207. self._load_wrapper()
  208. self._force_existence() # missing pages do not have IDs
  209. return self._pageid
  210. def url(self, force=False):
  211. """Returns the page's URL.
  212. Like title(), this won't do any API queries on its own unless force is
  213. True. If the API was never queried for this page, we will attempt to
  214. determine the URL ourselves based on the title.
  215. """
  216. if force:
  217. self._load_wrapper()
  218. if self._fullurl is not None:
  219. return self._fullurl
  220. else:
  221. slug = quote(self._title.replace(" ", "_"), safe="/:")
  222. path = self._site._article_path.replace("$1", slug)
  223. return ''.join((self._site._base_url, path))
  224. def namespace(self, force=False):
  225. """Returns the page's namespace ID (an integer).
  226. Like title(), this won't do any API queries on its own unless force is
  227. True. If the API was never queried for this page, we will attempt to
  228. determine the namespace ourselves based on the title.
  229. """
  230. if force:
  231. self._load_wrapper()
  232. return self._namespace
  233. def protection(self, force=False):
  234. """Returns the page's current protection status.
  235. Makes an API query if force is True or if we haven't already made one.
  236. Raises InvalidPageError if the page name is invalid. Will not raise an
  237. error if the page is missing because those can still be protected.
  238. """
  239. if self._exists == 0 or force:
  240. self._load_wrapper()
  241. self._force_validity() # invalid pages cannot be protected
  242. return self._protection
  243. def creator(self, force=False):
  244. """Returns the page's creator (i.e., the first user to edit the page).
  245. Makes an API query if force is True or if we haven't already made one.
  246. Normally, we can get the creator along with everything else (except
  247. content) in self._load_attributes(). However, due to a limitation in
  248. the API (can't get the editor of one revision and the content of
  249. another at both ends of the history), if our other attributes were only
  250. loaded from get(), we'll have to do another API query. This is done
  251. by calling ourselves again with force=True.
  252. Raises InvalidPageError or PageNotFoundError if the page name is
  253. invalid or the page does not exist, respectively.
  254. """
  255. if self._exists == 0 or force:
  256. self._load_wrapper()
  257. self._force_existence()
  258. if not self._creator and not force:
  259. self.creator(force=True)
  260. return self._creator
  261. def is_talkpage(self, force=False):
  262. """Returns True if the page is a talkpage, else False.
  263. Like title(), this won't do any API queries on its own unless force is
  264. True. If the API was never queried for this page, we will attempt to
  265. determine the talkpage status ourselves based on its namespace ID.
  266. """
  267. if force:
  268. self._load_wrapper()
  269. return self._is_talkpage
  270. def is_redirect(self, force=False):
  271. """Returns True if the page is a redirect, else False.
  272. Makes an API query if force is True or if we haven't already made one.
  273. We will return False even if the page does not exist or is invalid.
  274. """
  275. if self._exists == 0 or force:
  276. self._load_wrapper()
  277. return self._is_redirect
  278. def toggle_talk(self, force=False, follow_redirects=None):
  279. """Returns a content page's talk page, or vice versa.
  280. The title of the new page is determined by namespace logic, not API
  281. queries. We won't make any API queries on our own unless force is True,
  282. and the only reason then would be to forcibly update the title or
  283. follow redirects if we haven't already made an API query.
  284. If `follow_redirects` is anything other than None (the default), it
  285. will be passed to the new Page's __init__(). Otherwise, we'll use the
  286. value passed to our own __init__().
  287. Will raise InvalidPageError if we try to get the talk page of a special
  288. page (in the Special: or Media: namespaces), but we won't raise an
  289. exception if our page is otherwise missing or invalid.
  290. """
  291. if force:
  292. self._load_wrapper()
  293. if self._namespace < 0:
  294. ns = self._site.namespace_id_to_name(self._namespace)
  295. e = "Pages in the {0} namespace can't have talk pages.".format(ns)
  296. raise InvalidPageError(e)
  297. if self._is_talkpage:
  298. new_ns = self._namespace - 1
  299. else:
  300. new_ns = self._namespace + 1
  301. try:
  302. body = self._title.split(":", 1)[1]
  303. except IndexError:
  304. body = self._title
  305. new_prefix = self._site.namespace_id_to_name(new_ns)
  306. # If the new page is in namespace 0, don't do ":Title" (it's correct,
  307. # but unnecessary), just do "Title":
  308. if new_prefix:
  309. new_title = ':'.join((new_prefix, body))
  310. else:
  311. new_title = body
  312. if follow_redirects is None:
  313. follow_redirects = self._follow_redirects
  314. return Page(self._site, new_title, follow_redirects)
  315. def get(self, force=False):
  316. """Returns page content, which is cached if you try to call get again.
  317. Use `force` to forcibly reload page content even if we've already
  318. loaded some. This is good if you want to edit a page multiple times,
  319. and you want to get updated content before you make your second edit.
  320. Raises InvalidPageError or PageNotFoundError if the page name is
  321. invalid or the page does not exist, respectively.
  322. """
  323. if force or self._exists == 0:
  324. # Kill two birds with one stone by doing an API query for both our
  325. # attributes and our page content:
  326. params = {"action": "query", "rvprop": "content", "rvlimit": 1,
  327. "prop": "info|revisions", "inprop": "protection|url",
  328. "titles": self._title}
  329. result = self._site._api_query(params)
  330. self._load_attributes(result=result)
  331. self._force_existence()
  332. self._load_content(result=result)
  333. # Follow redirects if we're told to:
  334. if self._keep_following and self._is_redirect:
  335. self._title = self.get_redirect_target()
  336. self._keep_following = False # don't follow double redirects
  337. self._content = None # reset the content we just loaded
  338. self.get(force=True)
  339. return self._content
  340. # Make sure we're dealing with a real page here. This may be outdated
  341. # if the page was deleted since we last called self._load_attributes(),
  342. # but self._load_content() can handle that:
  343. self._force_existence()
  344. if self._content is None:
  345. self._load_content()
  346. return self._content
  347. def get_redirect_target(self, force=False):
  348. """If the page is a redirect, returns its destination.
  349. Use `force` to forcibly reload content even if we've already loaded
  350. some before. Note that this method calls get() for page content.
  351. Raises InvalidPageError or PageNotFoundError if the page name is
  352. invalid or the page does not exist, respectively. Raises RedirectError
  353. if the page is not a redirect.
  354. """
  355. content = self.get(force)
  356. regexp = "^\s*\#\s*redirect\s*\[\[(.*?)\]\]"
  357. try:
  358. return re.findall(regexp, content, flags=re.IGNORECASE)[0]
  359. except IndexError:
  360. e = "The page does not appear to have a redirect target."
  361. raise RedirectError(e)