-
Notifications
You must be signed in to change notification settings - Fork 7
/
mwapi.lua
372 lines (341 loc) · 10.7 KB
/
mwapi.lua
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
--[[
Author: Trougnouf (Benoit Brummer) <[email protected]>
Contributor: Simon Legner (simon04), Alexander Misel
mediawikiapi.lua uses some code adapted from LrMediaWiki
LrMediaWiki authors:
Robin Krahl <[email protected]>
Eckhard Henkel <[email protected]>
Dependencies:
* lua-sec: Lua bindings for OpenSSL library to provide TLS/SSL communication
* lua-luajson: JSON parser/encoder for Lua
* lua-multipart-post: HTTP Multipart Post helper
]]
local Utils = require('mwtest/utils')
local https = require('ssl.https')
local json = require('rapidjson')
local ltn12 = require('ltn12')
local mpost = require('multipart-post')
local MediaWikiApi = {
userAgent = string.format('mediawikilua %d.%d', 0, 2),
apiPath = 'https://zh.wikipedia.org/w/api.php',
cookie = {},
done_pages = {},
edit_token = nil,
base_time = nil
}
local function httpsget(url, reqheaders)
local res = {}
local _, code, resheaders, _ = https.request {
url = url,
protocol = 'tlsv1_2',
headers = reqheaders,
sink = ltn12.sink.table(res)
}
resheaders = resheaders or {}
resheaders.status = code
return table.concat(res), resheaders
end
local function httpspost(url, postBody, reqheaders)
local res = {}
local _, code, resheaders, _ = https.request {
url = url,
method = 'POST',
protocol = 'tlsv1_2',
headers = reqheaders,
source = ltn12.source.string(postBody),
sink = ltn12.sink.table(res)
}
resheaders = resheaders or {}
resheaders.status = code
return table.concat(res), resheaders
end
local function throwUserError(text)
print(json.encode(MediaWikiApi.done_pages))
error(text)
end
-- parse a received cookie and update MediaWikiApi.cookie
function MediaWikiApi.parseCookie(unparsedcookie)
while unparsedcookie and string.len(unparsedcookie) > 0 do
local i = string.find(unparsedcookie, ';')
local crumb = string.sub(unparsedcookie, 1, i - 1)
local isep = string.find(crumb, '=')
if isep then
local cvar = string.sub(crumb, 1, isep - 1)
local icvarcomma = string.find(cvar, ',')
while icvarcomma do
cvar = string.sub(cvar, icvarcomma + 2)
icvarcomma = string.find(cvar, ',')
end
MediaWikiApi.cookie[cvar] = string.sub(crumb, isep + 1)
end
local nexti = string.find(unparsedcookie, ',')
if not nexti then
return
end
unparsedcookie = string.sub(unparsedcookie, nexti + 2)
end
end
-- generate a cookie string from MediaWikiApi.cookie to send to server
function MediaWikiApi.cookie2string()
local prestr = {}
for cvar, cval in pairs(MediaWikiApi.cookie) do
table.insert(prestr, cvar .. '=' .. cval .. ';')
end
return table.concat(prestr)
end
function MediaWikiApi.getCurrent(title)
local arguments = {
action = 'query',
prop = 'revisions',
titles = title,
rvprop = 'ids|content|timestamp',
format = 'json',
formatversion = 2
}
local jsonres = MediaWikiApi.performRequest(arguments)
if not jsonres.query.pages[1].missing then
return jsonres.query.pages[1].revisions[1]
end
end
-- Demand an edit token. probably can change this to request only one per session
function MediaWikiApi.getEditToken()
if MediaWikiApi.edit_token == nil then
local arguments = {
action = 'query',
meta = 'tokens',
type = 'csrf',
format = 'json'
}
local jsonres = MediaWikiApi.performRequest(arguments)
MediaWikiApi.edit_token = jsonres.query.tokens.csrftoken
end
return MediaWikiApi.edit_token
end
function MediaWikiApi.edit(title, text, summary)
--print('\nEditing', title, text)
local arguments = {
action = 'edit',
title = title,
text = text,
summary = summary,
token = MediaWikiApi.getEditToken(),
basetimestamp = MediaWikiApi.base_time,
starttimestamp = os.time(),
format = 'json'
}
local res_error = MediaWikiApi.performRequest(arguments).error
if res_error then
throwUserError('Edit failed. Reason: ' .. res_error.info)
end
end
function MediaWikiApi.editPend(title, text, summary, isPrepend)
--print('\nEditing', title, text)
local arguments = {
action = 'edit',
title = title,
summary = summary,
token = MediaWikiApi.getEditToken(),
format = 'json'
}
if isPrepend then
arguments.prependtext = text
else
arguments.appendtext = text
end
local res_error = MediaWikiApi.performRequest(arguments).error
if res_error then
if res_error.code == 'editconflict' then
MediaWikiApi.trace(res_error.info)
else
throwUserError('Edit failed. Reason: ' .. res_error.info)
end
end
end
function MediaWikiApi.uploadfile(filepath, pagetext, filename, overwrite, comment)
local file_handler = io.open(filepath)
local content = {
action = 'upload',
filename = filename,
text = pagetext,
comment = comment,
token = MediaWikiApi.getEditToken(),
file = {
filename = 'whatevs',
data = file_handler:read('*all')
}
}
if overwrite then
content['ignorewarnings'] = 'true'
end
local res = {}
local req = mpost.gen_request(content)
req.headers['cookie'] = MediaWikiApi.cookie2string()
req.url = MediaWikiApi.apiPath
req.sink = ltn12.sink.table(res)
local _, code, resheaders = https.request(req)
--MediaWikiApi.trace(' Result headers:', resheaders)
MediaWikiApi.parseCookie(resheaders['set-cookie'])
return code, resheaders, res
end
-- Code adapted from LrMediaWiki:
MediaWikiApi.trace = function(...)
print(...)
end
--- Convert HTTP arguments to a URL-encoded request body.
-- @param arguments (table) the arguments to convert
-- @return (string) a request body created from the URL-encoded arguments
function MediaWikiApi.createRequestBody(arguments)
local body = nil
for key, value in pairs(arguments) do
if body then
body = body .. '&'
else
body = ''
end
body = body .. Utils.urlEncode(key) .. '=' .. Utils.urlEncode(value)
end
return body or ''
end
function MediaWikiApi.performHttpRequest(path, arguments, post) -- changed signature!
local requestBody = MediaWikiApi.createRequestBody(arguments)
local requestHeaders = {
['Content-Type'] = 'application/x-www-form-urlencoded',
['User-Agent'] = MediaWikiApi.userAgent
}
if post then
requestHeaders['Content-Length'] = #requestBody
end
requestHeaders['Cookie'] = MediaWikiApi.cookie2string()
MediaWikiApi.trace('Performing HTTP request')
-- MediaWikiApi.trace(' Path:', path)
-- MediaWikiApi.trace(' Request body:', requestBody)
local resultBody, resultHeaders
local dorequest = function(try_num)
if post then
resultBody, resultHeaders = httpspost(path, requestBody, requestHeaders)
else
resultBody, resultHeaders = httpsget(path .. '?' .. requestBody, requestHeaders)
end
end
for i = 1, 3 do
print(' Attempt ' .. i)
dorequest(i)
if resultHeaders.status ~= 'timeout' and resultHeaders.status ~= 'wantread' then
break
end
end
if not resultHeaders.status or resultHeaders.status == 'closed' then
throwUserError('No network connection')
elseif resultHeaders.status ~= 200 then
throwUserError('HttpError! Received HTTP status = ' .. resultHeaders.status)
end
MediaWikiApi.trace(' Result status:', resultHeaders.status)
MediaWikiApi.parseCookie(resultHeaders['set-cookie'])
-- MediaWikiApi.trace('new cookie: '..resultHeaders['set-cookie'])
-- MediaWikiApi.trace(' Result body:', resultBody)
return resultBody
end
function MediaWikiApi.performRequest(arguments)
local post = true
if arguments.action == 'query' then
post = false
end
local resultBody = MediaWikiApi.performHttpRequest(MediaWikiApi.apiPath, arguments, post)
local jsonres = json.decode(resultBody)
return jsonres
end
function MediaWikiApi.logout()
-- See https://www.mediawiki.org/wiki/API:Logout
local arguments = {
action = 'logout'
}
MediaWikiApi.performRequest(arguments)
end
function MediaWikiApi.login(username, password)
-- See https://www.mediawiki.org/wiki/API:Login
-- Check if the credentials are a main-account or a bot-account.
-- The different credentials need different login arguments.
-- The existance of the character '@' inside of an username is an
-- identicator if the credentials are a bot-account or a main-account.
local credentials
if string.find(username, '@') then
credentials = 'bot-account'
else
credentials = 'main-account'
end
MediaWikiApi.trace('Credentials: ' .. credentials)
-- Check if a user is logged in:
local arguments = {
action = 'query',
meta = 'userinfo',
format = 'json'
}
local jsonres = MediaWikiApi.performRequest(arguments)
local id = jsonres.query.userinfo.id
local name = jsonres.query.userinfo.name
if id == '0' or id == 0 then -- not logged in, name is the IP address
MediaWikiApi.trace('Not logged in, need to login')
else -- id ~= '0' – logged in
MediaWikiApi.trace('Logged in as user "' .. name .. '" (ID: ' .. id .. ')')
if name == username then -- user is already logged in
MediaWikiApi.trace('No new login needed (1)')
return true
else -- name ~= username
-- Check if name is main-account name of bot-username
if credentials == 'bot-account' then
local pattern = '(.*)@' -- all characters up to '@'
if name == string.match(username, pattern) then
MediaWikiApi.trace('No new login needed (2)')
return true
end
end
MediaWikiApi.trace('Logout and new login needed with username "' .. username .. '".')
MediaWikiApi.logout() -- without this logout a new login MIGHT fail
end
end
-- A login token needs to be retrieved prior of a login action:
arguments = {
action = 'query',
meta = 'tokens',
type = 'login',
format = 'json'
}
jsonres = MediaWikiApi.performRequest(arguments)
local logintoken = jsonres.query.tokens.logintoken
-- Perform login:
if credentials == 'main-account' then
arguments = {
format = 'json',
action = 'clientlogin',
loginreturnurl = 'https://www.mediawiki.org', -- dummy; required parameter
username = username,
password = password,
logintoken = logintoken
}
jsonres = MediaWikiApi.performRequest(arguments)
local loginResult = jsonres.clientlogin.status
if loginResult == 'PASS' then
return true
else
return jsonres.clientlogin.message
end
else -- credentials == bot-account
assert(credentials == 'bot-account')
arguments = {
format = 'json',
action = 'login',
lgname = username,
lgpassword = password,
lgtoken = logintoken
}
jsonres = MediaWikiApi.performRequest(arguments)
local loginResult = jsonres.login.result
if loginResult == 'Success' then
return true
else
return jsonres.login.reason
end
end
end
-- end of LrMediaWiki code
return MediaWikiApi