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.

956 regels
41 KiB

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