A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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