bb0642e0eade51ac85dc8588632cc09ea1b7a996
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 );
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 * Perform API get request
80 * @param {Object} parameters
81 * @param {Object} [ajaxOptions]
82 * @return {jQuery.Promise}
84 get: function ( parameters
, ajaxOptions
) {
85 ajaxOptions
= ajaxOptions
|| {};
86 ajaxOptions
.type
= 'GET';
87 return this.ajax( parameters
, ajaxOptions
);
91 * Perform API post request
93 * TODO: Post actions for non-local hostnames will need proxy.
95 * @param {Object} parameters
96 * @param {Object} [ajaxOptions]
97 * @return {jQuery.Promise}
99 post: function ( parameters
, ajaxOptions
) {
100 ajaxOptions
= ajaxOptions
|| {};
101 ajaxOptions
.type
= 'POST';
102 return this.ajax( parameters
, ajaxOptions
);
106 * Perform the API call.
108 * @param {Object} parameters
109 * @param {Object} [ajaxOptions]
110 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
113 ajax: function ( parameters
, ajaxOptions
) {
115 apiDeferred
= $.Deferred(),
118 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
119 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
121 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
122 if ( parameters
.token
) {
123 token
= parameters
.token
;
124 delete parameters
.token
;
127 // If multipart/form-data has been requested and emulation is possible, emulate it
129 ajaxOptions
.type
=== 'POST' &&
131 ajaxOptions
.contentType
=== 'multipart/form-data'
134 formData
= new FormData();
136 for ( key
in parameters
) {
137 formData
.append( key
, parameters
[key
] );
139 // If we extracted a token parameter, add it back in.
141 formData
.append( 'token', token
);
144 ajaxOptions
.data
= formData
;
146 // Prevent jQuery from mangling our FormData object
147 ajaxOptions
.processData
= false;
148 // Prevent jQuery from overriding the Content-Type header
149 ajaxOptions
.contentType
= false;
151 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
152 // So let's escape them here. See bug #28235
153 // This works because jQuery accepts data as a query string or as an Object
154 ajaxOptions
.data
= $.param( parameters
).replace( /\./g, '%2E' );
156 // If we extracted a token parameter, add it back in.
158 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
161 if ( ajaxOptions
.contentType
=== 'multipart/form-data' ) {
162 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
163 // it'll be wrong and the server will fail to decode the POST body
164 delete ajaxOptions
.contentType
;
168 // Make the AJAX request
169 xhr
= $.ajax( ajaxOptions
)
170 // If AJAX fails, reject API call with error code 'http'
171 // and details in second argument.
172 .fail( function ( xhr
, textStatus
, exception
) {
173 apiDeferred
.reject( 'http', {
175 textStatus
: textStatus
,
179 // AJAX success just means "200 OK" response, also check API error codes
180 .done( function ( result
, textStatus
, jqXHR
) {
181 if ( result
=== undefined || result
=== null || result
=== '' ) {
182 apiDeferred
.reject( 'ok-but-empty',
183 'OK response but empty result (check HTTP headers?)'
185 } else if ( result
.error
) {
186 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
187 apiDeferred
.reject( code
, result
);
189 apiDeferred
.resolve( result
, jqXHR
);
193 // Return the Promise
194 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
195 if ( !( code
=== 'http' && details
&& details
.textStatus
=== 'abort' ) ) {
196 mw
.log( 'mw.Api error: ', code
, details
);
202 * Post to API with specified type of token. If we have no token, get one and try to post.
203 * If we have a cached token try using that, and if it fails, blank out the
204 * cached token and start over. For example to change an user option you could do:
206 * new mw.Api().postWithToken( 'options', {
208 * optionname: 'gender',
209 * optionvalue: 'female'
212 * @param {string} tokenType The name of the token, like options or edit.
213 * @param {Object} params API parameters
214 * @param {Object} [ajaxOptions]
215 * @return {jQuery.Promise} See #post
218 postWithToken: function ( tokenType
, params
, ajaxOptions
) {
221 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
222 params
.token
= token
;
223 return api
.post( params
, ajaxOptions
).then(
224 // If no error, return to caller as-is
228 if ( code
=== 'badtoken' ) {
230 promises
[ api
.defaults
.ajax
.url
][ tokenType
+ 'Token' ] =
231 params
.token
= undefined;
234 return api
.getToken( tokenType
, params
.assert
).then( function ( token
) {
235 params
.token
= token
;
236 return api
.post( params
, ajaxOptions
);
240 // Different error, pass on to let caller handle the error code
248 * Get a token for a certain action from the API.
250 * The assert parameter is only for internal use by postWithToken.
252 * @param {string} type Token type
253 * @return {jQuery.Promise}
254 * @return {Function} return.done
255 * @return {string} return.done.token Received token.
258 getToken: function ( type
, assert
) {
260 promiseGroup
= promises
[ this.defaults
.ajax
.url
],
261 d
= promiseGroup
&& promiseGroup
[ type
+ 'Token' ];
264 apiPromise
= this.get( { action
: 'tokens', type
: type
, assert
: assert
} );
267 .then( function ( data
) {
268 // If token type is not available for this user,
269 // key '...token' is either missing or set to boolean false
270 if ( data
.tokens
&& data
.tokens
[type
+ 'token'] ) {
271 return data
.tokens
[type
+ 'token'];
274 return $.Deferred().reject( 'token-missing', data
);
276 // Clear promise. Do not cache errors.
277 delete promiseGroup
[ type
+ 'Token' ];
279 // Pass on to allow the caller to handle the error
282 // Attach abort handler
283 .promise( { abort
: apiPromise
.abort
} );
285 // Store deferred now so that we can use it again even if it isn't ready yet
286 if ( !promiseGroup
) {
287 promiseGroup
= promises
[ this.defaults
.ajax
.url
] = {};
289 promiseGroup
[ type
+ 'Token' ] = d
;
299 * List of errors we might receive from the API.
300 * For now, this just documents our expectation that there should be similar messages
304 // occurs when POST aborted
305 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
311 // really a warning, but we treat it like an error
315 // upload succeeded, but no image info.
316 // this is probably impossible, but might as well check for it
318 // remote errors, defined in API
327 'copyuploaddisabled',
333 'filetype-banned-type',
336 'verification-error',
343 'fileexists-shared-forbidden',
351 * List of warnings we might receive from the API.
352 * For now, this just documents our expectation that there should be similar messages
360 }( mediaWiki
, jQuery
) );