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.

site.py 19 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. # -*- coding: utf-8 -*-
  2. from cookielib import CookieJar
  3. from gzip import GzipFile
  4. from json import loads
  5. from re import escape as re_escape, match as re_match
  6. from StringIO import StringIO
  7. from urllib import unquote_plus, urlencode
  8. from urllib2 import build_opener, HTTPCookieProcessor, URLError
  9. from urlparse import urlparse
  10. from wiki.tools.category import Category
  11. from wiki.tools.constants import *
  12. from wiki.tools.exceptions import *
  13. from wiki.tools.page import Page
  14. from wiki.tools.user import User
  15. class Site(object):
  16. """
  17. EarwigBot's Wiki Toolset: Site Class
  18. Represents a Site, with support for API queries and returning Pages, Users,
  19. and Categories. The constructor takes a bunch of arguments and you probably
  20. won't need to call it directly, rather tools.get_site() for returning Site
  21. instances, tools.add_site() for adding new ones to config, and
  22. tools.del_site() for removing old ones from config, should suffice.
  23. Public methods:
  24. name -- returns our name (or "wikiid"), like "enwiki"
  25. project -- returns our project name, like "wikipedia"
  26. lang -- returns our language code, like "en"
  27. domain -- returns our web domain, like "en.wikipedia.org"
  28. api_query -- does an API query with the given kwargs as params
  29. namespace_id_to_name -- given a namespace ID, returns associated name(s)
  30. namespace_name_to_id -- given a namespace name, returns associated id
  31. get_page -- returns a Page object for the given title
  32. get_category -- returns a Category object for the given title
  33. get_user -- returns a User object for the given username
  34. """
  35. def __init__(self, name=None, project=None, lang=None, base_url=None,
  36. article_path=None, script_path=None, sql=(None, None),
  37. namespaces=None, login=(None, None), cookiejar=None):
  38. """Constructor for new Site instances.
  39. This probably isn't necessary to call yourself unless you're building a
  40. Site that's not in your config and you don't want to add it - normally
  41. all you need is tools.get_site(name), which creates the Site for you
  42. based on your config file. We accept a bunch of kwargs, but the only
  43. ones you really "need" are `base_url` and `script_path` - this is
  44. enough to figure out an API url. `login`, a tuple of
  45. (username, password), is highly recommended. `cookiejar` will be used
  46. to store cookies, and we'll use a normal CookieJar if none is given.
  47. First, we'll store the given arguments as attributes, then set up our
  48. URL opener. We'll load any of the attributes that weren't given from
  49. the API, and then log in if a username/pass was given and we aren't
  50. already logged in.
  51. """
  52. # attributes referring to site information, filled in by an API query
  53. # if they are missing (and an API url can be determined)
  54. self._name = name
  55. self._project = project
  56. self._lang = lang
  57. self._base_url = base_url
  58. self._article_path = article_path
  59. self._script_path = script_path
  60. self._sql = sql
  61. self._namespaces = namespaces
  62. # set up cookiejar and URL opener for making API queries
  63. if cookiejar is not None:
  64. self._cookiejar = cookiejar
  65. else:
  66. self._cookiejar = CookieJar()
  67. self._opener = build_opener(HTTPCookieProcessor(self._cookiejar))
  68. self._opener.addheaders = [("User-Agent", USER_AGENT),
  69. ("Accept-Encoding", "gzip")]
  70. # get all of the above attributes that were not specified as arguments
  71. self._load_attributes()
  72. # if we have a name/pass and the API says we're not logged in, log in
  73. self._login_info = name, password = login
  74. if name is not None and password is not None:
  75. logged_in_as = self._get_username_from_cookies()
  76. if logged_in_as is None or name != logged_in_as:
  77. self._login(login)
  78. def _api_query(self, params):
  79. """Do an API query with `params` as a dict of parameters.
  80. This will first attempt to construct an API url from self._base_url and
  81. self._script_path. We need both of these, or else we'll raise
  82. SiteAPIError.
  83. We'll encode the given params, adding format=json along the way, and
  84. make the request through self._opener, which has built-in cookie
  85. support via self._cookiejar, a User-Agent
  86. (wiki.tools.constants.USER_AGENT), and Accept-Encoding set to "gzip".
  87. Assuming everything went well, we'll gunzip the data (if compressed),
  88. load it as a JSON object, and return it.
  89. If our request failed, we'll raise SiteAPIError with details.
  90. There's helpful MediaWiki API documentation at
  91. <http://www.mediawiki.org/wiki/API>.
  92. """
  93. if self._base_url is None or self._script_path is None:
  94. e = "Tried to do an API query, but no API URL is known."
  95. raise SiteAPIError(e)
  96. url = ''.join((self._base_url, self._script_path, "/api.php"))
  97. params["format"] = "json" # this is the only format we understand
  98. data = urlencode(params)
  99. print url, data # debug code
  100. try:
  101. response = self._opener.open(url, data)
  102. except URLError as error:
  103. if hasattr(error, "reason"):
  104. e = "API query at {0} failed because {1}."
  105. e = e.format(error.geturl, error.reason)
  106. elif hasattr(error, "code"):
  107. e = "API query at {0} failed; got an error code of {1}."
  108. e = e.format(error.geturl, error.code)
  109. else:
  110. e = "API query failed."
  111. raise SiteAPIError(e)
  112. else:
  113. result = response.read()
  114. if response.headers.get("Content-Encoding") == "gzip":
  115. stream = StringIO(result)
  116. gzipper = GzipFile(fileobj=stream)
  117. result = gzipper.read()
  118. return loads(result) # parse as a JSON object
  119. def _load_attributes(self, force=False):
  120. """Load data about our Site from the API.
  121. This function is called by __init__() when one of the site attributes
  122. was not given as a keyword argument. We'll do an API query to get the
  123. missing data, but only if there actually *is* missing data.
  124. Additionally, you can call this with `force=True` to forcibly reload
  125. all attributes.
  126. """
  127. # all attributes to be loaded, except _namespaces, which is a special
  128. # case because it requires additional params in the API query
  129. attrs = [self._name, self._project, self._lang, self._base_url,
  130. self._article_path, self._script_path]
  131. params = {"action": "query", "meta": "siteinfo"}
  132. if self._namespaces is None or force:
  133. params["siprop"] = "general|namespaces|namespacealiases"
  134. result = self._api_query(params)
  135. self._load_namespaces(result)
  136. elif all(attrs): # everything is already specified and we're not told
  137. return # to force a reload, so do nothing
  138. else: # we're only loading attributes other than _namespaces
  139. params["siprop"] = "general"
  140. result = self._api_query(params)
  141. res = result["query"]["general"]
  142. self._name = res["wikiid"]
  143. self._project = res["sitename"].lower()
  144. self._lang = res["lang"]
  145. self._base_url = res["server"]
  146. self._article_path = res["articlepath"]
  147. self._script_path = res["scriptpath"]
  148. def _load_namespaces(self, result):
  149. """Fill self._namespaces with a dict of namespace IDs and names.
  150. Called by _load_attributes() with API data as `result` when
  151. self._namespaces was not given as an kwarg to __init__().
  152. """
  153. self._namespaces = {}
  154. for namespace in result["query"]["namespaces"].values():
  155. ns_id = namespace["id"]
  156. name = namespace["*"]
  157. try:
  158. canonical = namespace["canonical"]
  159. except KeyError:
  160. self._namespaces[ns_id] = [name]
  161. else:
  162. if name != canonical:
  163. self._namespaces[ns_id] = [name, canonical]
  164. else:
  165. self._namespaces[ns_id] = [name]
  166. for namespace in result["query"]["namespacealiases"]:
  167. ns_id = namespace["id"]
  168. alias = namespace["*"]
  169. self._namespaces[ns_id].append(alias)
  170. def _get_cookie(self, name, domain):
  171. """Return the named cookie unless it is expired or doesn't exist."""
  172. for cookie in self._cookiejar:
  173. if cookie.name == name and cookie.domain == domain:
  174. if cookie.is_expired():
  175. break
  176. return cookie
  177. def _get_username_from_cookies(self):
  178. """Try to return our username based solely on cookies.
  179. First, we'll look for a cookie named self._name + "Token", like
  180. "enwikiToken". If it exists and isn't expired, we'll assume it's valid
  181. and try to return the value of the cookie self._name + "UserName" (like
  182. "enwikiUserName"). This should work fine on wikis without single-user
  183. login.
  184. If `enwikiToken` doesn't exist, we'll try to find a cookie named
  185. `centralauth_Token`. If this exists and is not expired, we'll try to
  186. return the value of `centralauth_User`.
  187. If we didn't get any matches, we'll return None. Our goal here isn't to
  188. return the most likely username, or what we *want* our username to be
  189. (for that, we'd do self._login_info[0]), but rather to get our current
  190. username without an unnecessary ?action=query&meta=userinfo API query.
  191. """
  192. domain = self.domain()
  193. name = ''.join((self._name, "Token"))
  194. cookie = self._get_cookie(name, domain)
  195. if cookie is not None:
  196. name = ''.join((self._name, "UserName"))
  197. user_name = self._get_cookie(name, domain)
  198. if user_name is not None:
  199. return user_name.value
  200. name = "centralauth_Token"
  201. for cookie in self._cookiejar:
  202. if cookie.domain_initial_dot is False or cookie.is_expired():
  203. continue
  204. if cookie.name != name:
  205. continue
  206. # build a regex that will match domains this cookie affects
  207. search = ''.join(("(.*?)", re_escape(cookie.domain)))
  208. if re_match(search, domain): # test it against our site
  209. user_name = self._get_cookie("centralauth_User", cookie.domain)
  210. if user_name is not None:
  211. return user_name.value
  212. def _get_username_from_api(self):
  213. """Do a simple API query to get our username and return it.
  214. This is a reliable way to make sure we are actually logged in, because
  215. it doesn't deal with annoying cookie logic, but it results in an API
  216. query that is unnecessary in some cases.
  217. Called by _get_username() (in turn called by get_user() with no
  218. username argument) when cookie lookup fails, probably indicating that
  219. we are logged out.
  220. """
  221. params = {"action": "query", "meta": "userinfo"}
  222. result = self._api_query(params)
  223. return result["query"]["userinfo"]["name"]
  224. def _get_username(self):
  225. """Return the name of the current user, whether logged in or not.
  226. First, we'll try to deduce it solely from cookies, to avoid an
  227. unnecessary API query. For the cookie-detection method, see
  228. _get_username_from_cookies()'s docs.
  229. If our username isn't in cookies, then we're probably not logged in, or
  230. something fishy is going on (like forced logout). In this case, do a
  231. single API query for our username (or IP address) and return that.
  232. """
  233. name = self._get_username_from_cookies()
  234. if name is not None:
  235. return name
  236. return self._get_username_from_api()
  237. def _save_cookiejar(self):
  238. """Try to save our cookiejar after doing a (normal) login or logout.
  239. Calls the standard .save() method with no filename. Don't fret if our
  240. cookiejar doesn't support saving (CookieJar raises AttributeError,
  241. FileCookieJar raises NotImplementedError) or no default filename was
  242. given (LWPCookieJar and MozillaCookieJar raise ValueError).
  243. """
  244. try:
  245. self._cookiejar.save()
  246. except (AttributeError, NotImplementedError, ValueError):
  247. pass
  248. def _login(self, login, token=None, attempt=0):
  249. """Safely login through the API.
  250. Normally, this is called by __init__() if a username and password have
  251. been provided and no valid login cookies were found. The only other
  252. time it needs to be called is when those cookies expire, which is done
  253. automatically by api_query() if a query fails.
  254. Recent versions of MediaWiki's API have fixed a CSRF vulnerability,
  255. requiring login to be done in two separate requests. If the response
  256. from from our initial request is "NeedToken", we'll do another one with
  257. the token. If login is successful, we'll try to save our cookiejar.
  258. Raises LoginError on login errors (duh), like bad passwords and
  259. nonexistent usernames.
  260. `login` is a (username, password) tuple. `token` is the token returned
  261. from our first request, and `attempt` is to prevent getting stuck in a
  262. loop if MediaWiki isn't acting right.
  263. """
  264. name, password = login
  265. params = {"action": "login", "lgname": name, "lgpassword": password}
  266. if token is not None:
  267. params["lgtoken"] = token
  268. result = self._api_query(params)
  269. res = result["login"]["result"]
  270. if res == "Success":
  271. self._save_cookiejar()
  272. elif res == "NeedToken" and attempt == 0:
  273. token = result["login"]["token"]
  274. return self._login(login, token, attempt=1)
  275. else:
  276. if res == "Illegal":
  277. e = "The provided username is illegal."
  278. elif res == "NotExists":
  279. e = "The provided username does not exist."
  280. elif res == "EmptyPass":
  281. e = "No password was given."
  282. elif res == "WrongPass" or res == "WrongPluginPass":
  283. e = "The given password is incorrect."
  284. else:
  285. e = "Couldn't login; server says '{0}'.".format(res)
  286. raise LoginError(e)
  287. def _logout(self):
  288. """Safely logout through the API.
  289. We'll do a simple API request (api.php?action=logout), clear our
  290. cookiejar (which probably contains now-invalidated cookies) and try to
  291. save it, if it supports that sort of thing.
  292. """
  293. params = {"action": "logout"}
  294. self._api_query(params)
  295. self._cookiejar.clear()
  296. self._save_cookiejar()
  297. def api_query(self, **kwargs):
  298. """Do an API query with `kwargs` as the parameters.
  299. See _api_query()'s documentation for details.
  300. """
  301. return self._api_query(kwargs)
  302. def name(self):
  303. """Returns the Site's name (or "wikiid" in the API), like "enwiki"."""
  304. return self._name
  305. def project(self):
  306. """Returns the Site's project name in lowercase, like "wikipedia"."""
  307. return self._project
  308. def lang(self):
  309. """Returns the Site's language code, like "en" or "es"."""
  310. return self._lang
  311. def domain(self):
  312. """Returns the Site's web domain, like "en.wikipedia.org"."""
  313. return urlparse(self._base_url).netloc
  314. def namespace_id_to_name(self, ns_id, all=False):
  315. """Given a namespace ID, returns associated namespace names.
  316. If all is False (default), we'll return the first name in the list,
  317. which is usually the localized version. Otherwise, we'll return the
  318. entire list, which includes the canonical name.
  319. For example, returns u"Wikipedia" if ns_id=4 and all=False on enwiki;
  320. returns [u"Wikipedia", u"Project"] if ns_id=4 and all=True.
  321. Raises NamespaceNotFoundError if the ID is not found.
  322. """
  323. try:
  324. if all:
  325. return self._namespaces[ns_id]
  326. else:
  327. return self._namespaces[ns_id][0]
  328. except KeyError:
  329. e = "There is no namespace with id {0}.".format(ns_id)
  330. raise NamespaceNotFoundError(e)
  331. def namespace_name_to_id(self, name):
  332. """Given a namespace name, returns the associated ID.
  333. Like namespace_id_to_name(), but reversed. Case is ignored, because
  334. namespaces are assumed to be case-insensitive.
  335. Raises NamespaceNotFoundError if the name is not found.
  336. """
  337. lname = name.lower()
  338. for ns_id, names in self._namespaces.items():
  339. lnames = [n.lower() for n in names] # be case-insensitive
  340. if lname in lnames:
  341. return ns_id
  342. e = "There is no namespace with name '{0}'.".format(name)
  343. raise NamespaceNotFoundError(e)
  344. def get_page(self, title, follow_redirects=False):
  345. """Returns a Page object for the given title (pagename).
  346. Will return a Category object instead if the given title is in the
  347. category namespace. As Category is a subclass of Page, this should not
  348. cause problems.
  349. Note that this doesn't do any direct checks for existence or
  350. redirect-following - Page's methods provide that.
  351. """
  352. prefixes = self.namespace_id_to_name(NS_CATEGORY, all=True)
  353. prefix = title.split(":", 1)[0]
  354. if prefix != title: # avoid a page that is simply "Category"
  355. if prefix in prefixes:
  356. return Category(self, title, follow_redirects)
  357. return Page(self, title, follow_redirects)
  358. def get_category(self, catname, follow_redirects=False):
  359. """Returns a Category object for the given category name.
  360. `catname` should be given *without* a namespace prefix. This method is
  361. really just shorthand for get_page("Category:" + catname).
  362. """
  363. prefix = self.namespace_id_to_name(NS_CATEGORY)
  364. pagename = ':'.join((prefix, catname))
  365. return Category(self, pagename, follow_redirects)
  366. def get_user(self, username=None):
  367. """Returns a User object for the given username.
  368. If `username` is left as None, then a User object representing the
  369. currently logged-in (or anonymous!) user is returned.
  370. """
  371. if username is None:
  372. username = self._get_username()
  373. return User(self, username)