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

848 řádky
36 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from cookielib import CookieJar
  23. from gzip import GzipFile
  24. from json import loads
  25. from logging import getLogger, NullHandler
  26. from os.path import expanduser
  27. from re import escape as re_escape, match as re_match
  28. from StringIO import StringIO
  29. from threading import Lock
  30. from time import sleep, time
  31. from urllib import quote_plus
  32. from urllib2 import build_opener, HTTPCookieProcessor, URLError
  33. from urlparse import urlparse
  34. try:
  35. import oursql
  36. except ImportError:
  37. oursql = None
  38. from earwigbot import exceptions
  39. from earwigbot.wiki import constants
  40. from earwigbot.wiki.category import Category
  41. from earwigbot.wiki.page import Page
  42. from earwigbot.wiki.user import User
  43. __all__ = ["Site"]
  44. class Site(object):
  45. """
  46. **EarwigBot: Wiki Toolset: Site**
  47. Represents a site, with support for API queries and returning
  48. :py:class:`~earwigbot.wiki.page.Page`,
  49. :py:class:`~earwigbot.wiki.user.User`,
  50. and :py:class:`~earwigbot.wiki.category.Category` objects. The constructor
  51. takes a bunch of arguments and you probably won't need to call it directly,
  52. rather :py:meth:`wiki.get_site() <earwigbot.wiki.sitesdb.SitesDB.get_site>`
  53. for returning :py:class:`Site`
  54. instances, :py:meth:`wiki.add_site()
  55. <earwigbot.wiki.sitesdb.SitesDB.add_site>` for adding new ones to our
  56. database, and :py:meth:`wiki.remove_site()
  57. <earwigbot.wiki.sitesdb.SitesDB.remove_site>` for removing old ones from
  58. our database, should suffice.
  59. *Attributes:*
  60. - :py:attr:`name`: the site's name (or "wikiid"), like ``"enwiki"``
  61. - :py:attr:`project`: the site's project name, like ``"wikipedia"``
  62. - :py:attr:`lang`: the site's language code, like ``"en"``
  63. - :py:attr:`domain`: the site's web domain, like ``"en.wikipedia.org"``
  64. - :py:attr:`url`: the site's URL, like ``"https://en.wikipedia.org"``
  65. *Public methods:*
  66. - :py:meth:`api_query`: does an API query with kwargs as params
  67. - :py:meth:`sql_query`: does an SQL query and yields its results
  68. - :py:meth:`get_maxlag`: returns the internal database lag
  69. - :py:meth:`get_replag`: estimates the external database lag
  70. - :py:meth:`namespace_id_to_name`: returns names associated with an NS id
  71. - :py:meth:`namespace_name_to_id`: returns the ID associated with a NS name
  72. - :py:meth:`get_page`: returns a Page for the given title
  73. - :py:meth:`get_category`: returns a Category for the given title
  74. - :py:meth:`get_user`: returns a User object for the given name
  75. - :py:meth:`delegate`: controls when the API or SQL is used
  76. """
  77. SERVICE_API = 1
  78. SERVICE_SQL = 2
  79. def __init__(self, name=None, project=None, lang=None, base_url=None,
  80. article_path=None, script_path=None, sql=None,
  81. namespaces=None, login=(None, None), cookiejar=None,
  82. user_agent=None, use_https=False, assert_edit=None,
  83. maxlag=None, wait_between_queries=3, logger=None,
  84. search_config=(None, None)):
  85. """Constructor for new Site instances.
  86. This probably isn't necessary to call yourself unless you're building a
  87. Site that's not in your config and you don't want to add it - normally
  88. all you need is wiki.get_site(name), which creates the Site for you
  89. based on your config file and the sites database. We accept a bunch of
  90. kwargs, but the only ones you really "need" are *base_url* and
  91. *script_path*; this is enough to figure out an API url. *login*, a
  92. tuple of (username, password), is highly recommended. *cookiejar will
  93. be used to store cookies, and we'll use a normal CookieJar if none is
  94. given.
  95. First, we'll store the given arguments as attributes, then set up our
  96. URL opener. We'll load any of the attributes that weren't given from
  97. the API, and then log in if a username/pass was given and we aren't
  98. already logged in.
  99. """
  100. # Attributes referring to site information, filled in by an API query
  101. # if they are missing (and an API url can be determined):
  102. self._name = name
  103. self._project = project
  104. self._lang = lang
  105. self._base_url = base_url
  106. self._article_path = article_path
  107. self._script_path = script_path
  108. self._namespaces = namespaces
  109. # Attributes used for API queries:
  110. self._use_https = use_https
  111. self._assert_edit = assert_edit
  112. self._maxlag = maxlag
  113. self._wait_between_queries = wait_between_queries
  114. self._max_retries = 6
  115. self._last_query_time = 0
  116. self._api_lock = Lock()
  117. self._api_info_cache = {"maxlag": 0, "lastcheck": 0}
  118. # Attributes used for SQL queries:
  119. self._sql_data = sql
  120. self._sql_conn = None
  121. self._sql_lock = Lock()
  122. self._sql_info_cache = {"replag": 0, "lastcheck": 0, "usable": None}
  123. # Attribute used in copyright violation checks (see CopyrightMixIn):
  124. self._search_config = search_config
  125. # Set up cookiejar and URL opener for making API queries:
  126. if cookiejar:
  127. self._cookiejar = cookiejar
  128. else:
  129. self._cookiejar = CookieJar()
  130. if not user_agent:
  131. user_agent = constants.USER_AGENT # Set default UA
  132. self._opener = build_opener(HTTPCookieProcessor(self._cookiejar))
  133. self._opener.addheaders = [("User-Agent", user_agent),
  134. ("Accept-Encoding", "gzip")]
  135. # Get all of the above attributes that were not specified as arguments:
  136. self._load_attributes()
  137. # Set up our internal logger:
  138. if logger:
  139. self._logger = logger
  140. else: # Just set up a null logger to eat up our messages:
  141. self._logger = getLogger("earwigbot.wiki")
  142. self._logger.addHandler(NullHandler())
  143. # If we have a name/pass and the API says we're not logged in, log in:
  144. self._login_info = name, password = login
  145. if name and password:
  146. logged_in_as = self._get_username_from_cookies()
  147. if not logged_in_as or name != logged_in_as:
  148. self._login(login)
  149. def __repr__(self):
  150. """Return the canonical string representation of the Site."""
  151. res = ", ".join((
  152. "Site(name={_name!r}", "project={_project!r}", "lang={_lang!r}",
  153. "base_url={_base_url!r}", "article_path={_article_path!r}",
  154. "script_path={_script_path!r}", "use_https={_use_https!r}",
  155. "assert_edit={_assert_edit!r}", "maxlag={_maxlag!r}",
  156. "sql={_sql_data!r}", "login={0}", "user_agent={2!r}",
  157. "cookiejar={1})"))
  158. name, password = self._login_info
  159. login = "({0}, {1})".format(repr(name), "hidden" if password else None)
  160. cookies = self._cookiejar.__class__.__name__
  161. try:
  162. cookies += "({0!r})".format(self._cookiejar.filename)
  163. except AttributeError:
  164. cookies += "()"
  165. agent = self._opener.addheaders[0][1]
  166. return res.format(login, cookies, agent, **self.__dict__)
  167. def __str__(self):
  168. """Return a nice string representation of the Site."""
  169. res = "<Site {0} ({1}:{2}) at {3}>"
  170. return res.format(self.name, self.project, self.lang, self.domain)
  171. def _unicodeify(self, value, encoding="utf8"):
  172. """Return input as unicode if it's not unicode to begin with."""
  173. if isinstance(value, unicode):
  174. return value
  175. return unicode(value, encoding)
  176. def _urlencode_utf8(self, params):
  177. """Implement urllib.urlencode() with support for unicode input."""
  178. enc = lambda s: s.encode("utf8") if isinstance(s, unicode) else str(s)
  179. args = []
  180. for key, val in params.iteritems():
  181. key = quote_plus(enc(key))
  182. val = quote_plus(enc(val))
  183. args.append(key + "=" + val)
  184. return "&".join(args)
  185. def _api_query(self, params, tries=0, wait=5, ignore_maxlag=False):
  186. """Do an API query with *params* as a dict of parameters.
  187. See the documentation for :py:meth:`api_query` for full implementation
  188. details.
  189. """
  190. since_last_query = time() - self._last_query_time # Throttling support
  191. if since_last_query < self._wait_between_queries:
  192. wait_time = self._wait_between_queries - since_last_query
  193. log = "Throttled: waiting {0} seconds".format(round(wait_time, 2))
  194. self._logger.debug(log)
  195. sleep(wait_time)
  196. self._last_query_time = time()
  197. url, data = self._build_api_query(params, ignore_maxlag)
  198. if "lgpassword" in params:
  199. self._logger.debug("{0} -> <hidden>".format(url))
  200. else:
  201. self._logger.debug("{0} -> {1}".format(url, data))
  202. try:
  203. response = self._opener.open(url, data)
  204. except URLError as error:
  205. if hasattr(error, "reason"):
  206. e = "API query failed: {0}.".format(error.reason)
  207. elif hasattr(error, "code"):
  208. e = "API query failed: got an error code of {0}."
  209. e = e.format(error.code)
  210. else:
  211. e = "API query failed."
  212. raise exceptions.APIError(e)
  213. result = response.read()
  214. if response.headers.get("Content-Encoding") == "gzip":
  215. stream = StringIO(result)
  216. gzipper = GzipFile(fileobj=stream)
  217. result = gzipper.read()
  218. return self._handle_api_query_result(result, params, tries, wait)
  219. def _build_api_query(self, params, ignore_maxlag):
  220. """Given API query params, return the URL to query and POST data."""
  221. if not self._base_url or self._script_path is None:
  222. e = "Tried to do an API query, but no API URL is known."
  223. raise exceptions.APIError(e)
  224. url = ''.join((self.url, self._script_path, "/api.php"))
  225. params["format"] = "json" # This is the only format we understand
  226. if self._assert_edit: # If requested, ensure that we're logged in
  227. params["assert"] = self._assert_edit
  228. if self._maxlag and not ignore_maxlag:
  229. # If requested, don't overload the servers:
  230. params["maxlag"] = self._maxlag
  231. data = self._urlencode_utf8(params)
  232. return url, data
  233. def _handle_api_query_result(self, result, params, tries, wait):
  234. """Given the result of an API query, attempt to return useful data."""
  235. try:
  236. res = loads(result) # Try to parse as a JSON object
  237. except ValueError:
  238. e = "API query failed: JSON could not be decoded."
  239. raise exceptions.APIError(e)
  240. try:
  241. code = res["error"]["code"]
  242. info = res["error"]["info"]
  243. except (TypeError, KeyError): # Having these keys indicates a problem
  244. return res # All is well; return the decoded JSON
  245. if code == "maxlag": # We've been throttled by the server
  246. if tries >= self._max_retries:
  247. e = "Maximum number of retries reached ({0})."
  248. raise exceptions.APIError(e.format(self._max_retries))
  249. tries += 1
  250. msg = 'Server says "{0}"; retrying in {1} seconds ({2}/{3})'
  251. self._logger.info(msg.format(info, wait, tries, self._max_retries))
  252. sleep(wait)
  253. return self._api_query(params, tries=tries, wait=wait*2)
  254. else: # Some unknown error occurred
  255. e = 'API query failed: got error "{0}"; server says: "{1}".'
  256. error = exceptions.APIError(e.format(code, info))
  257. error.code, error.info = code, info
  258. raise error
  259. def _load_attributes(self, force=False):
  260. """Load data about our Site from the API.
  261. This function is called by __init__() when one of the site attributes
  262. was not given as a keyword argument. We'll do an API query to get the
  263. missing data, but only if there actually *is* missing data.
  264. Additionally, you can call this with *force* set to True to forcibly
  265. reload all attributes.
  266. """
  267. # All attributes to be loaded, except _namespaces, which is a special
  268. # case because it requires additional params in the API query:
  269. attrs = [self._name, self._project, self._lang, self._base_url,
  270. self._article_path, self._script_path]
  271. params = {"action": "query", "meta": "siteinfo", "siprop": "general"}
  272. if not self._namespaces or force:
  273. params["siprop"] += "|namespaces|namespacealiases"
  274. result = self.api_query(**params)
  275. self._load_namespaces(result)
  276. elif all(attrs): # Everything is already specified and we're not told
  277. return # to force a reload, so do nothing
  278. else: # We're only loading attributes other than _namespaces
  279. result = self.api_query(**params)
  280. res = result["query"]["general"]
  281. self._name = res["wikiid"]
  282. self._project = res["sitename"].lower()
  283. self._lang = res["lang"]
  284. self._base_url = res["server"]
  285. self._article_path = res["articlepath"]
  286. self._script_path = res["scriptpath"]
  287. def _load_namespaces(self, result):
  288. """Fill self._namespaces with a dict of namespace IDs and names.
  289. Called by _load_attributes() with API data as *result* when
  290. self._namespaces was not given as an kwarg to __init__().
  291. """
  292. self._namespaces = {}
  293. for namespace in result["query"]["namespaces"].values():
  294. ns_id = namespace["id"]
  295. name = namespace["*"]
  296. try:
  297. canonical = namespace["canonical"]
  298. except KeyError:
  299. self._namespaces[ns_id] = [name]
  300. else:
  301. if name != canonical:
  302. self._namespaces[ns_id] = [name, canonical]
  303. else:
  304. self._namespaces[ns_id] = [name]
  305. for namespace in result["query"]["namespacealiases"]:
  306. ns_id = namespace["id"]
  307. alias = namespace["*"]
  308. self._namespaces[ns_id].append(alias)
  309. def _get_cookie(self, name, domain):
  310. """Return the named cookie unless it is expired or doesn't exist."""
  311. for cookie in self._cookiejar:
  312. if cookie.name == name and cookie.domain == domain:
  313. if cookie.is_expired():
  314. break
  315. return cookie
  316. def _get_username_from_cookies(self):
  317. """Try to return our username based solely on cookies.
  318. First, we'll look for a cookie named self._name + "Token", like
  319. "enwikiToken". If it exists and isn't expired, we'll assume it's valid
  320. and try to return the value of the cookie self._name + "UserName" (like
  321. "enwikiUserName"). This should work fine on wikis without single-user
  322. login.
  323. If `enwikiToken` doesn't exist, we'll try to find a cookie named
  324. `centralauth_Token`. If this exists and is not expired, we'll try to
  325. return the value of `centralauth_User`.
  326. If we didn't get any matches, we'll return None. Our goal here isn't to
  327. return the most likely username, or what we *want* our username to be
  328. (for that, we'd do self._login_info[0]), but rather to get our current
  329. username without an unnecessary ?action=query&meta=userinfo API query.
  330. """
  331. name = ''.join((self._name, "Token"))
  332. cookie = self._get_cookie(name, self.domain)
  333. if cookie:
  334. name = ''.join((self._name, "UserName"))
  335. user_name = self._get_cookie(name, self.domain)
  336. if user_name:
  337. return user_name.value
  338. name = "centralauth_Token"
  339. for cookie in self._cookiejar:
  340. if not cookie.domain_initial_dot or cookie.is_expired():
  341. continue
  342. if cookie.name != name:
  343. continue
  344. # Build a regex that will match domains this cookie affects:
  345. search = ''.join(("(.*?)", re_escape(cookie.domain)))
  346. if re_match(search, self.domain): # Test it against our site
  347. user_name = self._get_cookie("centralauth_User", cookie.domain)
  348. if user_name:
  349. return user_name.value
  350. def _get_username_from_api(self):
  351. """Do a simple API query to get our username and return it.
  352. This is a reliable way to make sure we are actually logged in, because
  353. it doesn't deal with annoying cookie logic, but it results in an API
  354. query that is unnecessary in some cases.
  355. Called by _get_username() (in turn called by get_user() with no
  356. username argument) when cookie lookup fails, probably indicating that
  357. we are logged out.
  358. """
  359. result = self.api_query(action="query", meta="userinfo")
  360. return result["query"]["userinfo"]["name"]
  361. def _get_username(self):
  362. """Return the name of the current user, whether logged in or not.
  363. First, we'll try to deduce it solely from cookies, to avoid an
  364. unnecessary API query. For the cookie-detection method, see
  365. _get_username_from_cookies()'s docs.
  366. If our username isn't in cookies, then we're probably not logged in, or
  367. something fishy is going on (like forced logout). In this case, do a
  368. single API query for our username (or IP address) and return that.
  369. """
  370. name = self._get_username_from_cookies()
  371. if name:
  372. return name
  373. return self._get_username_from_api()
  374. def _save_cookiejar(self):
  375. """Try to save our cookiejar after doing a (normal) login or logout.
  376. Calls the standard .save() method with no filename. Don't fret if our
  377. cookiejar doesn't support saving (CookieJar raises AttributeError,
  378. FileCookieJar raises NotImplementedError) or no default filename was
  379. given (LWPCookieJar and MozillaCookieJar raise ValueError).
  380. """
  381. try:
  382. self._cookiejar.save()
  383. except (AttributeError, NotImplementedError, ValueError):
  384. pass
  385. def _login(self, login, token=None, attempt=0):
  386. """Safely login through the API.
  387. Normally, this is called by __init__() if a username and password have
  388. been provided and no valid login cookies were found. The only other
  389. time it needs to be called is when those cookies expire, which is done
  390. automatically by api_query() if a query fails.
  391. Recent versions of MediaWiki's API have fixed a CSRF vulnerability,
  392. requiring login to be done in two separate requests. If the response
  393. from from our initial request is "NeedToken", we'll do another one with
  394. the token. If login is successful, we'll try to save our cookiejar.
  395. Raises LoginError on login errors (duh), like bad passwords and
  396. nonexistent usernames.
  397. *login* is a (username, password) tuple. *token* is the token returned
  398. from our first request, and *attempt* is to prevent getting stuck in a
  399. loop if MediaWiki isn't acting right.
  400. """
  401. name, password = login
  402. if token:
  403. result = self.api_query(action="login", lgname=name,
  404. lgpassword=password, lgtoken=token)
  405. else:
  406. result = self.api_query(action="login", lgname=name,
  407. lgpassword=password)
  408. res = result["login"]["result"]
  409. if res == "Success":
  410. self._save_cookiejar()
  411. elif res == "NeedToken" and attempt == 0:
  412. token = result["login"]["token"]
  413. return self._login(login, token, attempt=1)
  414. else:
  415. if res == "Illegal":
  416. e = "The provided username is illegal."
  417. elif res == "NotExists":
  418. e = "The provided username does not exist."
  419. elif res == "EmptyPass":
  420. e = "No password was given."
  421. elif res == "WrongPass" or res == "WrongPluginPass":
  422. e = "The given password is incorrect."
  423. else:
  424. e = "Couldn't login; server says '{0}'.".format(res)
  425. raise exceptions.LoginError(e)
  426. def _logout(self):
  427. """Safely logout through the API.
  428. We'll do a simple API request (api.php?action=logout), clear our
  429. cookiejar (which probably contains now-invalidated cookies) and try to
  430. save it, if it supports that sort of thing.
  431. """
  432. self.api_query(action="logout")
  433. self._cookiejar.clear()
  434. self._save_cookiejar()
  435. def _sql_connect(self, **kwargs):
  436. """Attempt to establish a connection with this site's SQL database.
  437. oursql.connect() will be called with self._sql_data as its kwargs.
  438. Any kwargs given to this function will be passed to connect() and will
  439. have precedence over the config file.
  440. Will raise SQLError() if the module "oursql" is not available. oursql
  441. may raise its own exceptions (e.g. oursql.InterfaceError) if it cannot
  442. establish a connection.
  443. """
  444. if not oursql:
  445. e = "Module 'oursql' is required for SQL queries."
  446. raise exceptions.SQLError(e)
  447. args = self._sql_data
  448. for key, value in kwargs.iteritems():
  449. args[key] = value
  450. if "read_default_file" not in args and "user" not in args and "passwd" not in args:
  451. args["read_default_file"] = expanduser("~/.my.cnf")
  452. if "autoping" not in args:
  453. args["autoping"] = True
  454. if "autoreconnect" not in args:
  455. args["autoreconnect"] = True
  456. self._sql_conn = oursql.connect(**args)
  457. def _get_service_order(self):
  458. """Return a preferred order for using services (e.g. the API and SQL).
  459. A list is returned, starting with the most preferred service first and
  460. ending with the least preferred one. Currently, there are only two
  461. services. SERVICE_API will always be included since the API is expected
  462. to be always usable. In normal circumstances, self.SERVICE_SQL will be
  463. first (with the API second), since using SQL directly is easier on the
  464. servers than making web queries with the API. self.SERVICE_SQL will be
  465. second if replag is greater than three minutes (a cached value updated
  466. every two minutes at most), *unless* API lag is also very high.
  467. self.SERVICE_SQL will not be included in the list if we cannot form a
  468. proper SQL connection.
  469. """
  470. now = time()
  471. if now - self._sql_info_cache["lastcheck"] > 120:
  472. self._sql_info_cache["lastcheck"] = now
  473. try:
  474. self._sql_info_cache["replag"] = sqllag = self.get_replag()
  475. except (exceptions.SQLError, oursql.Error):
  476. self._sql_info_cache["usable"] = False
  477. return [self.SERVICE_API]
  478. self._sql_info_cache["usable"] = True
  479. else:
  480. if not self._sql_info_cache["usable"]:
  481. return [self.SERVICE_API]
  482. sqllag = self._sql_info_cache["replag"]
  483. if sqllag > 180:
  484. if not self._maxlag:
  485. return [self.SERVICE_API, self.SERVICE_SQL]
  486. if now - self._api_info_cache["lastcheck"] > 120:
  487. self._api_info_cache["lastcheck"] = now
  488. try:
  489. self._api_info_cache["maxlag"] = apilag = self.get_maxlag()
  490. except exceptions.APIError:
  491. self._api_info_cache["maxlag"] = apilag = 0
  492. else:
  493. apilag = self._api_info_cache["maxlag"]
  494. if sqllag / (180.0 / self._maxlag) < apilag:
  495. return [self.SERVICE_SQL, self.SERVICE_API]
  496. return [self.SERVICE_API, self.SERVICE_SQL]
  497. return [self.SERVICE_SQL, self.SERVICE_API]
  498. @property
  499. def name(self):
  500. """The Site's name (or "wikiid" in the API), like ``"enwiki"``."""
  501. return self._name
  502. @property
  503. def project(self):
  504. """The Site's project name in lowercase, like ``"wikipedia"``."""
  505. return self._project
  506. @property
  507. def lang(self):
  508. """The Site's language code, like ``"en"`` or ``"es"``."""
  509. return self._lang
  510. @property
  511. def domain(self):
  512. """The Site's web domain, like ``"en.wikipedia.org"``."""
  513. return urlparse(self._base_url).netloc
  514. @property
  515. def url(self):
  516. """The Site's full base URL, like ``"https://en.wikipedia.org"``."""
  517. url = self._base_url
  518. if url.startswith("//"): # Protocol-relative URLs from 1.18
  519. if self._use_https:
  520. url = "https:" + url
  521. else:
  522. url = "http:" + url
  523. return url
  524. def api_query(self, **kwargs):
  525. """Do an API query with `kwargs` as the parameters.
  526. This will first attempt to construct an API url from
  527. :py:attr:`self._base_url` and :py:attr:`self._script_path`. We need
  528. both of these, or else we'll raise
  529. :py:exc:`~earwigbot.exceptions.APIError`. If
  530. :py:attr:`self._base_url` is protocol-relative (introduced in MediaWiki
  531. 1.18), we'll choose HTTPS only if :py:attr:`self._user_https` is
  532. ``True``, otherwise HTTP.
  533. We'll encode the given params, adding ``format=json`` along the way, as
  534. well as ``&assert=`` and ``&maxlag=`` based on
  535. :py:attr:`self._assert_edit` and :py:attr:`_maxlag` respectively.
  536. Additionally, we'll sleep a bit if the last query was made fewer than
  537. :py:attr:`self._wait_between_queries` seconds ago. The request is made
  538. through :py:attr:`self._opener`, which has cookie support
  539. (:py:attr:`self._cookiejar`), a ``User-Agent``
  540. (:py:const:`earwigbot.wiki.constants.USER_AGENT`), and
  541. ``Accept-Encoding`` set to ``"gzip"``.
  542. Assuming everything went well, we'll gunzip the data (if compressed),
  543. load it as a JSON object, and return it.
  544. If our request failed for some reason, we'll raise
  545. :py:exc:`~earwigbot.exceptions.APIError` with details. If that
  546. reason was due to maxlag, we'll sleep for a bit and then repeat the
  547. query until we exceed :py:attr:`self._max_retries`.
  548. There is helpful MediaWiki API documentation at `MediaWiki.org
  549. <http://www.mediawiki.org/wiki/API>`_.
  550. """
  551. with self._api_lock:
  552. return self._api_query(kwargs)
  553. def sql_query(self, query, params=(), plain_query=False, dict_cursor=False,
  554. cursor_class=None, show_table=False):
  555. """Do an SQL query and yield its results.
  556. If *plain_query* is ``True``, we will force an unparameterized query.
  557. Specifying both *params* and *plain_query* will cause an error. If
  558. *dict_cursor* is ``True``, we will use :py:class:`oursql.DictCursor` as
  559. our cursor, otherwise the default :py:class:`oursql.Cursor`. If
  560. *cursor_class* is given, it will override this option. If *show_table*
  561. is True, the name of the table will be prepended to the name of the
  562. column. This will mainly affect an :py:class:`~oursql.DictCursor`.
  563. Example usage::
  564. >>> query = "SELECT user_id, user_registration FROM user WHERE user_name = ?"
  565. >>> params = ("The Earwig",)
  566. >>> result1 = site.sql_query(query, params)
  567. >>> result2 = site.sql_query(query, params, dict_cursor=True)
  568. >>> for row in result1: print row
  569. (7418060L, '20080703215134')
  570. >>> for row in result2: print row
  571. {'user_id': 7418060L, 'user_registration': '20080703215134'}
  572. This may raise :py:exc:`~earwigbot.exceptions.SQLError` or one of
  573. oursql's exceptions (:py:exc:`oursql.ProgrammingError`,
  574. :py:exc:`oursql.InterfaceError`, ...) if there were problems with the
  575. query.
  576. See :py:meth:`_sql_connect` for information on how a connection is
  577. acquired. Also relevant is `oursql's documentation
  578. <http://packages.python.org/oursql>`_ for details on that package.
  579. """
  580. if not cursor_class:
  581. if dict_cursor:
  582. cursor_class = oursql.DictCursor
  583. else:
  584. cursor_class = oursql.Cursor
  585. klass = cursor_class
  586. with self._sql_lock:
  587. if not self._sql_conn:
  588. self._sql_connect()
  589. with self._sql_conn.cursor(klass, show_table=show_table) as cur:
  590. cur.execute(query, params, plain_query)
  591. for result in cur:
  592. yield result
  593. def get_maxlag(self, showall=False):
  594. """Return the internal database replication lag in seconds.
  595. In a typical setup, this function returns the replication lag *within*
  596. the WMF's cluster, *not* external replication lag affecting the
  597. Toolserver (see :py:meth:`get_replag` for that). This is useful when
  598. combined with the ``maxlag`` API query param (added by config), in
  599. which queries will be halted and retried if the lag is too high,
  600. usually above five seconds.
  601. With *showall*, will return a list of the lag for all servers in the
  602. cluster, not just the one with the highest lag.
  603. """
  604. params = {"action": "query", "meta": "siteinfo", "siprop": "dbrepllag"}
  605. if showall:
  606. params["sishowalldb"] = 1
  607. with self._api_lock:
  608. result = self._api_query(params, ignore_maxlag=True)
  609. if showall:
  610. return [server["lag"] for server in result["query"]["dbrepllag"]]
  611. return result["query"]["dbrepllag"][0]["lag"]
  612. def get_replag(self):
  613. """Return the estimated external database replication lag in seconds.
  614. Requires SQL access. This function only makes sense on a replicated
  615. database (e.g. the Wikimedia Toolserver) and on a wiki that receives a
  616. large number of edits (ideally, at least one per second), or the result
  617. may be larger than expected, since it works by subtracting the current
  618. time from the timestamp of the latest recent changes event.
  619. This may raise :py:exc:`~earwigbot.exceptions.SQLError` or one of
  620. oursql's exceptions (:py:exc:`oursql.ProgrammingError`,
  621. :py:exc:`oursql.InterfaceError`, ...) if there were problems.
  622. """
  623. query = """SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(rc_timestamp) FROM
  624. recentchanges ORDER BY rc_timestamp DESC LIMIT 1"""
  625. result = list(self.sql_query(query))
  626. return result[0][0]
  627. def namespace_id_to_name(self, ns_id, all=False):
  628. """Given a namespace ID, returns associated namespace names.
  629. If *all* is ``False`` (default), we'll return the first name in the
  630. list, which is usually the localized version. Otherwise, we'll return
  631. the entire list, which includes the canonical name. For example, this
  632. returns ``u"Wikipedia"`` if *ns_id* = ``4`` and *all* is ``False`` on
  633. ``enwiki``; returns ``[u"Wikipedia", u"Project", u"WP"]`` if *ns_id* =
  634. ``4`` and *all* is ``True``.
  635. Raises :py:exc:`~earwigbot.exceptions.NamespaceNotFoundError` if the ID
  636. is not found.
  637. """
  638. try:
  639. if all:
  640. return self._namespaces[ns_id]
  641. else:
  642. return self._namespaces[ns_id][0]
  643. except KeyError:
  644. e = "There is no namespace with id {0}.".format(ns_id)
  645. raise exceptions.NamespaceNotFoundError(e)
  646. def namespace_name_to_id(self, name):
  647. """Given a namespace name, returns the associated ID.
  648. Like :py:meth:`namespace_id_to_name`, but reversed. Case is ignored,
  649. because namespaces are assumed to be case-insensitive.
  650. Raises :py:exc:`~earwigbot.exceptions.NamespaceNotFoundError` if the
  651. name is not found.
  652. """
  653. lname = name.lower()
  654. for ns_id, names in self._namespaces.items():
  655. lnames = [n.lower() for n in names] # Be case-insensitive
  656. if lname in lnames:
  657. return ns_id
  658. e = "There is no namespace with name '{0}'.".format(name)
  659. raise exceptions.NamespaceNotFoundError(e)
  660. def get_page(self, title, follow_redirects=False, pageid=None):
  661. """Return a :py:class:`Page` object for the given title.
  662. *follow_redirects* is passed directly to
  663. :py:class:`~earwigbot.wiki.page.Page`'s constructor. Also, this will
  664. return a :py:class:`~earwigbot.wiki.category.Category` object instead
  665. if the given title is in the category namespace. As
  666. :py:class:`~earwigbot.wiki.category.Category` is a subclass of
  667. :py:class:`~earwigbot.wiki.page.Page`, this should not cause problems.
  668. Note that this doesn't do any direct checks for existence or
  669. redirect-following: :py:class:`~earwigbot.wiki.page.Page`'s methods
  670. provide that.
  671. """
  672. title = self._unicodeify(title)
  673. prefixes = self.namespace_id_to_name(constants.NS_CATEGORY, all=True)
  674. prefix = title.split(":", 1)[0]
  675. if prefix != title: # Avoid a page that is simply "Category"
  676. if prefix in prefixes:
  677. return Category(self, title, follow_redirects, pageid)
  678. return Page(self, title, follow_redirects, pageid)
  679. def get_category(self, catname, follow_redirects=False, pageid=None):
  680. """Return a :py:class:`Category` object for the given category name.
  681. *catname* should be given *without* a namespace prefix. This method is
  682. really just shorthand for :py:meth:`get_page("Category:" + catname)
  683. <get_page>`.
  684. """
  685. catname = self._unicodeify(catname)
  686. prefix = self.namespace_id_to_name(constants.NS_CATEGORY)
  687. pagename = u':'.join((prefix, catname))
  688. return Category(self, pagename, follow_redirects, pageid)
  689. def get_user(self, username=None):
  690. """Return a :py:class:`User` object for the given username.
  691. If *username* is left as ``None``, then a
  692. :py:class:`~earwigbot.wiki.user.User` object representing the currently
  693. logged-in (or anonymous!) user is returned.
  694. """
  695. if username:
  696. username = self._unicodeify(username)
  697. else:
  698. username = self._get_username()
  699. return User(self, username)
  700. def delegate(self, services, args=None, kwargs=None):
  701. """Delegate a task to either the API or SQL depending on conditions.
  702. *services* should be a dictionary in which the key is the service name
  703. (:py:attr:`self.SERVICE_API <SERVICE_API>` or
  704. :py:attr:`self.SERVICE_SQL <SERVICE_SQL>`), and the value is the
  705. function to call for this service. All functions will be passed the
  706. same arguments the tuple *args* and the dict **kwargs**, which are both
  707. empty by default. The service order is determined by
  708. :py:meth:`_get_service_order`.
  709. Not every service needs an entry in the dictionary. Will raise
  710. :py:exc:`~earwigbot.exceptions.NoServiceError` if an appropriate
  711. service cannot be found.
  712. """
  713. if not args:
  714. args = ()
  715. if not kwargs:
  716. kwargs = {}
  717. order = self._get_service_order()
  718. for srv in order:
  719. if srv in services:
  720. try:
  721. return services[srv](*args, **kwargs)
  722. except exceptions.ServiceError:
  723. continue
  724. raise exceptions.NoServiceError(services)