mediawiki.api: Don't hold references to finished requests forever
[lhc/web/wiklou.git] / resources / src / mediawiki / api.js
1 ( function ( mw, $ ) {
2
3 /**
4 * @class mw.Api
5 */
6
7 /**
8 * @property {Object} defaultOptions Default options for #ajax calls. Can be overridden by passing
9 * `options` to mw.Api constructor.
10 * @property {Object} defaultOptions.parameters Default query parameters for API requests.
11 * @property {Object} defaultOptions.ajax Default options for jQuery#ajax.
12 * @private
13 */
14 var defaultOptions = {
15 parameters: {
16 action: 'query',
17 format: 'json'
18 },
19 ajax: {
20 url: mw.util.wikiScript( 'api' ),
21 timeout: 30 * 1000, // 30 seconds
22 dataType: 'json'
23 }
24 },
25
26 // Keyed by ajax url and symbolic name for the individual request
27 promises = {};
28
29 // Pre-populate with fake ajax promises to save http requests for tokens
30 // we already have on the page via the user.tokens module (bug 34733).
31 promises[ defaultOptions.ajax.url ] = {};
32 $.each( mw.user.tokens.get(), function ( key, value ) {
33 // This requires #getToken to use the same key as user.tokens.
34 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
35 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
36 .resolve( value )
37 .promise( { abort: function () {} } );
38 } );
39
40 /**
41 * Constructor to create an object to interact with the API of a particular MediaWiki server.
42 * mw.Api objects represent the API of a particular MediaWiki server.
43 *
44 * var api = new mw.Api();
45 * api.get( {
46 * action: 'query',
47 * meta: 'userinfo'
48 * } ).done( function ( data ) {
49 * console.log( data );
50 * } );
51 *
52 * Since MW 1.25, multiple values for a parameter can be specified using an array:
53 *
54 * var api = new mw.Api();
55 * api.get( {
56 * action: 'query',
57 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
58 * } ).done( function ( data ) {
59 * console.log( data );
60 * } );
61 *
62 * Since MW 1.26, boolean values for a parameter can be specified directly. If the value is
63 * `false` or `undefined`, the parameter will be omitted from the request, as required by the API.
64 *
65 * @constructor
66 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
67 * each individual request by passing them to #get or #post (or directly #ajax) later on.
68 */
69 mw.Api = function ( options ) {
70 options = options || {};
71
72 // Force a string if we got a mw.Uri object
73 if ( options.ajax && options.ajax.url !== undefined ) {
74 options.ajax.url = String( options.ajax.url );
75 }
76
77 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
78 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
79
80 this.defaults = options;
81 this.requests = [];
82 };
83
84 mw.Api.prototype = {
85 /**
86 * Abort all unfinished requests issued by this Api object.
87 *
88 * @method
89 */
90 abort: function () {
91 $.each( this.requests, function ( index, request ) {
92 if ( request ) {
93 request.abort();
94 }
95 } );
96 },
97
98 /**
99 * Perform API get request
100 *
101 * @param {Object} parameters
102 * @param {Object} [ajaxOptions]
103 * @return {jQuery.Promise}
104 */
105 get: function ( parameters, ajaxOptions ) {
106 ajaxOptions = ajaxOptions || {};
107 ajaxOptions.type = 'GET';
108 return this.ajax( parameters, ajaxOptions );
109 },
110
111 /**
112 * Perform API post request
113 *
114 * @param {Object} parameters
115 * @param {Object} [ajaxOptions]
116 * @return {jQuery.Promise}
117 */
118 post: function ( parameters, ajaxOptions ) {
119 ajaxOptions = ajaxOptions || {};
120 ajaxOptions.type = 'POST';
121 return this.ajax( parameters, ajaxOptions );
122 },
123
124 /**
125 * Massage parameters from the nice format we accept into a format suitable for the API.
126 *
127 * @private
128 * @param {Object} parameters (modified in-place)
129 */
130 preprocessParameters: function ( parameters ) {
131 var key;
132 // Handle common MediaWiki API idioms for passing parameters
133 for ( key in parameters ) {
134 // Multiple values are pipe-separated
135 if ( $.isArray( parameters[ key ] ) ) {
136 parameters[ key ] = parameters[ key ].join( '|' );
137 }
138 // Boolean values are only false when not given at all
139 if ( parameters[ key ] === false || parameters[ key ] === undefined ) {
140 delete parameters[ key ];
141 }
142 }
143 },
144
145 /**
146 * Perform the API call.
147 *
148 * @param {Object} parameters
149 * @param {Object} [ajaxOptions]
150 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
151 * Fail: Error code
152 */
153 ajax: function ( parameters, ajaxOptions ) {
154 var token, requestIndex,
155 api = this,
156 apiDeferred = $.Deferred(),
157 xhr, key, formData;
158
159 parameters = $.extend( {}, this.defaults.parameters, parameters );
160 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
161
162 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
163 if ( parameters.token ) {
164 token = parameters.token;
165 delete parameters.token;
166 }
167
168 this.preprocessParameters( parameters );
169
170 // If multipart/form-data has been requested and emulation is possible, emulate it
171 if (
172 ajaxOptions.type === 'POST' &&
173 window.FormData &&
174 ajaxOptions.contentType === 'multipart/form-data'
175 ) {
176
177 formData = new FormData();
178
179 for ( key in parameters ) {
180 formData.append( key, parameters[ key ] );
181 }
182 // If we extracted a token parameter, add it back in.
183 if ( token ) {
184 formData.append( 'token', token );
185 }
186
187 ajaxOptions.data = formData;
188
189 // Prevent jQuery from mangling our FormData object
190 ajaxOptions.processData = false;
191 // Prevent jQuery from overriding the Content-Type header
192 ajaxOptions.contentType = false;
193 } else {
194 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
195 // So let's escape them here. See bug #28235
196 // This works because jQuery accepts data as a query string or as an Object
197 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
198
199 // If we extracted a token parameter, add it back in.
200 if ( token ) {
201 ajaxOptions.data += '&token=' + encodeURIComponent( token );
202 }
203
204 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
205 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
206 // it'll be wrong and the server will fail to decode the POST body
207 delete ajaxOptions.contentType;
208 }
209 }
210
211 // Make the AJAX request
212 xhr = $.ajax( ajaxOptions )
213 // If AJAX fails, reject API call with error code 'http'
214 // and details in second argument.
215 .fail( function ( xhr, textStatus, exception ) {
216 apiDeferred.reject( 'http', {
217 xhr: xhr,
218 textStatus: textStatus,
219 exception: exception
220 } );
221 } )
222 // AJAX success just means "200 OK" response, also check API error codes
223 .done( function ( result, textStatus, jqXHR ) {
224 if ( result === undefined || result === null || result === '' ) {
225 apiDeferred.reject( 'ok-but-empty',
226 'OK response but empty result (check HTTP headers?)'
227 );
228 } else if ( result.error ) {
229 var code = result.error.code === undefined ? 'unknown' : result.error.code;
230 apiDeferred.reject( code, result );
231 } else {
232 apiDeferred.resolve( result, jqXHR );
233 }
234 } );
235
236 requestIndex = this.requests.length;
237 this.requests.push( xhr );
238 xhr.always( function () {
239 api.requests[ requestIndex ] = null;
240 } );
241 // Return the Promise
242 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
243 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
244 mw.log( 'mw.Api error: ', code, details );
245 }
246 } );
247 },
248
249 /**
250 * Post to API with specified type of token. If we have no token, get one and try to post.
251 * If we have a cached token try using that, and if it fails, blank out the
252 * cached token and start over. For example to change an user option you could do:
253 *
254 * new mw.Api().postWithToken( 'options', {
255 * action: 'options',
256 * optionname: 'gender',
257 * optionvalue: 'female'
258 * } );
259 *
260 * @param {string} tokenType The name of the token, like options or edit.
261 * @param {Object} params API parameters
262 * @param {Object} [ajaxOptions]
263 * @return {jQuery.Promise} See #post
264 * @since 1.22
265 */
266 postWithToken: function ( tokenType, params, ajaxOptions ) {
267 var api = this;
268
269 return api.getToken( tokenType, params.assert ).then( function ( token ) {
270 params.token = token;
271 return api.post( params, ajaxOptions ).then(
272 // If no error, return to caller as-is
273 null,
274 // Error handler
275 function ( code ) {
276 if ( code === 'badtoken' ) {
277 api.badToken( tokenType );
278 // Try again, once
279 params.token = undefined;
280 return api.getToken( tokenType, params.assert ).then( function ( token ) {
281 params.token = token;
282 return api.post( params, ajaxOptions );
283 } );
284 }
285
286 // Different error, pass on to let caller handle the error code
287 return this;
288 }
289 );
290 } );
291 },
292
293 /**
294 * Get a token for a certain action from the API.
295 *
296 * The assert parameter is only for internal use by postWithToken.
297 *
298 * @param {string} type Token type
299 * @return {jQuery.Promise}
300 * @return {Function} return.done
301 * @return {string} return.done.token Received token.
302 * @since 1.22
303 */
304 getToken: function ( type, assert ) {
305 var apiPromise,
306 promiseGroup = promises[ this.defaults.ajax.url ],
307 d = promiseGroup && promiseGroup[ type + 'Token' ];
308
309 if ( !d ) {
310 apiPromise = this.get( { action: 'tokens', type: type, assert: assert } );
311
312 d = apiPromise
313 .then( function ( data ) {
314 if ( data.tokens && data.tokens[ type + 'token' ] ) {
315 return data.tokens[ type + 'token' ];
316 }
317
318 // If token type is not available for this user,
319 // key '...token' is either missing or set to boolean false
320 return $.Deferred().reject( 'token-missing', data );
321 }, function () {
322 // Clear promise. Do not cache errors.
323 delete promiseGroup[ type + 'Token' ];
324 // Pass on to allow the caller to handle the error
325 return this;
326 } )
327 // Attach abort handler
328 .promise( { abort: apiPromise.abort } );
329
330 // Store deferred now so that we can use it again even if it isn't ready yet
331 if ( !promiseGroup ) {
332 promiseGroup = promises[ this.defaults.ajax.url ] = {};
333 }
334 promiseGroup[ type + 'Token' ] = d;
335 }
336
337 return d;
338 },
339
340 /**
341 * Indicate that the cached token for a certain action of the API is bad.
342 *
343 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
344 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
345 * automatically.
346 *
347 * @param {string} type Token type
348 * @since 1.26
349 */
350 badToken: function ( type ) {
351 var promiseGroup = promises[ this.defaults.ajax.url ];
352 if ( promiseGroup ) {
353 delete promiseGroup[ type + 'Token' ];
354 }
355 }
356 };
357
358 /**
359 * @static
360 * @property {Array}
361 * List of errors we might receive from the API.
362 * For now, this just documents our expectation that there should be similar messages
363 * available.
364 */
365 mw.Api.errors = [
366 // occurs when POST aborted
367 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
368 'ok-but-empty',
369
370 // timeout
371 'timeout',
372
373 // really a warning, but we treat it like an error
374 'duplicate',
375 'duplicate-archive',
376
377 // upload succeeded, but no image info.
378 // this is probably impossible, but might as well check for it
379 'noimageinfo',
380 // remote errors, defined in API
381 'uploaddisabled',
382 'nomodule',
383 'mustbeposted',
384 'badaccess-groups',
385 'missingresult',
386 'missingparam',
387 'invalid-file-key',
388 'copyuploaddisabled',
389 'mustbeloggedin',
390 'empty-file',
391 'file-too-large',
392 'filetype-missing',
393 'filetype-banned',
394 'filetype-banned-type',
395 'filename-tooshort',
396 'illegal-filename',
397 'verification-error',
398 'hookaborted',
399 'unknown-error',
400 'internal-error',
401 'overwrite',
402 'badtoken',
403 'fetchfileerror',
404 'fileexists-shared-forbidden',
405 'invalidtitle',
406 'notloggedin',
407
408 // Stash-specific errors - expanded
409 'stashfailed',
410 'stasherror',
411 'stashedfilenotfound',
412 'stashpathinvalid',
413 'stashfilestorage',
414 'stashzerolength',
415 'stashnotloggedin',
416 'stashwrongowner',
417 'stashnosuchfilekey'
418 ];
419
420 /**
421 * @static
422 * @property {Array}
423 * List of warnings we might receive from the API.
424 * For now, this just documents our expectation that there should be similar messages
425 * available.
426 */
427 mw.Api.warnings = [
428 'duplicate',
429 'exists'
430 ];
431
432 }( mediaWiki, jQuery ) );