Take care of some pesky whitespace issues
[mw] / src / mw / api.py
1 ###
2 # mw - VCS-like nonsense for MediaWiki websites
3 # Copyright (C) 2010  Ian Weller <ian@ianweller.org>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program.  If not, see <http://www.gnu.org/licenses/>.
17 ###
18
19 import cookielib
20 import gzip
21 import json
22 from StringIO import StringIO
23 import urllib
24 import urllib2
25
26
27 class API(object):
28
29     def __init__(self, api_url):
30         self.api_url = api_url
31         self.cookiejar = cookielib.CookieJar()
32         self.opener = urllib2.build_opener(
33                 urllib2.HTTPCookieProcessor(self.cookiejar))
34         self._high_limits = None
35
36     def call(self, data):
37         data['format'] = 'json'
38         request = urllib2.Request(self.api_url, urllib.urlencode(data))
39         request.add_header('Accept-encoding', 'gzip')
40         response = self.opener.open(request)
41         if response.headers.get('Content-Encoding') == 'gzip':
42             compressed = StringIO(response.read())
43             gzipper = gzip.GzipFile(fileobj=compressed)
44             data = gzipper.read()
45         else:
46             data = response.read()
47         return json.loads(data)
48
49     def limits(self, low, high):
50         if self._high_limits == None:
51             result = self.call({'action': 'query',
52                                 'meta': 'userinfo',
53                                 'uiprop': 'rights'})
54             self._high_limits = 'apihighlimits' in \
55                     result['query']['userinfo']['rights']
56         if self._high_limits:
57             return high
58         else:
59             return low
60
61
62 def pagename_to_filename(name):
63     name = name.replace(' ', '_')
64     name = name.replace('/', '!')
65     return name
66
67
68 def filename_to_pagename(name):
69     name = name.replace('!', '/')
70     name = name.replace('_', ' ')
71     return name

Benjamin Mako Hill || Want to submit a patch?