A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

742 řádky
31 KiB

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