summaryrefslogtreecommitdiff
path: root/www/wiki/resources/src/mediawiki.widgets/MediaSearch/mw.widgets.MediaResourceProvider.js
blob: d767109c2dd09a49bee1e697eed8ba505c4d5361 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*!
 * MediaWiki Widgets - MediaResourceProvider class.
 *
 * @copyright 2011-2016 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */
( function ( $, mw ) {

	/**
	 * MediaWiki media resource provider.
	 *
	 * @class
	 * @extends mw.widgets.APIResultsProvider
	 *
	 * @constructor
	 * @param {string} apiurl The API url
	 * @param {Object} [config] Configuration options
	 * @cfg {string} [scriptDirUrl] The url of the API script
	 */
	mw.widgets.MediaResourceProvider = function MwWidgetsMediaResourceProvider( apiurl, config ) {
		config = config || {};

		// Parent constructor
		mw.widgets.MediaResourceProvider.super.call( this, apiurl, config );

		// Fetching configuration
		this.scriptDirUrl = config.scriptDirUrl;
		this.isLocal = config.local !== undefined;

		if ( this.isLocal ) {
			this.setAPIurl( mw.util.wikiScript( 'api' ) );
		} else {
			// If 'apiurl' is set, use that. Otherwise, build the url
			// from scriptDirUrl and /api.php suffix
			this.setAPIurl( this.getAPIurl() || ( this.scriptDirUrl + '/api.php' ) );
		}

		this.siteInfoPromise = null;
		this.thumbSizes = [];
		this.imageSizes = [];
	};

	/* Inheritance */
	OO.inheritClass( mw.widgets.MediaResourceProvider, mw.widgets.APIResultsProvider );

	/* Methods */

	/**
	 * @inheritdoc
	 */
	mw.widgets.MediaResourceProvider.prototype.getStaticParams = function () {
		return $.extend(
			{},
			// Parent method
			mw.widgets.MediaResourceProvider.super.prototype.getStaticParams.call( this ),
			{
				action: 'query',
				iiprop: 'dimensions|url|mediatype|extmetadata|timestamp|user',
				iiextmetadatalanguage: this.getLang(),
				prop: 'imageinfo'
			}
		);
	};

	/**
	 * Initialize the source and get the site info.
	 *
	 * Connect to the api url and retrieve the siteinfo parameters
	 * that are required for fetching results.
	 *
	 * @return {jQuery.Promise} Promise that resolves when the class
	 * properties are set.
	 */
	mw.widgets.MediaResourceProvider.prototype.loadSiteInfo = function () {
		var provider = this;

		if ( !this.siteInfoPromise ) {
			this.siteInfoPromise = new mw.Api().get( {
				action: 'query',
				meta: 'siteinfo'
			} )
				.then( function ( data ) {
					provider.setImageSizes( data.query.general.imagelimits || [] );
					provider.setThumbSizes( data.query.general.thumblimits || [] );
					provider.setUserParams( {
						// Standard width per resource
						iiurlwidth: provider.getStandardWidth()
					} );
				} );
		}
		return this.siteInfoPromise;
	};

	/**
	 * Override parent method and get results from the source
	 *
	 * @param {number} [howMany] The number of items to pull from the API
	 * @return {jQuery.Promise} Promise that is resolved into an array
	 * of available results, or is rejected if no results are available.
	 */
	mw.widgets.MediaResourceProvider.prototype.getResults = function ( howMany ) {
		var xhr,
			aborted = false,
			provider = this;

		return this.loadSiteInfo()
			.then( function () {
				if ( aborted ) {
					return $.Deferred().reject();
				}
				xhr = provider.fetchAPIresults( howMany );
				return xhr;
			} )
			.then(
				function ( results ) {
					if ( !results || results.length === 0 ) {
						provider.toggleDepleted( true );
						return [];
					}
					return results;
				},
				// Process failed, return an empty promise
				function () {
					provider.toggleDepleted( true );
					return $.Deferred().resolve( [] );
				}
			)
			.promise( { abort: function () {
				aborted = true;
				if ( xhr ) {
					xhr.abort();
				}
			} } );
	};

	/**
	 * Get continuation API data
	 *
	 * @param {number} howMany The number of results to retrieve
	 * @return {Object} API request data
	 */
	mw.widgets.MediaResourceProvider.prototype.getContinueData = function () {
		return {};
	};

	/**
	 * Set continuation data for the next page
	 *
	 * @param {Object} continueData Continuation data
	 */
	mw.widgets.MediaResourceProvider.prototype.setContinue = function () {
	};

	/**
	 * Sort the results
	 *
	 * @param {Object[]} results API results
	 * @return {Object[]} Sorted results
	 */
	mw.widgets.MediaResourceProvider.prototype.sort = function ( results ) {
		return results;
	};

	/**
	 * Call the API for search results.
	 *
	 * @param {number} howMany The number of results to retrieve
	 * @return {jQuery.Promise} Promise that resolves with an array of objects that contain
	 *  the fetched data.
	 */
	mw.widgets.MediaResourceProvider.prototype.fetchAPIresults = function ( howMany ) {
		var xhr, api,
			provider = this;

		if ( !this.isValid() ) {
			return $.Deferred().reject().promise( { abort: $.noop } );
		}

		api = this.isLocal ? new mw.Api() : new mw.ForeignApi( this.getAPIurl(), { anonymous: true } );
		xhr = api.get( $.extend( {}, this.getStaticParams(), this.getUserParams(), this.getContinueData( howMany ) ) );
		return xhr
			.then( function ( data ) {
				var page, newObj, raw,
					results = [];

				if ( data.error ) {
					provider.toggleDepleted( true );
					return [];
				}

				if ( data.continue ) {
					// Update the offset for next time
					provider.setContinue( data.continue );
				} else {
					// This is the last available set of results. Mark as depleted!
					provider.toggleDepleted( true );
				}

				// If the source returned no results, it will not have a
				// query property
				if ( data.query ) {
					raw = data.query.pages;
					if ( raw ) {
						// Strip away the page ids
						for ( page in raw ) {
							if ( !raw[ page ].imageinfo ) {
								// The search may give us pages that belong to the File:
								// namespace but have no files in them, either because
								// they were deleted or imported wrongly, or just started
								// as pages. In that case, the response will not include
								// imageinfo. Skip those files.
								continue;
							}
							newObj = raw[ page ].imageinfo[ 0 ];
							newObj.title = raw[ page ].title;
							newObj.index = raw[ page ].index;
							results.push( newObj );
						}
					}
				}
				return provider.sort( results );
			} )
			.promise( { abort: xhr.abort } );
	};

	/**
	 * Set name
	 *
	 * @param {string} name
	 */
	mw.widgets.MediaResourceProvider.prototype.setName = function ( name ) {
		this.name = name;
	};

	/**
	 * Get name
	 *
	 * @return {string} name
	 */
	mw.widgets.MediaResourceProvider.prototype.getName = function () {
		return this.name;
	};

	/**
	 * Get standard width, based on the provider source's thumb sizes.
	 *
	 * @return {number|undefined} fetchWidth
	 */
	mw.widgets.MediaResourceProvider.prototype.getStandardWidth = function () {
		return ( this.thumbSizes && this.thumbSizes[ this.thumbSizes.length - 1 ] ) ||
			( this.imageSizes && this.imageSizes[ 0 ] ) ||
			// Fall back on a number
			300;
	};

	/**
	 * Get prop
	 *
	 * @return {string} prop
	 */
	mw.widgets.MediaResourceProvider.prototype.getFetchProp = function () {
		return this.fetchProp;
	};

	/**
	 * Set prop
	 *
	 * @param {string} prop
	 */
	mw.widgets.MediaResourceProvider.prototype.setFetchProp = function ( prop ) {
		this.fetchProp = prop;
	};

	/**
	 * Set thumb sizes
	 *
	 * @param {number[]} sizes Available thumbnail sizes
	 */
	mw.widgets.MediaResourceProvider.prototype.setThumbSizes = function ( sizes ) {
		this.thumbSizes = sizes;
	};

	/**
	 * Set image sizes
	 *
	 * @param {number[]} sizes Available image sizes
	 */
	mw.widgets.MediaResourceProvider.prototype.setImageSizes = function ( sizes ) {
		this.imageSizes = sizes;
	};

	/**
	 * Get thumb sizes
	 *
	 * @return {number[]} sizes Available thumbnail sizes
	 */
	mw.widgets.MediaResourceProvider.prototype.getThumbSizes = function () {
		return this.thumbSizes;
	};

	/**
	 * Get image sizes
	 *
	 * @return {number[]} sizes Available image sizes
	 */
	mw.widgets.MediaResourceProvider.prototype.getImageSizes = function () {
		return this.imageSizes;
	};

	/**
	 * Check if this source is valid.
	 *
	 * @return {boolean} Source is valid
	 */
	mw.widgets.MediaResourceProvider.prototype.isValid = function () {
		return this.isLocal ||
			// If we don't have either 'apiurl' or 'scriptDirUrl'
			// the source is invalid, and we will skip it
			this.apiurl !== undefined ||
			this.scriptDirUrl !== undefined;
	};
}( jQuery, mediaWiki ) );