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ů.

617 řádky
25 KiB

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