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.

694 lines
29 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.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")
  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 _urlencode_utf8(self, params):
  157. """Implement urllib.urlencode(params) with support for unicode input."""
  158. enc = lambda s: s.encode("utf8") if isinstance(s, unicode) else str(s)
  159. args = []
  160. for key, val in params.iteritems():
  161. key = quote_plus(enc(key))
  162. val = quote_plus(enc(val))
  163. args.append(key + "=" + val)
  164. return "&".join(args)
  165. def _api_query(self, params, tries=0, wait=5):
  166. """Do an API query with `params` as a dict of parameters.
  167. This will first attempt to construct an API url from self._base_url and
  168. self._script_path. We need both of these, or else we'll raise
  169. SiteAPIError. If self._base_url is protocol-relative (introduced in
  170. MediaWiki 1.18), we'll choose HTTPS if self._user_https is True,
  171. otherwise HTTP.
  172. We'll encode the given params, adding format=json along the way, as
  173. well as &assert= and &maxlag= based on self._assert_edit and _maxlag.
  174. Additionally, we'll sleep a bit if the last query was made less than
  175. self._wait_between_queries seconds ago. The request is made through
  176. self._opener, which has cookie support (self._cookiejar), a User-Agent
  177. (wiki.constants.USER_AGENT), and Accept-Encoding set to "gzip".
  178. Assuming everything went well, we'll gunzip the data (if compressed),
  179. load it as a JSON object, and return it.
  180. If our request failed for some reason, we'll raise SiteAPIError with
  181. details. If that reason was due to maxlag, we'll sleep for a bit and
  182. then repeat the query until we exceed self._max_retries.
  183. There's helpful MediaWiki API documentation at
  184. <http://www.mediawiki.org/wiki/API>.
  185. """
  186. since_last_query = time() - self._last_query_time # Throttling support
  187. if since_last_query < self._wait_between_queries:
  188. wait_time = self._wait_between_queries - since_last_query
  189. log = "Throttled: waiting {0} seconds".format(round(wait_time, 2))
  190. self._logger.debug(log)
  191. sleep(wait_time)
  192. self._last_query_time = time()
  193. url, data = self._build_api_query(params)
  194. self._logger.debug("{0} -> {1}".format(url, data))
  195. try:
  196. response = self._opener.open(url, data)
  197. except URLError as error:
  198. if hasattr(error, "reason"):
  199. e = "API query failed: {0}.".format(error.reason)
  200. elif hasattr(error, "code"):
  201. e = "API query failed: got an error code of {0}."
  202. e = e.format(error.code)
  203. else:
  204. e = "API query failed."
  205. raise SiteAPIError(e)
  206. result = response.read()
  207. if response.headers.get("Content-Encoding") == "gzip":
  208. stream = StringIO(result)
  209. gzipper = GzipFile(fileobj=stream)
  210. result = gzipper.read()
  211. return self._handle_api_query_result(result, params, tries, wait)
  212. def _build_api_query(self, params):
  213. """Given API query params, return the URL to query and POST data."""
  214. if not self._base_url or self._script_path is None:
  215. e = "Tried to do an API query, but no API URL is known."
  216. raise SiteAPIError(e)
  217. base_url = self._base_url
  218. if base_url.startswith("//"): # Protocol-relative URLs from 1.18
  219. if self._use_https:
  220. base_url = "https:" + base_url
  221. else:
  222. base_url = "http:" + base_url
  223. url = ''.join((base_url, self._script_path, "/api.php"))
  224. params["format"] = "json" # This is the only format we understand
  225. if self._assert_edit: # If requested, ensure that we're logged in
  226. params["assert"] = self._assert_edit
  227. if self._maxlag: # If requested, don't overload the servers
  228. params["maxlag"] = self._maxlag
  229. data = self._urlencode_utf8(params)
  230. return url, data
  231. def _handle_api_query_result(self, result, params, tries, wait):
  232. """Given the result of an API query, attempt to return useful data."""
  233. try:
  234. res = loads(result) # Try to parse as a JSON object
  235. except ValueError:
  236. e = "API query failed: JSON could not be decoded."
  237. raise SiteAPIError(e)
  238. try:
  239. code = res["error"]["code"]
  240. info = res["error"]["info"]
  241. except (TypeError, KeyError): # Having these keys indicates a problem
  242. return res # All is well; return the decoded JSON
  243. if code == "maxlag": # We've been throttled by the server
  244. if tries >= self._max_retries:
  245. e = "Maximum number of retries reached ({0})."
  246. raise SiteAPIError(e.format(self._max_retries))
  247. tries += 1
  248. msg = 'Server says "{0}"; retrying in {1} seconds ({2}/{3})'
  249. self._logger.info(msg.format(info, wait, tries, self._max_retries))
  250. sleep(wait)
  251. return self._api_query(params, tries=tries, wait=wait*3)
  252. else: # Some unknown error occurred
  253. e = 'API query failed: got error "{0}"; server says: "{1}".'
  254. error = SiteAPIError(e.format(code, info))
  255. error.code, error.info = code, info
  256. raise error
  257. def _load_attributes(self, force=False):
  258. """Load data about our Site from the API.
  259. This function is called by __init__() when one of the site attributes
  260. was not given as a keyword argument. We'll do an API query to get the
  261. missing data, but only if there actually *is* missing data.
  262. Additionally, you can call this with `force=True` to forcibly reload
  263. all attributes.
  264. """
  265. # All attributes to be loaded, except _namespaces, which is a special
  266. # case because it requires additional params in the API query:
  267. attrs = [self._name, self._project, self._lang, self._base_url,
  268. self._article_path, self._script_path]
  269. params = {"action": "query", "meta": "siteinfo"}
  270. if not self._namespaces or force:
  271. params["siprop"] = "general|namespaces|namespacealiases"
  272. result = self._api_query(params)
  273. self._load_namespaces(result)
  274. elif all(attrs): # Everything is already specified and we're not told
  275. return # to force a reload, so do nothing
  276. else: # We're only loading attributes other than _namespaces
  277. params["siprop"] = "general"
  278. result = self._api_query(params)
  279. res = result["query"]["general"]
  280. self._name = res["wikiid"]
  281. self._project = res["sitename"].lower()
  282. self._lang = res["lang"]
  283. self._base_url = res["server"]
  284. self._article_path = res["articlepath"]
  285. self._script_path = res["scriptpath"]
  286. def _load_namespaces(self, result):
  287. """Fill self._namespaces with a dict of namespace IDs and names.
  288. Called by _load_attributes() with API data as `result` when
  289. self._namespaces was not given as an kwarg to __init__().
  290. """
  291. self._namespaces = {}
  292. for namespace in result["query"]["namespaces"].values():
  293. ns_id = namespace["id"]
  294. name = namespace["*"]
  295. try:
  296. canonical = namespace["canonical"]
  297. except KeyError:
  298. self._namespaces[ns_id] = [name]
  299. else:
  300. if name != canonical:
  301. self._namespaces[ns_id] = [name, canonical]
  302. else:
  303. self._namespaces[ns_id] = [name]
  304. for namespace in result["query"]["namespacealiases"]:
  305. ns_id = namespace["id"]
  306. alias = namespace["*"]
  307. self._namespaces[ns_id].append(alias)
  308. def _get_cookie(self, name, domain):
  309. """Return the named cookie unless it is expired or doesn't exist."""
  310. for cookie in self._cookiejar:
  311. if cookie.name == name and cookie.domain == domain:
  312. if cookie.is_expired():
  313. break
  314. return cookie
  315. def _get_username_from_cookies(self):
  316. """Try to return our username based solely on cookies.
  317. First, we'll look for a cookie named self._name + "Token", like
  318. "enwikiToken". If it exists and isn't expired, we'll assume it's valid
  319. and try to return the value of the cookie self._name + "UserName" (like
  320. "enwikiUserName"). This should work fine on wikis without single-user
  321. login.
  322. If `enwikiToken` doesn't exist, we'll try to find a cookie named
  323. `centralauth_Token`. If this exists and is not expired, we'll try to
  324. return the value of `centralauth_User`.
  325. If we didn't get any matches, we'll return None. Our goal here isn't to
  326. return the most likely username, or what we *want* our username to be
  327. (for that, we'd do self._login_info[0]), but rather to get our current
  328. username without an unnecessary ?action=query&meta=userinfo API query.
  329. """
  330. domain = self.domain()
  331. name = ''.join((self._name, "Token"))
  332. cookie = self._get_cookie(name, domain)
  333. if cookie:
  334. name = ''.join((self._name, "UserName"))
  335. user_name = self._get_cookie(name, domain)
  336. if user_name:
  337. return user_name.value
  338. name = "centralauth_Token"
  339. for cookie in self._cookiejar:
  340. if not cookie.domain_initial_dot or cookie.is_expired():
  341. continue
  342. if cookie.name != name:
  343. continue
  344. # Build a regex that will match domains this cookie affects:
  345. search = ''.join(("(.*?)", re_escape(cookie.domain)))
  346. if re_match(search, domain): # Test it against our site
  347. user_name = self._get_cookie("centralauth_User", cookie.domain)
  348. if user_name:
  349. return user_name.value
  350. def _get_username_from_api(self):
  351. """Do a simple API query to get our username and return it.
  352. This is a reliable way to make sure we are actually logged in, because
  353. it doesn't deal with annoying cookie logic, but it results in an API
  354. query that is unnecessary in some cases.
  355. Called by _get_username() (in turn called by get_user() with no
  356. username argument) when cookie lookup fails, probably indicating that
  357. we are logged out.
  358. """
  359. params = {"action": "query", "meta": "userinfo"}
  360. result = self._api_query(params)
  361. return result["query"]["userinfo"]["name"]
  362. def _get_username(self):
  363. """Return the name of the current user, whether logged in or not.
  364. First, we'll try to deduce it solely from cookies, to avoid an
  365. unnecessary API query. For the cookie-detection method, see
  366. _get_username_from_cookies()'s docs.
  367. If our username isn't in cookies, then we're probably not logged in, or
  368. something fishy is going on (like forced logout). In this case, do a
  369. single API query for our username (or IP address) and return that.
  370. """
  371. name = self._get_username_from_cookies()
  372. if name:
  373. return name
  374. return self._get_username_from_api()
  375. def _save_cookiejar(self):
  376. """Try to save our cookiejar after doing a (normal) login or logout.
  377. Calls the standard .save() method with no filename. Don't fret if our
  378. cookiejar doesn't support saving (CookieJar raises AttributeError,
  379. FileCookieJar raises NotImplementedError) or no default filename was
  380. given (LWPCookieJar and MozillaCookieJar raise ValueError).
  381. """
  382. try:
  383. self._cookiejar.save()
  384. except (AttributeError, NotImplementedError, ValueError):
  385. pass
  386. def _login(self, login, token=None, attempt=0):
  387. """Safely login through the API.
  388. Normally, this is called by __init__() if a username and password have
  389. been provided and no valid login cookies were found. The only other
  390. time it needs to be called is when those cookies expire, which is done
  391. automatically by api_query() if a query fails.
  392. Recent versions of MediaWiki's API have fixed a CSRF vulnerability,
  393. requiring login to be done in two separate requests. If the response
  394. from from our initial request is "NeedToken", we'll do another one with
  395. the token. If login is successful, we'll try to save our cookiejar.
  396. Raises LoginError on login errors (duh), like bad passwords and
  397. nonexistent usernames.
  398. `login` is a (username, password) tuple. `token` is the token returned
  399. from our first request, and `attempt` is to prevent getting stuck in a
  400. loop if MediaWiki isn't acting right.
  401. """
  402. name, password = login
  403. params = {"action": "login", "lgname": name, "lgpassword": password}
  404. if token:
  405. params["lgtoken"] = token
  406. result = self._api_query(params)
  407. res = result["login"]["result"]
  408. if res == "Success":
  409. self._save_cookiejar()
  410. elif res == "NeedToken" and attempt == 0:
  411. token = result["login"]["token"]
  412. return self._login(login, token, attempt=1)
  413. else:
  414. if res == "Illegal":
  415. e = "The provided username is illegal."
  416. elif res == "NotExists":
  417. e = "The provided username does not exist."
  418. elif res == "EmptyPass":
  419. e = "No password was given."
  420. elif res == "WrongPass" or res == "WrongPluginPass":
  421. e = "The given password is incorrect."
  422. else:
  423. e = "Couldn't login; server says '{0}'.".format(res)
  424. raise LoginError(e)
  425. def _logout(self):
  426. """Safely logout through the API.
  427. We'll do a simple API request (api.php?action=logout), clear our
  428. cookiejar (which probably contains now-invalidated cookies) and try to
  429. save it, if it supports that sort of thing.
  430. """
  431. params = {"action": "logout"}
  432. self._api_query(params)
  433. self._cookiejar.clear()
  434. self._save_cookiejar()
  435. def _sql_connect(self, **kwargs):
  436. """Attempt to establish a connection with this site's SQL database.
  437. oursql.connect() will be called with self._sql_data as its kwargs.
  438. Any kwargs given to this function will be passed to connect() and will
  439. have precedence over the config file.
  440. Will raise SQLError() if the module "oursql" is not available. oursql
  441. may raise its own exceptions (e.g. oursql.InterfaceError) if it cannot
  442. establish a connection.
  443. """
  444. if not oursql:
  445. e = "Module 'oursql' is required for SQL queries."
  446. raise SQLError(e)
  447. args = self._sql_data
  448. for key, value in kwargs.iteritems():
  449. args[key] = value
  450. if "read_default_file" not in args and "user" not in args and "passwd" not in args:
  451. args["read_default_file"] = expanduser("~/.my.cnf")
  452. if "autoping" not in args:
  453. args["autoping"] = True
  454. if "autoreconnect" not in args:
  455. args["autoreconnect"] = True
  456. self._sql_conn = oursql.connect(**args)
  457. def name(self):
  458. """Returns the Site's name (or "wikiid" in the API), like "enwiki"."""
  459. return self._name
  460. def project(self):
  461. """Returns the Site's project name in lowercase, like "wikipedia"."""
  462. return self._project
  463. def lang(self):
  464. """Returns the Site's language code, like "en" or "es"."""
  465. return self._lang
  466. def domain(self):
  467. """Returns the Site's web domain, like "en.wikipedia.org"."""
  468. return urlparse(self._base_url).netloc
  469. def api_query(self, **kwargs):
  470. """Do an API query with `kwargs` as the parameters.
  471. See _api_query()'s documentation for details.
  472. """
  473. return self._api_query(kwargs)
  474. def sql_query(self, query, params=(), plain_query=False, dict_cursor=False,
  475. cursor_class=None, show_table=False):
  476. """Do an SQL query and yield its results.
  477. If `plain_query` is True, we will force an unparameterized query.
  478. Specifying both params and plain_query will cause an error.
  479. If `dict_cursor` is True, we will use oursql.DictCursor as our cursor,
  480. otherwise the default oursql.Cursor. If `cursor_class` is given, it
  481. will override this option.
  482. If `show_table` is True, the name of the table will be prepended to the
  483. name of the column. This will mainly affect a DictCursor.
  484. Example:
  485. >>> query = "SELECT user_id, user_registration FROM user WHERE user_name = ?"
  486. >>> params = ("The Earwig",)
  487. >>> result1 = site.sql_query(query, params)
  488. >>> result2 = site.sql_query(query, params, dict_cursor=True)
  489. >>> for row in result1: print row
  490. (7418060L, '20080703215134')
  491. >>> for row in result2: print row
  492. {'user_id': 7418060L, 'user_registration': '20080703215134'}
  493. See _sql_connect() for information on how a connection is acquired.
  494. <http://packages.python.org/oursql> has helpful documentation on the
  495. oursql module.
  496. This may raise SQLError() or one of oursql's exceptions
  497. (oursql.ProgrammingError, oursql.InterfaceError, ...) if there were
  498. problems with the query.
  499. """
  500. if not cursor_class:
  501. if dict_cursor:
  502. cursor_class = oursql.DictCursor
  503. else:
  504. cursor_class = oursql.Cursor
  505. klass = cursor_class
  506. with self._sql_lock:
  507. if not self._sql_conn:
  508. self._sql_connect()
  509. with self._sql_conn.cursor(klass, show_table=show_table) as cur:
  510. cur.execute(query, params, plain_query)
  511. for result in cur:
  512. yield result
  513. def get_replag(self):
  514. """Return the estimated database replication lag in seconds.
  515. Requires SQL access. This function only makes sense on a replicated
  516. database (e.g. the Wikimedia Toolserver) and on a wiki that receives a
  517. large number of edits (ideally, at least one per second), or the result
  518. may be larger than expected.
  519. """
  520. query = """SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(rc_timestamp) FROM
  521. recentchanges ORDER BY rc_timestamp DESC LIMIT 1"""
  522. result = list(self.sql_query(query))
  523. return result[0][0]
  524. def namespace_id_to_name(self, ns_id, all=False):
  525. """Given a namespace ID, returns associated namespace names.
  526. If all is False (default), we'll return the first name in the list,
  527. which is usually the localized version. Otherwise, we'll return the
  528. entire list, which includes the canonical name.
  529. For example, returns u"Wikipedia" if ns_id=4 and all=False on enwiki;
  530. returns [u"Wikipedia", u"Project", u"WP"] if ns_id=4 and all=True.
  531. Raises NamespaceNotFoundError if the ID is not found.
  532. """
  533. try:
  534. if all:
  535. return self._namespaces[ns_id]
  536. else:
  537. return self._namespaces[ns_id][0]
  538. except KeyError:
  539. e = "There is no namespace with id {0}.".format(ns_id)
  540. raise NamespaceNotFoundError(e)
  541. def namespace_name_to_id(self, name):
  542. """Given a namespace name, returns the associated ID.
  543. Like namespace_id_to_name(), but reversed. Case is ignored, because
  544. namespaces are assumed to be case-insensitive.
  545. Raises NamespaceNotFoundError if the name is not found.
  546. """
  547. lname = name.lower()
  548. for ns_id, names in self._namespaces.items():
  549. lnames = [n.lower() for n in names] # Be case-insensitive
  550. if lname in lnames:
  551. return ns_id
  552. e = "There is no namespace with name '{0}'.".format(name)
  553. raise NamespaceNotFoundError(e)
  554. def get_page(self, title, follow_redirects=False):
  555. """Returns a Page object for the given title (pagename).
  556. Will return a Category object instead if the given title is in the
  557. category namespace. As Category is a subclass of Page, this should not
  558. cause problems.
  559. Note that this doesn't do any direct checks for existence or
  560. redirect-following - Page's methods provide that.
  561. """
  562. prefixes = self.namespace_id_to_name(NS_CATEGORY, all=True)
  563. prefix = title.split(":", 1)[0]
  564. if prefix != title: # Avoid a page that is simply "Category"
  565. if prefix in prefixes:
  566. return Category(self, title, follow_redirects)
  567. return Page(self, title, follow_redirects)
  568. def get_category(self, catname, follow_redirects=False):
  569. """Returns a Category object for the given category name.
  570. `catname` should be given *without* a namespace prefix. This method is
  571. really just shorthand for get_page("Category:" + catname).
  572. """
  573. prefix = self.namespace_id_to_name(NS_CATEGORY)
  574. pagename = ':'.join((prefix, catname))
  575. return Category(self, pagename, follow_redirects)
  576. def get_user(self, username=None):
  577. """Returns a User object for the given username.
  578. If `username` is left as None, then a User object representing the
  579. currently logged-in (or anonymous!) user is returned.
  580. """
  581. if not username:
  582. username = self._get_username()
  583. return User(self, username)