All files / mobile.editor.overlay EditorGateway.js

92.04% Statements 81/88
83.33% Branches 50/60
93.75% Functions 15/16
91.95% Lines 80/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3001x 1x 1x                                       26x 26x 26x 26x 26x 26x 26x 26x 26x 26x                       17x       1x 1x 1x 1x         1x 1x       16x                       18x           18x 1x   17x                             17x       17x 14x   17x 17x 1x     16x   16x 1x       1x     15x 15x 15x       16x 16x 16x 16x   16x                         14x 13x   1x   14x                                   14x   14x             14x 14x                           14x 14x     14x 12x                 14x 12x 5x 5x     7x     2x   14x     14x                 3x                           3x 3x   3x                               3x       3x 3x 3x     3x 3x   3x       1x 1x   1x 1x     3x                               1x  
const mobile = require( 'mobile.startup' );
const util = mobile.util;
const actionParams = mobile.actionParams;
 
/**
 * API that helps save and retrieve page content
 *
 * @private
 */
class EditorGateway {
	/**
	 * @param {Object} options Configuration options
	 * @param {mw.Api} options.api an Api to use.
	 * @param {string} options.title the title to edit
	 * @param {string|null} options.sectionId the id of the section to operate edits on.
	 * @param {number} [options.oldId] revision to operate on. If absent defaults to latest.
	 * @param {boolean} [options.fromModified] whether the page was loaded in a modified state
	 * @param {string} [options.preload] the name of a page to preload into the editor
	 * @param {Array} [options.preloadparams] parameters to prefill into the preload content
	 * @param {string} [options.editintro] edit intro to add to notices
	 */
	constructor( options ) {
		this.api = options.api;
		this.title = options.title;
		this.sectionId = options.sectionId;
		this.oldId = options.oldId;
		this.preload = options.preload;
		this.preloadparams = options.preloadparams;
		this.editintro = options.editintro;
		this.content = undefined;
		this.fromModified = options.fromModified;
		this.hasChanged = options.fromModified;
	}
 
	/**
	 * Get the block (if there is one) from the result.
	 *
	 * @param {Object} pageObj Page object
	 * @return {Object|null}
	 */
	getBlockInfo( pageObj ) {
		let blockedError;
 
		if ( pageObj.actions &&
			pageObj.actions.edit &&
			Array.isArray( pageObj.actions.edit )
		) {
			pageObj.actions.edit.some( ( error ) => {
				Eif ( [ 'blocked', 'autoblocked' ].indexOf( error.code ) !== -1 ) {
					blockedError = error;
					return true;
				}
				return false;
			} );
 
			Eif ( blockedError && blockedError.data && blockedError.data.blockinfo ) {
				return blockedError.data.blockinfo;
			}
		}
 
		return null;
	}
 
	/**
	 * Get the content of a page.
	 *
	 * @instance
	 * @return {jQuery.Promise}
	 */
	getContent() {
		let options;
 
		const resolve = () => util.Deferred().resolve( {
			text: this.content || '',
			blockinfo: this.blockinfo,
			notices: this.notices
		} );
 
		if ( this.content !== undefined ) {
			return resolve();
		} else {
			options = actionParams( {
				prop: [ 'revisions', 'info' ],
				rvprop: [ 'content', 'timestamp' ],
				inprop: [ 'preloadcontent', 'editintro' ],
				inpreloadcustom: this.preload,
				inpreloadparams: this.preloadparams,
				ineditintrocustom: this.editintro,
				titles: this.title,
				// get block information for this user
				intestactions: 'edit',
				// …and test whether this edit will auto-create an account
				intestactionsautocreate: true,
				intestactionsdetail: 'full'
			} );
			// Load text of old revision if desired
			Iif ( this.oldId ) {
				options.rvstartid = this.oldId;
			}
			// See T52136 - passing rvsection will fail with non wikitext
			if ( this.sectionId ) {
				options.rvsection = this.sectionId;
			}
			return this.api.get( options ).then( ( resp ) => {
				if ( resp.error ) {
					return util.Deferred().reject( resp.error.code );
				}
 
				const pageObj = resp.query.pages[0];
				// page might not exist and caller might not have known.
				if ( pageObj.missing !== undefined ) {
					Iif ( pageObj.preloadcontent ) {
						this.content = pageObj.preloadcontent.content;
						this.hasChanged = !pageObj.preloadisdefault;
					} else {
						this.content = '';
					}
				} else {
					const revision = pageObj.revisions[0];
					this.content = revision.content;
					this.timestamp = revision.timestamp;
				}
 
				// save content a second time to be able to check for changes
				this.originalContent = this.content;
				this.blockinfo = this.getBlockInfo( pageObj );
				this.wouldautocreate = pageObj.wouldautocreate && pageObj.wouldautocreate.edit;
				this.notices = pageObj.editintro;
 
				return resolve();
			} );
		}
	}
 
