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.

926 lines
40 KiB

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