A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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