	/**
	 * Mark content as modified and set changes to be submitted when #save
	 * is invoked.
	 *
	 * @instance
	 * @param {string} content New section content.
	 */
	setContent( content ) {
		if ( this.originalContent !== content || this.fromModified ) {
			this.hasChanged = true;
		} else {
			this.hasChanged = false;
		}
		this.content = content;
	}
 
	/**
	 * Save the new content of the section, previously set using #setContent.
	 *
	 * @instance
	 * @param {Object} options Configuration options
	 * @param {string} [options.summary] Optional summary for the edit.
	 * @param {string} [options.captchaId] If CAPTCHA was requested, ID of the
	 * captcha.
	 * @param {string} [options.captchaWord] If CAPTCHA was requested, term
	 * displayed in the CAPTCHA.
	 * @return {jQuery.Deferred} On failure callback is passed an object with
	 * `type` and `details` properties. `type` is a string describing the type
	 * of error, `details` can be any object (usually error message).
	 */
	save( options ) {
		const result = util.Deferred();
 
		options = options || {};
 
		/**
		 * Save content. Make an API request.
		 *
		 * @return {jQuery.Deferred}
		 */
		const saveContent = () => {
			const apiOptions = {
				action: 'edit',
				errorformat: 'html',
				errorlang: mw.config.get( 'wgUserLanguage' ),
				errorsuselocal: 1,
				formatversion: 2,
				title: this.title,
				summary: options.summary,
				captchaid: options.captchaId,
				captchaword: options.captchaWord,
				basetimestamp: this.timestamp,
				starttimestamp: this.timestamp
			};
 
			Eif ( this.content !== undefined ) {
				apiOptions.text = this.content;
			}
 
			if ( this.sectionId ) {
				apiOptions.section = this.sectionId;
			}
 
			// TODO: When `wouldautocreate` is true, we should also set up:
			// - apiOptions.returntofragment to be the URL fragment to link to the section
			//   (but we don't know what it is; `sectionId` here is the number)
			// - apiOptions.returntoquery to be 'redirect=no' if we're saving a redirect
			//   (but we have can't figure that out, unless we parse the wikitext)
 
			this.api.postWithToken( 'csrf', apiOptions ).then( ( data ) => {
				if ( data && data.edit && data.edit.result === 'Success' ) {
					this.hasChanged = false;
					result.resolve( data.edit.newrevid, data.edit.tempusercreatedredirect,
						data.edit.tempusercreated );
				} else {
					result.reject( data );
				}
			}, ( code, data ) => {
				result.reject( data );
			} );
			return result;
		};
 
		return saveContent();
	}
 
	/**
	 * Abort any pending previews.
	 *
	 * @instance
	 */
	abortPreview() {
		Iif ( this._pending ) {
			this._pending.abort();
		}
	}
 
	/**
	 * Get page preview from the API and abort any existing previews.
	 *
	 * @instance
	 * @param {Object} options API query parameters
	 * @return {jQuery.Deferred}
	 */
	getPreview( options ) {
		let
			sectionLine = '',
			sectionId = '';
 
		util.extend( options, {
			action: 'parse',
			// Enable section preview mode to avoid errors (T51218)
			sectionpreview: true,
			// Hide section edit links
			disableeditsection: true,
			// needed for pre-save transform to work (T55692)
			pst: true,
			// Output mobile HTML (T56243)
			mobileformat: true,
			useskin: mw.config.get( 'skin' ),
			disabletoc: true,
			title: this.title,
			prop: [ 'text', 'sections' ]
		} );
 
		this.abortPreview();
		// Acquire a temporary user username before previewing, so that signatures and
		// user-related magic words display the temp user instead of IP user in the
		// preview. (T331397)
		const promise = mw.user.acquireTempUserName().then( () => {
			this._pending = this.api.post( options );
			return this._pending;
		} );
 
		return promise.then( ( resp ) => {
			Eif ( resp && resp.parse && resp.parse.text ) {
				// When editing section 0 or the whole page, there is no section name, so skip
				if ( this.sectionId && this.sectionId !== '0' &&
					resp.parse.sections !== undefined &&
					resp.parse.sections[0] !== undefined
				) {
					Eif ( resp.parse.sections[0].anchor !== undefined ) {
						sectionId = resp.parse.sections[0].anchor;
					}
					Eif ( resp.parse.sections[0].line !== undefined ) {
						sectionLine = resp.parse.sections[0].line;
					}
				}
				return {
					text: resp.parse.text['*'],
					id: sectionId,
					line: sectionLine
				};
			} else {
				return util.Deferred().reject();
			}
		} ).promise( {
			abort: () => {
				this._pending.abort();
			}
		} );
	}
}
 
module.exports = EditorGateway;