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 deferreds to save http requests for tokens
28 // we already have on the page via the user.tokens module (bug 34733).
29 deferreds[ 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 deferreds[ 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 );
55 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
56 * overridden for each individual request to {@link jQuery#ajax} later on.
58 mw.Api = function ( options ) {
60 if ( options === undefined ) {
64 // Force a string if we got a mw.Uri object
65 if ( options.ajax && options.ajax.url !== undefined ) {
66 options.ajax.url = String( options.ajax.url );
69 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
70 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
72 this.defaults = options;
78 * Normalize the ajax options for compatibility and/or convenience methods.
80 * @param {Object} [arg] An object contaning one or more of options.ajax.
81 * @return {Object} Normalized ajax options.
83 normalizeAjaxOptions: function ( arg ) {
84 // Arg argument is usually empty
85 // (before MW 1.20 it was used to pass ok callbacks)
87 // Options can also be a success callback handler
88 if ( typeof arg === 'function' ) {
95 * Perform API get request
97 * @param {Object} parameters
98 * @param {Object|Function} [ajaxOptions]
99 * @return {jQuery.Promise}
101 get: function ( parameters, ajaxOptions ) {
102 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
103 ajaxOptions.type = 'GET';
104 return this.ajax( parameters, ajaxOptions );
108 * Perform API post request
110 * TODO: Post actions for non-local hostnames will need proxy.
112 * @param {Object} parameters
113 * @param {Object|Function} [ajaxOptions]
114 * @return {jQuery.Promise}
116 post: function ( parameters, ajaxOptions ) {
117 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
118 ajaxOptions.type = 'POST';
119 return this.ajax( parameters, ajaxOptions );
123 * Perform the API call.
125 * @param {Object} parameters
126 * @param {Object} [ajaxOptions]
127 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
130 ajax: function ( parameters, ajaxOptions ) {
132 apiDeferred = $.Deferred(),
133 msg = 'Use of mediawiki.api callback params is deprecated. Use the Promise instead.',
136 parameters = $.extend( {}, this.defaults.parameters, parameters );
137 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
139 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
140 if ( parameters.token ) {
141 token = parameters.token;
142 delete parameters.token;
145 // If multipart/form-data has been requested and emulation is possible, emulate it
147 ajaxOptions.type === 'POST' &&
149 ajaxOptions.contentType === 'multipart/form-data'
152 formData = new FormData();
154 for ( key in parameters ) {
155 formData.append( key, parameters[key] );
157 // If we extracted a token parameter, add it back in.
159 formData.append( 'token', token );
162 ajaxOptions.data = formData;
164 // Prevent jQuery from mangling our FormData object
165 ajaxOptions.processData = false;
166 // Prevent jQuery from overriding the Content-Type header
167 ajaxOptions.contentType = false;
169 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
170 // So let's escape them here. See bug #28235
171 // This works because jQuery accepts data as a query string or as an Object
172 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
174 // If we extracted a token parameter, add it back in.
176 ajaxOptions.data += '&token=' + encodeURIComponent( token );
179 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
180 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
181 // it'll be wrong and the server will fail to decode the POST body
182 delete ajaxOptions.contentType;
186 // Backwards compatibility: Before MediaWiki 1.20,
187 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
188 if ( ajaxOptions.ok ) {
189 mw.track( 'mw.deprecate', 'api.cbParam' );
191 apiDeferred.done( ajaxOptions.ok );
192 delete ajaxOptions.ok;
194 if ( ajaxOptions.err ) {
195 mw.track( 'mw.deprecate', 'api.cbParam' );
197 apiDeferred.fail( ajaxOptions.err );
198 delete ajaxOptions.err;
201 // Make the AJAX request
202 xhr = $.ajax( ajaxOptions )
203 // If AJAX fails, reject API call with error code 'http'
204 // and details in second argument.
205 .fail( function ( xhr, textStatus, exception ) {
206 apiDeferred.reject( 'http', {
208 textStatus: textStatus,
212 // AJAX success just means "200 OK" response, also check API error codes
213 .done( function ( result, textStatus, jqXHR ) {
214 if ( result === undefined || result === null || result === '' ) {
215 apiDeferred.reject( 'ok-but-empty',
216 'OK response but empty result (check HTTP headers?)'
218 } else if ( result.error ) {
219 var code = result.error.code === undefined ? 'unknown' : result.error.code;
220 apiDeferred.reject( code, result );
222 apiDeferred.resolve( result, jqXHR );
226 // Return the Promise
227 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
228 if ( code !== 'abort' ) {
229 mw.log( 'mw.Api error: ', code, details );
235 * Post to API with specified type of token. If we have no token, get one and try to post.
236 * If we have a cached token try using that, and if it fails, blank out the
237 * cached token and start over. For example to change an user option you could do:
239 * new mw.Api().postWithToken( 'options', {
241 * optionname: 'gender',
242 * optionvalue: 'female'
245 * @param {string} tokenType The name of the token, like options or edit.
246 * @param {Object} params API parameters
247 * @return {jQuery.Promise} See #post
250 postWithToken: function ( tokenType, params ) {
253 return api.getToken( tokenType ).then( function ( token ) {
254 params.token = token;
255 return api.post( params ).then(
256 // If no error, return to caller as-is
260 if ( code === 'badtoken' ) {
262 deferreds[ api.defaults.ajax.url ][ tokenType + 'Token' ] =
263 params.token = undefined;
266 return api.getToken( tokenType ).then( function ( token ) {
267 params.token = token;
268 return api.post( params );
272 // Different error, pass on to let caller handle the error code
280 * Get a token for a certain action from the API.
282 * @param {string} type Token type
283 * @return {jQuery.Promise}
284 * @return {Function} return.done
285 * @return {string} return.done.token Received token.
288 getToken: function ( type ) {
290 deferredGroup = deferreds[ this.defaults.ajax.url ],
291 d = deferredGroup && deferredGroup[ type + 'Token' ];
296 apiPromise = this.get( { action: 'tokens', type: type } )
297 .done( function ( data ) {
298 // If token type is not available for this user,
299 // key '...token' is missing or can contain Boolean false
300 if ( data.tokens && data.tokens[type + 'token'] ) {
301 d.resolve( data.tokens[type + 'token'] );
303 d.reject( 'token-missing', data );
308 // Attach abort handler
309 d.abort = apiPromise.abort;
311 // Store deferred now so that we can use this again even if it isn't ready yet
312 if ( !deferredGroup ) {
313 deferredGroup = deferreds[ this.defaults.ajax.url ] = {};
315 deferredGroup[ type + 'Token' ] = d;
318 return d.promise( { abort: d.abort } );
325 * List of errors we might receive from the API.
326 * For now, this just documents our expectation that there should be similar messages
330 // occurs when POST aborted
331 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
337 // really a warning, but we treat it like an error
341 // upload succeeded, but no image info.
342 // this is probably impossible, but might as well check for it
344 // remote errors, defined in API
353 'copyuploaddisabled',
359 'filetype-banned-type',
362 'verification-error',
369 'fileexists-shared-forbidden',
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 ) );