User:Magiczocker/UpdateList.js

From Support Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* Script to update [[Module:Wikis/list.json]] */
mw.loader.using( 'mediawiki.util' ).then( function () {
	function update() {
		Promise.all( [
			fetch( 'https://support.wiki.gg/index.php?title=Module:Wikis/list.json&action=raw&safemode=1&debug=1', {
				method: 'GET'
			} ),
			fetch( 'https://app.wiki.gg/wikis', {
				method: 'GET'
			} )
		] ).then( function ( responses ) {
			return Promise.all( responses.map( function ( response ) {
				return response.json();
			} ) );
		} ).then( function ( data ) {
			var current = data[ 0 ],
				latest = data[ 1 ],
				count = 0,

				// Create list of current wikis
				wikis = current.map( function ( wiki ) {
					return wiki.name;
				} );

			// Add new entries
			latest.forEach( function ( wiki ) {
				if ( !wikis.includes( wiki.wiki_id ) ) {
					current.push( {
						name: wiki.wiki_id,
						lang: [ 'en' ],
						origin: '*'
					} );
					count++;
				}
			} );

			// Sort list alphabetically
			current.sort( function ( a, b ) {
				var textA = a.name.toUpperCase(),
					textB = b.name.toUpperCase();
				return ( textA < textB ) ? -1 : ( textA > textB ) ? 1 : 0;
			} );

			// Log output
			fetch( mw.config.get( 'wgScriptPath' ) + '/api.php', {
				body: new URLSearchParams( {
					action: 'edit',
					title: 'Module:Wikis/list.json',
					summary: 'Update list (automatic)',
					text: JSON.stringify( current ),
					format: 'json',
					token: mw.user.tokens.get( 'csrfToken' )
				} ),
				method: 'POST',
				credentials: 'include'
			} );

			alert( 'Added ' + count + ' new wikis.' );
		} ).catch( function ( err ) {
			console.error( '[UpdateList]', err );
		} );
	}
	if ( mw.config.get( 'wgPageName' ) === 'Module:Wikis/list.json' ) {
		mw.util.addPortletLink(
			'p-views',
			'#',
			'Update list',
			'ca-update',
			'Update list of wikis'
		).children[ 0 ].addEventListener( 'click', function ( event ) {
			event.preventDefault();
			if ( confirm( 'Update list?' ) ) {
				update();
			}
		} );
	}
} );