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 * 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 );
63 * @param {Object} [options] See #defaultOptions documentation above. Can also be overridden for
64 * each individual request by passing them to #get or #post (or directly #ajax) later on.
66 mw
.Api = function ( options
) {
67 // TODO: Share API objects with exact same config.
68 options
= options
|| {};
70 // Force a string if we got a mw.Uri object
71 if ( options
.ajax
&& options
.ajax
.url
!== undefined ) {
72 options
.ajax
.url
= String( options
.ajax
.url
);
75 options
.parameters
= $.extend( {}, defaultOptions
.parameters
, options
.parameters
);
76 options
.ajax
= $.extend( {}, defaultOptions
.ajax
, options
.ajax
);
78 this.defaults
= options
;
84 * Perform API get request
86 * @param {Object} parameters
87 * @param {Object} [ajaxOptions]
88 * @return {jQuery.Promise}
90 get: function ( parameters
, ajaxOptions
) {
91 ajaxOptions
= ajaxOptions
|| {};
92 ajaxOptions
.type
= 'GET';
93 return this.ajax( parameters
, ajaxOptions
);
97 * Perform API post request
99 * TODO: Post actions for non-local hostnames will need proxy.
101 * @param {Object} parameters
102 * @param {Object} [ajaxOptions]
103 * @return {jQuery.Promise}
105 post: function ( parameters
, ajaxOptions
) {
106 ajaxOptions
= ajaxOptions
|| {};
107 ajaxOptions
.type
= 'POST';
108 return this.ajax( parameters
, ajaxOptions
);
112 * Perform the API call.
114 * @param {Object} parameters
115 * @param {Object} [ajaxOptions]
116 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
119 ajax: function ( parameters
, ajaxOptions
) {
121 apiDeferred
= $.Deferred(),
124 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
125 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
127 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
128 if ( parameters
.token
) {
129 token
= parameters
.token
;
130 delete parameters
.token
;
133 for ( key
in parameters
) {
134 if ( $.isArray( parameters
[key
] ) ) {
135 parameters
[key
] = parameters
[key
].join( '|' );
139 // If multipart/form-data has been requested and emulation is possible, emulate it
141 ajaxOptions
.type
=== 'POST' &&
143 ajaxOptions
.contentType
=== 'multipart/form-data'
146 formData
= new FormData();
148 for ( key
in parameters
) {
149 formData
.append( key
, parameters
[key
] );
151 // If we extracted a token parameter, add it back in.
153 formData
.append( 'token', token
);
156 ajaxOptions
.data
= formData
;
158 // Prevent jQuery from mangling our FormData object
159 ajaxOptions
.processData
= false;
160 // Prevent jQuery from overriding the Content-Type header
161 ajaxOptions
.contentType
= false;
163 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
164 // So let's escape them here. See bug #28235
165 // This works because jQuery accepts data as a query string or as an Object
166 ajaxOptions
.data
= $.param( parameters
).replace( /\./g, '%2E' );
168 // If we extracted a token parameter, add it back in.
170 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
173 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
174 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
175 // it'll be wrong and the server will fail to decode the POST body
176 delete ajaxOptions
.contentType
;
180 // Make the AJAX request
181 xhr
= $.ajax( ajaxOptions
)
182 // If AJAX fails, reject API call with error code 'http'
183 // and details in second argument.
184 .fail( function ( xhr
, textStatus
, exception
) {
185 apiDeferred
.reject( 'http', {
187 textStatus
: textStatus
,
191 // AJAX success just means "200 OK" response, also check API error codes
192 .done( function ( result
, textStatus
, jqXHR
) {
193 if ( result
=== undefined || result
=== null || result
=== '' ) {
194 apiDeferred
.reject( 'ok-but-empty',
195 'OK response but empty result (check HTTP headers?)'
197 } else if ( result
.error
) {
198 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
199 apiDeferred
.reject( code
, result
);
201 apiDeferred
.resolve( result
, jqXHR
);
205 // Return the Promise
206 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
207 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
208 mw
.log( 'mw.Api error: ', code
, details
);
214 * Post to API with specified type of token. If we have no token, get one and try to post.
215 * If we have a cached token try using that, and if it fails, blank out the
216 * cached token and start over. For example to change an user option you could do:
218 * new mw.Api().postWithToken( 'options', {
220 * optionname: 'gender',
221 * optionvalue: 'female'
224 * @param {string} tokenType The name of the token, like options or edit.
225 * @param {Object} params API parameters
226 * @param {Object} [ajaxOptions]
227 * @return {jQuery.Promise} See #post
230 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
233 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
234 params
.token
= token
;
235 return api
.post( params
, ajaxOptions
).then(
236 // If no error, return to caller as-is
240 if ( code
=== 'badtoken' ) {
241 api
.badToken( tokenType
);
243 params
.token
= undefined;
244 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
245 params
.token
= token
;
246 return api
.post( params
, ajaxOptions
);
250 // Different error, pass on to let caller handle the error code
258 * Get a token for a certain action from the API.
260 * The assert parameter is only for internal use by postWithToken.
262 * @param {string} type Token type
263 * @return {jQuery.Promise}
264 * @return {Function} return.done
265 * @return {string} return.done.token Received token.
268 getToken: function ( type
, assert
) {
270 promiseGroup
= promises
[ this.defaults
.ajax
.url
],
271 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
274 apiPromise
= this.get( { action
: 'tokens', type
: type
, assert
: assert
} );
277 .then( function ( data
) {
278 if ( data
.tokens
&& data
.tokens
[type
+ 'token'] ) {
279 return data
.tokens
[type
+ 'token'];
282 // If token type is not available for this user,
283 // key '...token' is either missing or set to boolean false
284 return $.Deferred().reject( 'token-missing', data
);
286 // Clear promise. Do not cache errors.
287 delete promiseGroup
[ type
+ 'Token' ];
288 // Pass on to allow the caller to handle the error
291 // Attach abort handler
292 .promise( { abort
: apiPromise
.abort
} );
294 // Store deferred now so that we can use it again even if it isn't ready yet
295 if ( !promiseGroup
) {
296 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
298 promiseGroup
[ type
+ 'Token' ] = d
;
305 * Indicate that the cached token for a certain action of the API is bad.
307 * Call this if you get a 'badtoken' error when using the token returned by #getToken.
308 * You may also want to use #postWithToken instead, which invalidates bad cached tokens
311 * @param {string} type Token type
314 badToken: function ( type
) {
315 var promiseGroup
= promises
[ this.defaults
.ajax
.url
];
316 if ( promiseGroup
) {
317 delete promiseGroup
[ type
+ 'Token' ];
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
352 'copyuploaddisabled',
358 'filetype-banned-type',
361 'verification-error',
368 'fileexists-shared-forbidden',
372 // Stash-specific errors - expanded
375 'stashedfilenotfound',
387 * List of warnings we might receive from the API.
388 * For now, this just documents our expectation that there should be similar messages
396 }( mediaWiki
, jQuery
) );