Split /resources into /resources/lib and /resources/src
[lhc/web/wiklou.git] / resources / src / mediawiki.api / mediawiki.api.js
1 ( function ( mw, $ ) {
2
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?
7 var defaultOptions = {
8
9 // Query parameters for API requests
10 parameters: {
11 action: 'query',
12 format: 'json'
13 },
14
15 // Ajax options for jQuery.ajax()
16 ajax: {
17 url: mw.util.wikiScript( 'api' ),
18
19 timeout: 30 * 1000, // 30 seconds
20
21 dataType: 'json'
22 }
23 },
24 // Keyed by ajax url and symbolic name for the individual request
25 deferreds = {};
26
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()
34 .resolve( value )
35 .promise( { abort: function () {} } );
36 } );
37
38 /**
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.
41 *
42 * TODO: Share API objects with exact same config.
43 *
44 * var api = new mw.Api();
45 * api.get( {
46 * action: 'query',
47 * meta: 'userinfo'
48 * } ).done ( function ( data ) {
49 * console.log( data );
50 * } );
51 *
52 * @class
53 *
54 * @constructor
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.
57 */
58 mw.Api = function ( options ) {
59
60 if ( options === undefined ) {
61 options = {};
62 }
63
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 );
67 }
68
69 options.parameters = $.extend( {}, defaultOptions.parameters, options.parameters );
70 options.ajax = $.extend( {}, defaultOptions.ajax, options.ajax );
71
72 this.defaults = options;
73 };
74
75 mw.Api.prototype = {
76
77 /**
78 * Normalize the ajax options for compatibility and/or convenience methods.
79 *
80 * @param {Object} [arg] An object contaning one or more of options.ajax.
81 * @return {Object} Normalized ajax options.
82 */
83 normalizeAjaxOptions: function ( arg ) {
84 // Arg argument is usually empty
85 // (before MW 1.20 it was used to pass ok callbacks)
86 var opts = arg || {};
87 // Options can also be a success callback handler
88 if ( typeof arg === 'function' ) {
89 opts = { ok: arg };
90 }
91 return opts;
92 },
93
94 /**
95 * Perform API get request
96 *
97 * @param {Object} parameters
98 * @param {Object|Function} [ajaxOptions]
99 * @return {jQuery.Promise}
100 */
101 get: function ( parameters, ajaxOptions ) {
102 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
103 ajaxOptions.type = 'GET';
104 return this.ajax( parameters, ajaxOptions );
105 },
106
107 /**
108 * Perform API post request
109 *
110 * TODO: Post actions for non-local hostnames will need proxy.
111 *
112 * @param {Object} parameters
113 * @param {Object|Function} [ajaxOptions]
114 * @return {jQuery.Promise}
115 */
116 post: function ( parameters, ajaxOptions ) {
117 ajaxOptions = this.normalizeAjaxOptions( ajaxOptions );
118 ajaxOptions.type = 'POST';
119 return this.ajax( parameters, ajaxOptions );
120 },
121
122 /**
123 * Perform the API call.
124 *
125 * @param {Object} parameters
126 * @param {Object} [ajaxOptions]
127 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
128 * Fail: Error code
129 */
130 ajax: function ( parameters, ajaxOptions ) {
131 var token,
132 apiDeferred = $.Deferred(),
133 msg = 'Use of mediawiki.api callback params is deprecated. Use the Promise instead.',
134 xhr;
135
136 parameters = $.extend( {}, this.defaults.parameters, parameters );
137 ajaxOptions = $.extend( {}, this.defaults.ajax, ajaxOptions );
138
139 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
140 if ( parameters.token ) {
141 token = parameters.token;
142 delete parameters.token;
143 }
144 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
145 // So let's escape them here. See bug #28235
146 // This works because jQuery accepts data as a query string or as an Object
147 ajaxOptions.data = $.param( parameters ).replace( /\./g, '%2E' );
148
149 // If we extracted a token parameter, add it back in.
150 if ( token ) {
151 ajaxOptions.data += '&token=' + encodeURIComponent( token );
152 }
153
154 // Backwards compatibility: Before MediaWiki 1.20,
155 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
156 if ( ajaxOptions.ok ) {
157 mw.track( 'mw.deprecate', 'api.cbParam' );
158 mw.log.warn( msg );
159 apiDeferred.done( ajaxOptions.ok );
160 delete ajaxOptions.ok;
161 }
162 if ( ajaxOptions.err ) {
163 mw.track( 'mw.deprecate', 'api.cbParam' );
164 mw.log.warn( msg );
165 apiDeferred.fail( ajaxOptions.err );
166 delete ajaxOptions.err;
167 }
168
169 // Make the AJAX request
170 xhr = $.ajax( ajaxOptions )
171 // If AJAX fails, reject API call with error code 'http'
172 // and details in second argument.
173 .fail( function ( xhr, textStatus, exception ) {
174 apiDeferred.reject( 'http', {
175 xhr: xhr,
176 textStatus: textStatus,
177 exception: exception
178 } );
179 } )
180 // AJAX success just means "200 OK" response, also check API error codes
181 .done( function ( result, textStatus, jqXHR ) {
182 if ( result === undefined || result === null || result === '' ) {
183 apiDeferred.reject( 'ok-but-empty',
184 'OK response but empty result (check HTTP headers?)'
185 );
186 } else if ( result.error ) {
187 var code = result.error.code === undefined ? 'unknown' : result.error.code;
188 apiDeferred.reject( code, result );
189 } else {
190 apiDeferred.resolve( result, jqXHR );
191 }
192 } );
193
194 // Return the Promise
195 return apiDeferred.promise( { abort: xhr.abort } ).fail( function ( code, details ) {
196 mw.log( 'mw.Api error: ', code, details );
197 } );
198 },
199
200 /**
201 * Post to API with specified type of token. If we have no token, get one and try to post.
202 * If we have a cached token try using that, and if it fails, blank out the
203 * cached token and start over. For example to change an user option you could do:
204 *
205 * new mw.Api().postWithToken( 'options', {
206 * action: 'options',
207 * optionname: 'gender',
208 * optionvalue: 'female'
209 * } );
210 *
211 * @param {string} tokenType The name of the token, like options or edit.
212 * @param {Object} params API parameters
213 * @return {jQuery.Promise} See #post
214 * @since 1.22
215 */
216 postWithToken: function ( tokenType, params ) {
217 var api = this;
218
219 return api.getToken( tokenType ).then( function ( token ) {
220 params.token = token;
221 return api.post( params ).then(
222 // If no error, return to caller as-is
223 null,
224 // Error handler
225 function ( code ) {
226 if ( code === 'badtoken' ) {
227 // Clear from cache
228 deferreds[ this.defaults.ajax.url ][ tokenType + 'Token' ] =
229 params.token = undefined;
230
231 // Try again, once
232 return api.getToken( tokenType ).then( function ( token ) {
233 params.token = token;
234 return api.post( params );
235 } );
236 }
237
238 // Different error, pass on to let caller handle the error code
239 return this;
240 }
241 );
242 } );
243 },
244
245 /**
246 * Get a token for a certain action from the API.
247 *
248 * @param {string} type Token type
249 * @return {jQuery.Promise}
250 * @return {Function} return.done
251 * @return {string} return.done.token Received token.
252 * @since 1.22
253 */
254 getToken: function ( type ) {
255 var apiPromise,
256 deferredGroup = deferreds[ this.defaults.ajax.url ],
257 d = deferredGroup && deferredGroup[ type + 'Token' ];
258
259 if ( !d ) {
260 d = $.Deferred();
261
262 apiPromise = this.get( { action: 'tokens', type: type } )
263 .done( function ( data ) {
264 // If token type is not available for this user,
265 // key '...token' is missing or can contain Boolean false
266 if ( data.tokens && data.tokens[type + 'token'] ) {
267 d.resolve( data.tokens[type + 'token'] );
268 } else {
269 d.reject( 'token-missing', data );
270 }
271 } )
272 .fail( d.reject );
273
274 // Attach abort handler
275 d.abort = apiPromise.abort;
276
277 // Store deferred now so that we can use this again even if it isn't ready yet
278 if ( !deferredGroup ) {
279 deferredGroup = deferreds[ this.defaults.ajax.url ] = {};
280 }
281 deferredGroup[ type + 'Token' ] = d;
282 }
283
284 return d.promise( { abort: d.abort } );
285 }
286 };
287
288 /**
289 * @static
290 * @property {Array}
291 * List of errors we might receive from the API.
292 * For now, this just documents our expectation that there should be similar messages
293 * available.
294 */
295 mw.Api.errors = [
296 // occurs when POST aborted
297 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
298 'ok-but-empty',
299
300 // timeout
301 'timeout',
302
303 // really a warning, but we treat it like an error
304 'duplicate',
305 'duplicate-archive',
306
307 // upload succeeded, but no image info.
308 // this is probably impossible, but might as well check for it
309 'noimageinfo',
310 // remote errors, defined in API
311 'uploaddisabled',
312 'nomodule',
313 'mustbeposted',
314 'badaccess-groups',
315 'stashfailed',
316 'missingresult',
317 'missingparam',
318 'invalid-file-key',
319 'copyuploaddisabled',
320 'mustbeloggedin',
321 'empty-file',
322 'file-too-large',
323 'filetype-missing',
324 'filetype-banned',
325 'filetype-banned-type',
326 'filename-tooshort',
327 'illegal-filename',
328 'verification-error',
329 'hookaborted',
330 'unknown-error',
331 'internal-error',
332 'overwrite',
333 'badtoken',
334 'fetchfileerror',
335 'fileexists-shared-forbidden',
336 'invalidtitle',
337 'notloggedin'
338 ];
339
340 /**
341 * @static
342 * @property {Array}
343 * List of warnings we might receive from the API.
344 * For now, this just documents our expectation that there should be similar messages
345 * available.
346 */
347 mw.Api.warnings = [
348 'duplicate',
349 'exists'
350 ];
351
352 }( mediaWiki, jQuery ) );