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

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