A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

908 wiersze
40 KiB

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