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.
14 var defaultOptions
= {
20 url
: mw
.util
.wikiScript( 'api' ),
21 timeout
: 30 * 1000, // 30 seconds
26 // Keyed by ajax url and symbolic name for the individual request
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()
37 .promise( { abort: function () {} } );
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.
44 * var api = new mw.Api();
48 * } ).done( function ( data ) {
49 * console.log( data );
52 * Since MW 1.25, multiple values for a parameter can be specified using an array:
54 * var api = new mw.Api();
57 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
58 * } ).done( function ( data ) {
59 * console.log( data );
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.
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.
69 mw
.Api = function ( options
) {
70 // TODO: Share API objects with exact same config.
71 options
= options
|| {};
73 // Force a string if we got a mw.Uri object
74 if ( options
.ajax
&& options
.ajax
.url
!== undefined ) {
75 options
.ajax
.url
= String( options
.ajax
.url
);
78 options
.parameters
= $.extend( {}, defaultOptions
.parameters
, options
.parameters
);
79 options
.ajax
= $.extend( {}, defaultOptions
.ajax
, options
.ajax
);
81 this.defaults
= options
;
87 * Abort all unfinished requests issued by this Api object.
92 $.each( this.requests
, function ( index
, request
) {
98 * Perform API get request
100 * @param {Object} parameters
101 * @param {Object} [ajaxOptions]
102 * @return {jQuery.Promise}
104 get: function ( parameters
, ajaxOptions
) {
105 ajaxOptions
= ajaxOptions
|| {};
106 ajaxOptions
.type
= 'GET';
107 return this.ajax( parameters
, ajaxOptions
);
111 * Perform API post request
113 * TODO: Post actions for non-local hostnames will need proxy.
115 * @param {Object} parameters
116 * @param {Object} [ajaxOptions]
117 * @return {jQuery.Promise}
119 post: function ( parameters
, ajaxOptions
) {
120 ajaxOptions
= ajaxOptions
|| {};
121 ajaxOptions
.type
= 'POST';
122 return this.ajax( parameters
, ajaxOptions
);
126 * Massage parameters from the nice format we accept into a format suitable for the API.
129 * @param {Object} parameters (modified in-place)
131 preprocessParameters: function ( parameters
) {
133 // Handle common MediaWiki API idioms for passing parameters
134 for ( key
in parameters
) {
135 // Multiple values are pipe-separated
136 if ( $.isArray( parameters
[ key
] ) ) {
137 parameters
[ key
] = parameters
[ key
].join( '|' );
139 // Boolean values are only false when not given at all
140 if ( parameters
[ key
] === false || parameters
[ key
] === undefined ) {
141 delete parameters
[ key
];
147 * Perform the API call.
149 * @param {Object} parameters
150 * @param {Object} [ajaxOptions]
151 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
154 ajax: function ( parameters
, ajaxOptions
) {
156 apiDeferred
= $.Deferred(),
159 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
160 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
162 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
163 if ( parameters
.token
) {
164 token
= parameters
.token
;
165 delete parameters
.token
;
168 this.preprocessParameters( parameters
);
170 // If multipart/form-data has been requested and emulation is possible, emulate it
172 ajaxOptions
.type
=== 'POST' &&
174 ajaxOptions
.contentType
=== 'multipart/form-data'
177 formData
= new FormData();
179 for ( key
in parameters
) {
180 formData
.append( key
, parameters
[ key
] );
182 // If we extracted a token parameter, add it back in.
184 formData
.append( 'token', token
);
187 ajaxOptions
.data
= formData
;
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;
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' );
199 // If we extracted a token parameter, add it back in.
201 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
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
;
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', {
218 textStatus
: textStatus
,
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?)'
228 } else if ( result
.error
) {
229 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
230 apiDeferred
.reject( code
, result
);
232 apiDeferred
.resolve( result
, jqXHR
);
236 this.requests
.push( xhr
);
237 // Return the Promise
238 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
239 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
240 mw
.log( 'mw.Api error: ', code
, details
);
246 * Post to API with specified type of token. If we have no token, get one and try to post.
247 * If we have a cached token try using that, and if it fails, blank out the
248 * cached token and start over. For example to change an user option you could do:
250 * new mw.Api().postWithToken( 'options', {
252 * optionname: 'gender',
253 * optionvalue: 'female'
256 * @param {string} tokenType The name of the token, like options or edit.
257 * @param {Object} params API parameters
258 * @param {Object} [ajaxOptions]
259 * @return {jQuery.Promise} See #post
262 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
265 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
266 params
.token
= token
;
267 return api
.post( params
, ajaxOptions
).then(
268 // If no error, return to caller as-is
272 if ( code
=== 'badtoken' ) {
273 api
.badToken( tokenType
);
275 params
.token
= undefined;
276 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
277 params
.token
= token
;
278 return api
.post( params
, ajaxOptions
);
282 // Different error, pass on to let caller handle the error code
290 * Get a token for a certain action from the API.
292 * The assert parameter is only for internal use by postWithToken.
294 * @param {string} type Token type
295 * @return {jQuery.Promise}
296 * @return {Function} return.done
297 * @return {string} return.done.token Received token.
300 getToken: function ( type
, assert
) {
302 promiseGroup
= promises
[ this.defaults
.ajax
.url
],
303 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
306 apiPromise
= this.get( { action
: 'tokens', type
: type
, assert
: assert
} );
309 .then( function ( data
) {
310 if ( data
.tokens
&& data
.tokens
[ type
+ 'token' ] ) {
311 return data
.tokens
[ type
+ 'token' ];
314 // If token type is not available for this user,
315 // key '...token' is either missing or set to boolean false
316 return $.Deferred().reject( 'token-missing', data
);
318 // Clear promise. Do not cache errors.
319 delete promiseGroup
[ type
+ 'Token' ];
320 // Pass on to allow the caller to handle the error
323 // Attach abort handler
324 .promise( { abort
: apiPromise
.abort
} );
326 // Store deferred now so that we can use it again even if it isn't ready yet
327 if ( !promiseGroup
) {
328 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
330 promiseGroup
[ type
+ 'Token' ] = d
;
337 * Indicate that the cached token for a certain action of the API is bad.
339 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
340 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
343 * @param {string} type Token type
346 badToken: function ( type
) {
347 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
348 if ( promiseGroup
) {
349 delete promiseGroup
[ type
+ 'Token' ];
357 * List of errors we might receive from the API.
358 * For now, this just documents our expectation that there should be similar messages
362 // occurs when POST aborted
363 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
369 // really a warning, but we treat it like an error
373 // upload succeeded, but no image info.
374 // this is probably impossible, but might as well check for it
376 // remote errors, defined in API
384 'copyuploaddisabled',
390 'filetype-banned-type',
393 'verification-error',
400 'fileexists-shared-forbidden',
404 // Stash-specific errors - expanded
407 'stashedfilenotfound',
419 * List of warnings we might receive from the API.
420 * For now, this just documents our expectation that there should be similar messages
428 }( mediaWiki
, jQuery
) );