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.

853 lines
36 KiB

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