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.

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