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.

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