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.

site.py 21 KiB

13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. # -*- coding: utf-8 -*-
  2. from cookielib import CookieJar
  3. from gzip import GzipFile
  4. from json import loads
  5. from re import escape as re_escape, match as re_match
  6. from StringIO import StringIO
  7. from time import sleep
  8. from urllib import unquote_plus, urlencode
  9. from urllib2 import build_opener, HTTPCookieProcessor, URLError
  10. from urlparse import urlparse
  11. from wiki.category import Category
  12. from wiki.constants import *
  13. from wiki.exceptions import *
  14. from wiki.page import Page
  15. from wiki.user import User
  16. class Site(object):
  17. """
  18. EarwigBot's Wiki Toolset: Site Class
  19. Represents a Site, with support for API queries and returning Pages, Users,
  20. and Categories. The constructor takes a bunch of arguments and you probably
  21. won't need to call it directly, rather tools.get_site() for returning Site
  22. instances, tools.add_site() for adding new ones to config, and
  23. tools.del_site() for removing old ones from config, should suffice.
  24. Public methods:
  25. name -- returns our name (or "wikiid"), like "enwiki"
  26. project -- returns our project name, like "wikipedia"
  27. lang -- returns our language code, like "en"
  28. domain -- returns our web domain, like "en.wikipedia.org"
  29. api_query -- does an API query with the given kwargs as params
  30. namespace_id_to_name -- given a namespace ID, returns associated name(s)
  31. namespace_name_to_id -- given a namespace name, returns associated id
  32. get_page -- returns a Page object for the given title
  33. get_category -- returns a Category object for the given title
  34. get_user -- returns a User object for the given username
  35. """
  36. def __init__(self, name=None, project=None, lang=None, base_url=None,
  37. article_path=None, script_path=None, sql=(None, None),
  38. namespaces=None, login=(None, None), cookiejar=None,
  39. user_agent=None, assert_edit=None, maxlag=None):
  40. """Constructor for new Site instances.
  41. This probably isn't necessary to call yourself unless you're building a
  42. Site that's not in your config and you don't want to add it - normally
  43. all you need is tools.get_site(name), which creates the Site for you
  44. based on your config file. We accept a bunch of kwargs, but the only
  45. ones you really "need" are `base_url` and `script_path` - this is
  46. enough to figure out an API url. `login`, a tuple of
  47. (username, password), is highly recommended. `cookiejar` will be used
  48. to store cookies, and we'll use a normal CookieJar if none is given.
  49. First, we'll store the given arguments as attributes, then set up our
  50. URL opener. We'll load any of the attributes that weren't given from
  51. the API, and then log in if a username/pass was given and we aren't
  52. already logged in.
  53. """
  54. # Attributes referring to site information, filled in by an API query
  55. # if they are missing (and an API url can be determined):
  56. self._name = name
  57. self._project = project
  58. self._lang = lang
  59. self._base_url = base_url
  60. self._article_path = article_path
  61. self._script_path = script_path
  62. self._sql = sql
  63. self._namespaces = namespaces
  64. # Attributes used when querying the API:
  65. self._assert_edit = assert_edit
  66. self._maxlag = maxlag
  67. self._max_retries = 5
  68. # Set up cookiejar and URL opener for making API queries:
  69. if cookiejar is not None:
  70. self._cookiejar = cookiejar
  71. else:
  72. self._cookiejar = CookieJar()
  73. if user_agent is None:
  74. user_agent = USER_AGENT # Set default UA from wiki.constants
  75. self._opener = build_opener(HTTPCookieProcessor(self._cookiejar))
  76. self._opener.addheaders = [("User-Agent", user_agent),
  77. ("Accept-Encoding", "gzip")]
  78. # Get all of the above attributes that were not specified as arguments:
  79. self._load_attributes()
  80. # If we have a name/pass and the API says we're not logged in, log in:
  81. self._login_info = name, password = login
  82. if name is not None and password is not None:
  83. logged_in_as = self._get_username_from_cookies()
  84. if logged_in_as is None or name != logged_in_as:
  85. self._login(login)
  86. def __repr__(self):
  87. """Returns the canonical string representation of the Site."""
  88. res = ", ".join((
  89. "Site(name={_name!r}", "project={_project!r}", "lang={_lang!r}",
  90. "base_url={_base_url!r}", "article_path={_article_path!r}",
  91. "script_path={_script_path!r}", "assert_edit={_assert_edit!r}",
  92. "maxlag={_maxlag!r}", "sql={_sql!r}", "login={0}",
  93. "user_agent={2!r}", "cookiejar={1})"
  94. ))
  95. name, password = self._login_info
  96. login = "({0}, {1})".format(repr(name), "hidden" if password else None)
  97. cookies = self._cookiejar.__class__.__name__
  98. try:
  99. cookies += "({0!r})".format(self._cookiejar.filename)
  100. except AttributeError:
  101. cookies += "()"
  102. agent = self._opener.addheaders[0][1]
  103. return res.format(login, cookies, agent, **self.__dict__)
  104. def __str__(self):
  105. """Returns a nice string representation of the Site."""
  106. res = "<Site {0} ({1}:{2}) at {3}>"
  107. return res.format(self.name(), self.project(), self.lang(),
  108. self.domain())
  109. def _api_query(self, params, tries=0, wait=5):
  110. """Do an API query with `params` as a dict of parameters.
  111. This will first attempt to construct an API url from self._base_url and
  112. self._script_path. We need both of these, or else we'll raise
  113. SiteAPIError.
  114. We'll encode the given params, adding format=json along the way, as
  115. well as &assert= and &maxlag= based on self._assert_edit and _maxlag.
  116. We make the request through self._opener, which has built-in cookie
  117. support via self._cookiejar, a User-Agent (wiki.constants.USER_AGENT),
  118. and Accept-Encoding set to "gzip".
  119. Assuming everything went well, we'll gunzip the data (if compressed),
  120. load it as a JSON object, and return it.
  121. If our request failed for some reason, we'll raise SiteAPIError with
  122. details. If that reason was due to maxlag, we'll sleep for a bit and
  123. then repeat the query until we exceed self._max_retries.
  124. There's helpful MediaWiki API documentation at
  125. <http://www.mediawiki.org/wiki/API>.
  126. """
  127. if self._base_url is None or self._script_path is None:
  128. e = "Tried to do an API query, but no API URL is known."
  129. raise SiteAPIError(e)
  130. url = ''.join((self._base_url, self._script_path, "/api.php"))
  131. params["format"] = "json" # This is the only format we understand
  132. if self._assert_edit: # If requested, ensure that we're logged in
  133. params["assert"] = self._assert_edit
  134. if self._maxlag: # If requested, don't overload the servers
  135. params["maxlag"] = self._maxlag
  136. data = urlencode(params)
  137. print url, data # debug code
  138. try:
  139. response = self._opener.open(url, data)
  140. except URLError as error:
  141. if hasattr(error, "reason"):
  142. e = "API query failed: {0}.".format(error.reason)
  143. elif hasattr(error, "code"):
  144. e = "API query failed: got an error code of {0}."
  145. e = e.format(error.code)
  146. else:
  147. e = "API query failed."
  148. raise SiteAPIError(e)
  149. result = response.read()
  150. if response.headers.get("Content-Encoding") == "gzip":
  151. stream = StringIO(result)
  152. gzipper = GzipFile(fileobj=stream)
  153. result = gzipper.read()
  154. try:
  155. res = loads(result) # Parse as a JSON object
  156. except ValueError:
  157. e = "API query failed: JSON could not be decoded."
  158. raise SiteAPIError(e)
  159. try:
  160. code = res["error"]["code"]
  161. info = res["error"]["info"]
  162. except (TypeError, KeyError):
  163. return res
  164. if code == "maxlag":
  165. if tries >= self._max_retries:
  166. e = "Maximum number of retries reached ({0})."
  167. raise SiteAPIError(e.format(self._max_retries))
  168. tries += 1
  169. msg = 'Server says: "{0}". Retrying in {1} seconds ({2}/{3}).'
  170. print msg.format(info, wait, tries, self._max_retries)
  171. sleep(wait)
  172. return self._api_query(params, tries=tries, wait=wait*3)
  173. else:
  174. e = 'API query failed: got error "{0}"; server says: "{1}".'
  175. error = SiteAPIError(e.format(code, info))
  176. error.code, error.info = code, info
  177. raise error
  178. def _load_attributes(self, force=False):
  179. """Load data about our Site from the API.
  180. This function is called by __init__() when one of the site attributes
  181. was not given as a keyword argument. We'll do an API query to get the
  182. missing data, but only if there actually *is* missing data.
  183. Additionally, you can call this with `force=True` to forcibly reload
  184. all attributes.
  185. """
  186. # All attributes to be loaded, except _namespaces, which is a special
  187. # case because it requires additional params in the API query:
  188. attrs = [self._name, self._project, self._lang, self._base_url,
  189. self._article_path, self._script_path]
  190. params = {"action": "query", "meta": "siteinfo"}
  191. if not self._namespaces or force:
  192. params["siprop"] = "general|namespaces|namespacealiases"
  193. result = self._api_query(params)
  194. self._load_namespaces(result)
  195. elif all(attrs): # Everything is already specified and we're not told
  196. return # to force a reload, so do nothing
  197. else: # We're only loading attributes other than _namespaces
  198. params["siprop"] = "general"
  199. result = self._api_query(params)
  200. res = result["query"]["general"]
  201. self._name = res["wikiid"]
  202. self._project = res["sitename"].lower()
  203. self._lang = res["lang"]
  204. self._base_url = res["server"]
  205. self._article_path = res["articlepath"]
  206. self._script_path = res["scriptpath"]
  207. def _load_namespaces(self, result):
  208. """Fill self._namespaces with a dict of namespace IDs and names.
  209. Called by _load_attributes() with API data as `result` when
  210. self._namespaces was not given as an kwarg to __init__().
  211. """
  212. self._namespaces = {}
  213. for namespace in result["query"]["namespaces"].values():
  214. ns_id = namespace["id"]
  215. name = namespace["*"]
  216. try:
  217. canonical = namespace["canonical"]
  218. except KeyError:
  219. self._namespaces[ns_id] = [name]
  220. else:
  221. if name != canonical:
  222. self._namespaces[ns_id] = [name, canonical]
  223. else:
  224. self._namespaces[ns_id] = [name]
  225. for namespace in result["query"]["namespacealiases"]:
  226. ns_id = namespace["id"]
  227. alias = namespace["*"]
  228. self._namespaces[ns_id].append(alias)
  229. def _get_cookie(self, name, domain):
  230. """Return the named cookie unless it is expired or doesn't exist."""
  231. for cookie in self._cookiejar:
  232. if cookie.name == name and cookie.domain == domain:
  233. if cookie.is_expired():
  234. break
  235. return cookie
  236. def _get_username_from_cookies(self):
  237. """Try to return our username based solely on cookies.
  238. First, we'll look for a cookie named self._name + "Token", like
  239. "enwikiToken". If it exists and isn't expired, we'll assume it's valid
  240. and try to return the value of the cookie self._name + "UserName" (like
  241. "enwikiUserName"). This should work fine on wikis without single-user
  242. login.
  243. If `enwikiToken` doesn't exist, we'll try to find a cookie named
  244. `centralauth_Token`. If this exists and is not expired, we'll try to
  245. return the value of `centralauth_User`.
  246. If we didn't get any matches, we'll return None. Our goal here isn't to
  247. return the most likely username, or what we *want* our username to be
  248. (for that, we'd do self._login_info[0]), but rather to get our current
  249. username without an unnecessary ?action=query&meta=userinfo API query.
  250. """
  251. domain = self.domain()
  252. name = ''.join((self._name, "Token"))
  253. cookie = self._get_cookie(name, domain)
  254. if cookie is not None:
  255. name = ''.join((self._name, "UserName"))
  256. user_name = self._get_cookie(name, domain)
  257. if user_name is not None:
  258. return user_name.value
  259. name = "centralauth_Token"
  260. for cookie in self._cookiejar:
  261. if cookie.domain_initial_dot is False or cookie.is_expired():
  262. continue
  263. if cookie.name != name:
  264. continue
  265. # Build a regex that will match domains this cookie affects:
  266. search = ''.join(("(.*?)", re_escape(cookie.domain)))
  267. if re_match(search, domain): # Test it against our site
  268. user_name = self._get_cookie("centralauth_User", cookie.domain)
  269. if user_name is not None:
  270. return user_name.value
  271. def _get_username_from_api(self):
  272. """Do a simple API query to get our username and return it.
  273. This is a reliable way to make sure we are actually logged in, because
  274. it doesn't deal with annoying cookie logic, but it results in an API
  275. query that is unnecessary in some cases.
  276. Called by _get_username() (in turn called by get_user() with no
  277. username argument) when cookie lookup fails, probably indicating that
  278. we are logged out.
  279. """
  280. params = {"action": "query", "meta": "userinfo"}
  281. result = self._api_query(params)
  282. return result["query"]["userinfo"]["name"]
  283. def _get_username(self):
  284. """Return the name of the current user, whether logged in or not.
  285. First, we'll try to deduce it solely from cookies, to avoid an
  286. unnecessary API query. For the cookie-detection method, see
  287. _get_username_from_cookies()'s docs.
  288. If our username isn't in cookies, then we're probably not logged in, or
  289. something fishy is going on (like forced logout). In this case, do a
  290. single API query for our username (or IP address) and return that.
  291. """
  292. name = self._get_username_from_cookies()
  293. if name is not None:
  294. return name
  295. return self._get_username_from_api()
  296. def _save_cookiejar(self):
  297. """Try to save our cookiejar after doing a (normal) login or logout.
  298. Calls the standard .save() method with no filename. Don't fret if our
  299. cookiejar doesn't support saving (CookieJar raises AttributeError,
  300. FileCookieJar raises NotImplementedError) or no default filename was
  301. given (LWPCookieJar and MozillaCookieJar raise ValueError).
  302. """
  303. try:
  304. self._cookiejar.save()
  305. except (AttributeError, NotImplementedError, ValueError):
  306. pass
  307. def _login(self, login, token=None, attempt=0):
  308. """Safely login through the API.
  309. Normally, this is called by __init__() if a username and password have
  310. been provided and no valid login cookies were found. The only other
  311. time it needs to be called is when those cookies expire, which is done
  312. automatically by api_query() if a query fails.
  313. Recent versions of MediaWiki's API have fixed a CSRF vulnerability,
  314. requiring login to be done in two separate requests. If the response
  315. from from our initial request is "NeedToken", we'll do another one with
  316. the token. If login is successful, we'll try to save our cookiejar.
  317. Raises LoginError on login errors (duh), like bad passwords and
  318. nonexistent usernames.
  319. `login` is a (username, password) tuple. `token` is the token returned
  320. from our first request, and `attempt` is to prevent getting stuck in a
  321. loop if MediaWiki isn't acting right.
  322. """
  323. name, password = login
  324. params = {"action": "login", "lgname": name, "lgpassword": password}
  325. if token is not None:
  326. params["lgtoken"] = token
  327. result = self._api_query(params)
  328. res = result["login"]["result"]
  329. if res == "Success":
  330. self._save_cookiejar()
  331. elif res == "NeedToken" and attempt == 0:
  332. token = result["login"]["token"]
  333. return self._login(login, token, attempt=1)
  334. else:
  335. if res == "Illegal":
  336. e = "The provided username is illegal."
  337. elif res == "NotExists":
  338. e = "The provided username does not exist."
  339. elif res == "EmptyPass":
  340. e = "No password was given."
  341. elif res == "WrongPass" or res == "WrongPluginPass":
  342. e = "The given password is incorrect."
  343. else:
  344. e = "Couldn't login; server says '{0}'.".format(res)
  345. raise LoginError(e)
  346. def _logout(self):
  347. """Safely logout through the API.
  348. We'll do a simple API request (api.php?action=logout), clear our
  349. cookiejar (which probably contains now-invalidated cookies) and try to
  350. save it, if it supports that sort of thing.
  351. """
  352. params = {"action": "logout"}
  353. self._api_query(params)
  354. self._cookiejar.clear()
  355. self._save_cookiejar()
  356. def api_query(self, **kwargs):
  357. """Do an API query with `kwargs` as the parameters.
  358. See _api_query()'s documentation for details.
  359. """
  360. return self._api_query(kwargs)
  361. def name(self):
  362. """Returns the Site's name (or "wikiid" in the API), like "enwiki"."""
  363. return self._name
  364. def project(self):
  365. """Returns the Site's project name in lowercase, like "wikipedia"."""
  366. return self._project
  367. def lang(self):
  368. """Returns the Site's language code, like "en" or "es"."""
  369. return self._lang
  370. def domain(self):
  371. """Returns the Site's web domain, like "en.wikipedia.org"."""
  372. return urlparse(self._base_url).netloc
  373. def namespace_id_to_name(self, ns_id, all=False):
  374. """Given a namespace ID, returns associated namespace names.
  375. If all is False (default), we'll return the first name in the list,
  376. which is usually the localized version. Otherwise, we'll return the
  377. entire list, which includes the canonical name.
  378. For example, returns u"Wikipedia" if ns_id=4 and all=False on enwiki;
  379. returns [u"Wikipedia", u"Project"] if ns_id=4 and all=True.
  380. Raises NamespaceNotFoundError if the ID is not found.
  381. """
  382. try:
  383. if all:
  384. return self._namespaces[ns_id]
  385. else:
  386. return self._namespaces[ns_id][0]
  387. except KeyError:
  388. e = "There is no namespace with id {0}.".format(ns_id)
  389. raise NamespaceNotFoundError(e)
  390. def namespace_name_to_id(self, name):
  391. """Given a namespace name, returns the associated ID.
  392. Like namespace_id_to_name(), but reversed. Case is ignored, because
  393. namespaces are assumed to be case-insensitive.
  394. Raises NamespaceNotFoundError if the name is not found.
  395. """
  396. lname = name.lower()
  397. for ns_id, names in self._namespaces.items():
  398. lnames = [n.lower() for n in names] # Be case-insensitive
  399. if lname in lnames:
  400. return ns_id
  401. e = "There is no namespace with name '{0}'.".format(name)
  402. raise NamespaceNotFoundError(e)
  403. def get_page(self, title, follow_redirects=False):
  404. """Returns a Page object for the given title (pagename).
  405. Will return a Category object instead if the given title is in the
  406. category namespace. As Category is a subclass of Page, this should not
  407. cause problems.
  408. Note that this doesn't do any direct checks for existence or
  409. redirect-following - Page's methods provide that.
  410. """
  411. prefixes = self.namespace_id_to_name(NS_CATEGORY, all=True)
  412. prefix = title.split(":", 1)[0]
  413. if prefix != title: # Avoid a page that is simply "Category"
  414. if prefix in prefixes:
  415. return Category(self, title, follow_redirects)
  416. return Page(self, title, follow_redirects)
  417. def get_category(self, catname, follow_redirects=False):
  418. """Returns a Category object for the given category name.
  419. `catname` should be given *without* a namespace prefix. This method is
  420. really just shorthand for get_page("Category:" + catname).
  421. """
  422. prefix = self.namespace_id_to_name(NS_CATEGORY)
  423. pagename = ':'.join((prefix, catname))
  424. return Category(self, pagename, follow_redirects)
  425. def get_user(self, username=None):
  426. """Returns a User object for the given username.
  427. If `username` is left as None, then a User object representing the
  428. currently logged-in (or anonymous!) user is returned.
  429. """
  430. if username is None:
  431. username = self._get_username()
  432. return User(self, username)