3 // We allow people to omit these default parameters from API requests
4 // there is very customizable error handling here, on a per-call basis
5 // wondering, would it be simpler to make it easy to clone the api object,
6 // change error handling, and use that instead?
9 // Query parameters for API requests
15 // Ajax options for jQuery.ajax()
17 url: mw.util.wikiScript( 'api' ),
19 timeout: 30 * 1000, // 30 seconds
24 // Keyed by ajax url and symbolic name for the individual request
27 // Pre-populate with fake ajax promises to save http requests for tokens
28 // we already have on the page via the user.tokens module (bug 34733).
29 promises[ defaultOptions.ajax.url ] = {};
30 $.each( mw.user.tokens.get(), function ( key, value ) {
31 // This requires #getToken to use the same key as user.tokens.
32 // Format: token-type + "Token" (eg. editToken, patrolToken, watchToken).
33 promises[ defaultOptions.ajax.url ][ key ] = $.Deferred()
35 .promise( { abort: function () {} } );
39 * Constructor to create an object to interact with the API of a particular MediaWiki server.
40 * mw.Api objects represent the API of a particular MediaWiki server.
42 * TODO: Share API objects with exact same config.
44 * var api = new mw.Api();
48 * } ).done ( function ( data ) {
49 * console.log( data );
52 * Multiple values for a parameter can be specified using an array (since MW 1.25):
54 * var api = new mw.Api();
57 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
58 * } ).done ( function ( data ) {
59 * console.log( data );
65 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
66 * overridden for each individual request to {@link jQuery#ajax} later on.
68 mw.Api = function ( options ) {
70 if ( options === undefined ) {
74 // Force a string if we got a mw.Uri object
75 if ( options.ajax && options.ajax.url !== undefined ) {
76 options.ajax.url = String( options.ajax.url );
79 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
80 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
82 this.defaults = options;
88 * Perform API get request
90 * @param {Object} parameters
91 * @param {Object} [ajaxOptions]
92 * @return {jQuery.Promise}
94 get: function ( parameters, ajaxOptions ) {
95 ajaxOptions = ajaxOptions || {};
96 ajaxOptions.type = 'GET';
97 return this.ajax( parameters, ajaxOptions );
101 * Perform API post request
103 * TODO: Post actions for non-local hostnames will need proxy.
105 * @param {Object} parameters
106 * @param {Object} [ajaxOptions]
107 * @return {jQuery.Promise}
109 post: function ( parameters, ajaxOptions ) {
110 ajaxOptions = ajaxOptions || {};
111 ajaxOptions.type = 'POST';
112 return this.ajax( parameters, ajaxOptions );
116 * Perform the API call.
118 * @param {Object} parameters
119 * @param {Object} [ajaxOptions]
120 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
123 ajax: function ( parameters, ajaxOptions ) {
125 apiDeferred = $.Deferred(),
128 parameters = $.extend( {}, this.defaults.parameters, parameters );
129 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
131 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
132 if ( parameters.token ) {
133 token = parameters.token;
134 delete parameters.token;
137 for ( key in parameters ) {
138 if ( $.isArray( parameters[key] ) ) {
139 parameters[key] = parameters[key].join( '|' );
143 // If multipart/form-data has been requested and emulation is possible, emulate it
145 ajaxOptions.type === 'POST' &&
147 ajaxOptions.contentType === 'multipart/form-data'
150 formData = new FormData();
152 for ( key in parameters ) {
153 formData.append( key, parameters[key] );
155 // If we extracted a token parameter, add it back in.
157 formData.append( 'token', token );
160 ajaxOptions.data = formData;
162 // Prevent jQuery from mangling our FormData object
163 ajaxOptions.processData = false;
164 // Prevent jQuery from overriding the Content-Type header
165 ajaxOptions.contentType = false;
167 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
168 // So let's escape them here. See bug #28235
169 // This works because jQuery accepts data as a query string or as an Object
170 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
172 // If we extracted a token parameter, add it back in.
174 ajaxOptions.data += '&token=' + encodeURIComponent( token );
177 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
178 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
179 // it'll be wrong and the server will fail to decode the POST body
180 delete ajaxOptions.contentType;
184 // Make the AJAX request
185 xhr = $.ajax( ajaxOptions )
186 // If AJAX fails, reject API call with error code 'http'
187 // and details in second argument.
188 .fail( function ( xhr, textStatus, exception ) {
189 apiDeferred.reject( 'http', {
191 textStatus: textStatus,
195 // AJAX success just means "200 OK" response, also check API error codes
196 .done( function ( result, textStatus, jqXHR ) {
197 if ( result === undefined || result === null || result === '' ) {
198 apiDeferred.reject( 'ok-but-empty',
199 'OK response but empty result (check HTTP headers?)'
201 } else if ( result.error ) {
202 var code = result.error.code === undefined ? 'unknown' : result.error.code;
203 apiDeferred.reject( code, result );
205 apiDeferred.resolve( result, jqXHR );
209 // Return the Promise
210 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
211 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
212 mw.log( 'mw.Api error: ', code, details );
218 * Post to API with specified type of token. If we have no token, get one and try to post.
219 * If we have a cached token try using that, and if it fails, blank out the
220 * cached token and start over. For example to change an user option you could do:
222 * new mw.Api().postWithToken( 'options', {
224 * optionname: 'gender',
225 * optionvalue: 'female'
228 * @param {string} tokenType The name of the token, like options or edit.
229 * @param {Object} params API parameters
230 * @param {Object} [ajaxOptions]
231 * @return {jQuery.Promise} See #post
234 postWithToken: function ( tokenType, params, ajaxOptions ) {
237 return api.getToken( tokenType, params.assert ).then( function ( token ) {
238 params.token = token;
239 return api.post( params, ajaxOptions ).then(
240 // If no error, return to caller as-is
244 if ( code === 'badtoken' ) {
246 promises[ api.defaults.ajax.url ][ tokenType + 'Token' ] =
247 params.token = undefined;
250 return api.getToken( tokenType, params.assert ).then( function ( token ) {
251 params.token = token;
252 return api.post( params, ajaxOptions );
256 // Different error, pass on to let caller handle the error code
264 * Get a token for a certain action from the API.
266 * The assert parameter is only for internal use by postWithToken.
268 * @param {string} type Token type
269 * @return {jQuery.Promise}
270 * @return {Function} return.done
271 * @return {string} return.done.token Received token.
274 getToken: function ( type, assert ) {
276 promiseGroup = promises[ this.defaults.ajax.url ],
277 d = promiseGroup && promiseGroup[ type + 'Token' ];
280 apiPromise = this.get( { action: 'tokens', type: type, assert: assert } );
283 .then( function ( data ) {
284 // If token type is not available for this user,
285 // key '...token' is either missing or set to boolean false
286 if ( data.tokens && data.tokens[type + 'token'] ) {
287 return data.tokens[type + 'token'];
290 return $.Deferred().reject( 'token-missing', data );
292 // Clear promise. Do not cache errors.
293 delete promiseGroup[ type + 'Token' ];
295 // Pass on to allow the caller to handle the error
298 // Attach abort handler
299 .promise( { abort: apiPromise.abort } );
301 // Store deferred now so that we can use it again even if it isn't ready yet
302 if ( !promiseGroup ) {
303 promiseGroup = promises[ this.defaults.ajax.url ] = {};
305 promiseGroup[ type + 'Token' ] = d;
315 * List of errors we might receive from the API.
316 * For now, this just documents our expectation that there should be similar messages
320 // occurs when POST aborted
321 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
327 // really a warning, but we treat it like an error
331 // upload succeeded, but no image info.
332 // this is probably impossible, but might as well check for it
334 // remote errors, defined in API
342 'copyuploaddisabled',
348 'filetype-banned-type',
351 'verification-error',
358 'fileexists-shared-forbidden',
362 // Stash-specific errors - expanded
365 'stashedfilenotfound',
377 * List of warnings we might receive from the API.
378 * For now, this just documents our expectation that there should be similar messages
386 }( mediaWiki, jQuery ) );