forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
deki.py
346 lines (282 loc) · 11.5 KB
/
deki.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
""" deki.py - Access the wiki pages on a MindTouch Deki server via the API.
Here's what this code can do:
wiki = deki.Deki("http://developer.mozilla.org/@api/deki/", username, password)
page = wiki.get_page("Sheep")
print page.title
print page.doc.toxml()
page.title = "Bananas"
page.save()
There are also some additional methods:
wiki.create_page(path, content, title=, override=)
wiki.move_page(old, new)
wiki.get_subpages(page)
This module does not try to mimic the MindTouch "Plug" API. It's meant to be
higher-level than that.
"""
import sys
import urllib2, cookielib, httplib
import xml.dom.minidom as dom
from urllib import quote as _urllib_quote
from urllib import urlencode as _urlencode
import urlparse
from datetime import datetime
import re
__all__ = ['Deki']
# === Utils
def _check(fact):
if not fact:
raise AssertionError('check failed')
def _urlquote(s, *args):
return _urllib_quote(s.encode('utf-8'), *args)
def _make_url(*dirs, **params):
""" dirs must already be url-encoded, params must not """
url = '/'.join(dirs)
if params:
url += '?' + _urlencode(params)
return url
class PutRequest(urllib2.Request):
def get_method(self):
return "PUT"
# === Dream framework client code
# This handler causes python to "always be logged in" when it's talking to the
# server. If you're just accessing public pages, it generates more requests
# than are strictly needed, but this is the behavior you want for a bot.
#
# The users/authenticate request is sent twice: once without any basic auth and
# once with. Dumb. Feel free to fix.
#
class _LoginHandler(urllib2.HTTPCookieProcessor):
def __init__(self, server):
policy = cookielib.DefaultCookiePolicy(rfc2965=True)
cookiejar = cookielib.CookieJar(policy)
urllib2.HTTPCookieProcessor.__init__(self, cookiejar)
self.server = server
def http_request(self, req):
#print "DEBUG- Requesting " + req.get_full_url()
s = self.server
req = urllib2.HTTPCookieProcessor.http_request(self, req)
if ('Cookie' not in req.unredirected_hdrs
and req.get_full_url() != s.base + 'users/authenticate'):
s.login()
# Retry - should have a new cookie.
req = urllib2.HTTPCookieProcessor.http_request(self, req)
_check('Cookie' in req.unredirected_hdrs)
return req
class DreamClient:
def __init__(self, base, user, password):
"""
base - The base URI of the Deki API, with trailing slash.
Typically, 'http://wiki.example.org/@api/deki/'.
user, password - Your Deki login information.
"""
self.base = base
pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
pm.add_password(None, self.base, user, password)
ah = urllib2.HTTPBasicAuthHandler(pm)
lh = _LoginHandler(self)
self._opener = urllib2.build_opener(ah, lh)
def login(self):
response = self._opener.open(self.base + 'users/authenticate')
response.close()
def open(self, url):
return self._opener.open(self.base + url)
def _handleResponse(self, req):
"""Helper method shared between post() and put()"""
resp = self._opener.open(req)
try:
ct = resp.headers.get('Content-Type', '(none)')
if '/xml' in ct or '+xml' in ct:
return dom.parse(resp)
else:
#print "DEBUG- Content-Type:", ct
crud = resp.read()
#print 'DEBUG- crud:\n---\n%s\n---' % re.sub(r'(?m)^', ' ', crud)
return None
finally:
resp.close()
def post(self, url, data, type):
#print "DEBUG- posting to:", self.base + url
req = urllib2.Request(self.base + url, data, {'Content-Type': type})
return self._handleResponse(req)
def put(self, url, data, type):
#print "DEBUG- putting to:", self.base + url
req = PutRequest(self.base + url, data, {'Content-Type': type})
return self._handleResponse(req)
def get_xml(self, url):
resp = self.open(url)
try:
return dom.parse(resp)
finally:
resp.close()
# === DOM
def _text_of(node):
if node.nodeType == node.ELEMENT_NODE:
return u''.join(_text_of(n) for n in node.childNodes)
elif node.nodeType == node.TEXT_NODE:
return node.nodeValue
else:
return u''
def _the_element_by_name(doc, tagName):
elts = doc.getElementsByTagName(tagName)
if len(elts) != 1:
raise ValueError("Expected exactly one <%s> tag, got %d." % (tagName, len(elts)))
return elts[0]
def _first_element(node):
n = node.firstChild
while n is not None:
if n.nodeType == n.ELEMENT_NODE:
return n
n = node.nextSibling
return None
def _find_elements(node, path):
if u'/' in path:
[first, rest] = path.split(u'/', 1)
for child in _find_elements(node, first):
for desc in _find_elements(child, rest):
yield desc
else:
for n in node.childNodes:
if n.nodeType == node.ELEMENT_NODE and n.nodeName == path:
yield n
# === Deki
def _format_page_id(id):
if isinstance(id, int):
return str(id)
elif id is Deki.HOME:
return 'home'
elif isinstance(id, basestring):
# Double-encoded, per the Deki API reference.
return '=' + _urlquote(_urlquote(id, ''))
class Deki(DreamClient):
HOME = object()
def get_page(self, page_id):
""" Get the content of a page from the wiki.
The page_id argument must be one of:
an int - The page id (an arbitrary number assigned by Deki)
a str - The page name (not the title, the full path that shows up in the URL)
Deki.HOME - Refers to the main page of the wiki.
Returns a Page object.
"""
p = Page(self)
p._load(page_id)
return p
def create_page(self, path, content, title=None, overwrite=False):
""" Create a new wiki page.
Parameters:
path - str - The page id.
content - str - The XML content to put in the new page.
The document element must be a <body>.
title - str - The page title. Keyword argument only.
Defaults to the last path-segment of path.
overwrite - bool - Whether to overwrite an existing page. If false,
and the page already exists, the method will throw an error.
"""
if title is None:
title = path.split('/')[-1]
doc = dom.parseString(content)
_check(doc.documentElement.tagName == 'body')
p = Page(self)
p._create(path, title, doc, overwrite)
def attach_file(self, page, name, data, mimetype, description=None):
"""Create or update a file attachment.
Parameters:
page - str - the page ID this file is related to
name - str - the name of the file
data - str - the file data
mimetype - str - the MIME type of the file
description - str - a description of the file
"""
p = {}
if description is not None:
p['description'] = description
url = _make_url('pages', _format_page_id(page),
'files', _format_page_id(name), **p)
r = self.put(url, data, mimetype)
_check(r.documentElement.nodeName == u'file')
def get_subpages(self, page_id):
""" Return the ids of all subpages of the given page. """
doc = self.get_xml(_make_url("pages", _format_page_id(page_id),
"files,subpages"))
for elt in _find_elements(doc, u'page/subpages/page.subpage/path'):
yield _text_of(elt)
def move_page(self, page_id, new_title, redirects=True):
""" Move an existing page to a new location.
A page cannot be moved to a destination that already exists, is a
descendant, or has a protected title (ex. Special:xxx, User:,
Template:).
When a page is moved, subpages under the specified page are also moved.
For each moved page, the system automatically creates an alias page
that redirects from the old to the new destination.
"""
self.post(_make_url("pages", _format_page_id(page_id), "move",
to=new_title,
redirects=redirects and "1" or "0"),
"", "text/plain")
class Page:
""" A Deki wiki page.
To obtain a page, call wiki.get_page(id).
Attributes:
title : unicode - The page title.
doc : Document - The content of the page as a DOM Document.
The root element of this document is a <body>.
path : unicode - The path. Use this to detect redirects, as otherwise
page.save() will overwrite the redirect with a copy of the content!
deki : Deki - The Deki object from which the page was loaded.
page_id : str/id/Deki.HOME - The page id used to load the page.
load_time : datetime - The time the page was loaded,
according to the clock on the client machine.
Methods:
save() - Save the modified document back to the server.
Only the page.title and the contents of page.doc are saved.
"""
def __init__(self, deki):
self.deki = deki
def _create(self, path, title, doc, overwrite):
self.title = title
self.doc = doc
self.page_id = path
if overwrite:
self.load_time = datetime(2500, 1, 1)
else:
self.load_time = datetime(1900, 1, 1)
self.path = path
self.save()
def _load(self, page_id):
""" page_id - See comment near the definition of `HOME`. """
load_time = datetime.utcnow()
# Getting the title is a whole separate query!
url = 'pages/%s/info' % _format_page_id(page_id)
doc = self.deki.get_xml(url)
title = _text_of(_the_element_by_name(doc, 'title'))
path = _text_of(_the_element_by_name(doc, 'path'))
# If you prefer to sling regexes, you can request format=raw instead.
# The result is an XML document with one big fat text node in the body.
url = _make_url('pages', _format_page_id(page_id), 'contents',
format='xhtml', mode='edit')
doc = self.deki.get_xml(url)
content = doc.documentElement
_check(content.tagName == u'content')
body = _first_element(content)
_check(body is not None)
_check(body.tagName == u'body')
doc.removeChild(content)
doc.appendChild(body)
self.page_id = page_id
self.load_time = load_time
self.title = title
self.path = path
self.doc = doc
def save(self):
p = {'edittime': _urlquote(self.load_time.strftime('%Y%m%d%H%M%S')),
'abort': 'modified'}
if self.title is not None:
p['title'] = _urlquote(self.title)
url = _make_url('pages', _format_page_id(self.page_id), 'contents', **p)
body = self.doc.documentElement
bodyInnerXML = ''.join(n.toxml('utf-8') for n in body.childNodes)
reply = self.deki.post(url, bodyInnerXML, 'text/plain; charset=utf-8')
_check(reply.documentElement.nodeName == u'edit')
_check(reply.documentElement.getAttribute(u'status') == u'success')