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.

946 lines
41 KiB

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