<commit_before>/** @module deliteful/SidePane */
define([
	"dcl/dcl",
	"dpointer/events",
	"dojo/dom-class",
	"dojo/sniff",
	"delite/register",
	"delite/DisplayContainer",
	"dojo/Deferred",
	"delite/theme!./SidePane/themes/{{theme}}/SidePane_css",
	"requirejs-dplugins/has!bidi?delite/theme!./SidePane/themes/{{theme}}/SidePane_rtl_css"
],
	function (dcl, pointer, domClass, has, register, DisplayContainer, Deferred) {
		function prefix(v) {
			return "-d-side-pane-" + v;
		}
		function setVisibility(node, val) {
			if (val) {
				node.style.visibility = "visible";
				node.style.display = "";
			} else {
				node.style.visibility = "hidden";
				node.style.display = "none";
			}
		}
		function getNextSibling(node) {
			do {
				node = node.nextElementSibling;
			} while (node && node.nodeType !== 1);
			return node;
		}
		/**
		 * A widget displayed on the side of the screen.
		 *
		 * It can be displayed on top of the page
		 * (mode=overlay) or can push the content of the page (mode=push or mode=reveal).
		 * SidePane is a widget hidden by default.
		 * This widget must be a sibling of html's body element.
		 * If mode is set to "push" or "reveal", the width of the SidePane can't be changed in the markup
		 * (15em by default).
		 * However it can be changed in SidePane.less (@PANE_WIDTH variable).
		 * In "push" and "reveal" mode, the pushed element is the first sibling of the SidePane which has
		 * of type element (nodeType == 1) and not a SidePane.
		 * @example
		 *
		 *   <d-side-pane>
		 *       SidePane content
		 *   </d-side-pane>
		 *

		 *       Main application
		 *

		 *
		 * @class module:deliteful/SidePane
		 * @augments module:delite/DisplayContainer
		 */
		return register("d-side-pane", [HTMLElement, DisplayContainer],
			/** @lends module:deliteful/SidePane#*/ {
			/**
			 * The name of the CSS class of this widget.
			 * @member {string}
			 * @default "d-side-pane"
			 */
			baseClass: "d-side-pane",

			/**
			 * Can be "overlay", "reveal" or "push".
			 * In overlay mode, the pane is shown on top of the page.
			 * In reveal and push modes, The page is moved to make the pane visible. The difference between
			 * these two modes is the animated transition: in reveal mode, the pane does not move, it is
			 * already under the page. In push mode, the pane slide with the page.
			 * @member {string}
			 * @default "push"
			 */
			mode: "push",

			/**
			 * Can be "start" or "end". If set to "start", the panel is displayed on the
			 * left side in LTR mode.
			 * @member {string}
			 * @default "push"
			 */
			position: "start",

			/**
			 * Enable/Disable animations.
			 * @member {boolean}
			 * @default true
			 */
			animate: true,

			/**
			 * Enables the swipe closing of the pane.
			 * @member {boolean}
			 * @default true
			 */
			swipeClosing: true,

			_transitionTiming: {default: 0, chrome: 50, ios: 20, android: 100, mozilla: 100},
			_timing: 0,
			_visible: false,
			_opening: false,
			_originX: NaN,
			_originY: NaN,

			show: dcl.superCall(function (sup) {
				return function () {
					if (arguments.length > 0) {
						return sup.apply(this, arguments).then(function (value) {
							return this._open().then(function () {
								return value;
							});
						}.bind(this));
					} else {
						return this._open();
					}
				};
			}),

			hide: dcl.superCall(function (sup) {
				return function () {
					if (arguments.length > 0) {
						return sup.apply(this, arguments).then(function (value) {
							return this._close().then(function () {
								return value;
							});
						}.bind(this));
					} else {
						return this._close();
					}
				};
			}),

			/**
			 * Open the pane.
			 * @private
			 */
			_open: function () {
				var deferred = new Deferred();
				var nextElement = getNextSibling(this);
				if (!this._visible) {
					if (this.animate) {
						domClass.add(this, prefix("animate"));
						if (nextElement) {
							domClass.add(nextElement, prefix("animate"));
						}
					}

					if (this.mode === "reveal") {
						if (nextElement) {
							this._setAfterTransitionHandlers(nextElement, {node: nextElement}, deferred);
						}
					} else {
						this._setAfterTransitionHandlers(this, {node: this}, deferred);
					}

					setVisibility(this, true);

					if (this.animate) {
						this.defer(this._openImpl, this._timing);
					} else {
						this._openImpl();
						this.defer(function () {deferred.resolve(); }, this._timing);
					}
				} else {
					deferred.resolve();
				}
				return deferred.promise;
			},

			/**
			 * Close the pane.
			 * @private
			 */
			_close: function () {
				var deferred = new Deferred();
				if (this._visible) {
					if (this.mode === "reveal") {
						var nextElement = getNextSibling(this);
						if (nextElement) {
							this._setAfterTransitionHandlers(nextElement, {node: nextElement});
						}
					} else {
						this._setAfterTransitionHandlers(this, {node: this}, deferred);
					}
					this._hideImpl();
					if (!this.animate) {
						this.defer(function () {setVisibility(this, false); deferred.resolve(); }.bind(this),
							this._timing);
					}
				} else {
					deferred.resolve();
				}
				return deferred.promise;
			},

			_setAfterTransitionHandlers: function (node, event, deferred) {
				var self = this, endProps = {
					node: node,
					handle: function () { self._afterTransitionHandle(endProps); },
					props: event,
					deferred: deferred
				};
				node.addEventListener("webkitTransitionEnd", endProps.handle);
				node.addEventListener("transitionend", endProps.handle); // IE10 + FF
			},

			_afterTransitionHandle: function (item) {
				domClass.remove(this, prefix("under"));
				if (!this._visible) {
					setVisibility(this, false);
				}
				item.node.removeEventListener("webkitTransitionEnd", item.handle);
				item.node.removeEventListener("transitionend", item.handle);
				item.deferred.resolve();
			},

			postCreate: function () {
				setVisibility(this, false);

				// trigger refreshRendering() to run and apply mode & position even if they are the default values
				this.notifyCurrentValue("mode");
				this.notifyCurrentValue("position");
			},

			preCreate: function () {
				this._transitionTiming = {default: 0, chrome: 20, ios: 20, android: 100, mozilla: 100};
				for (var o in this._transitionTiming) {
					if (has(o) && this._timing < this._transitionTiming[o]) {
						this._timing = this._transitionTiming[o];
					}
				}
			},

			buildRendering: function () {
				this.parentNode.style.overflow = "hidden";
				pointer.setTouchAction(this, "none");
				this._resetInteractions();
			},

			refreshRendering: function (props) {
				var nextElement = getNextSibling(this);

				// Always remove animation during a refresh. Avoid to see moving the pane on mode changes.
				// Not very reliable on IE11.
				domClass.remove(this, prefix("animate"));
				if (nextElement) {
					domClass.remove(nextElement, prefix("animate"));
					if (!this.isLeftToRight()) {
						domClass.add(nextElement, "d-rtl");
					}
					else {
						domClass.remove(nextElement, "d-rtl");
					}
				}

				if ("mode" in props) {
					domClass.remove(this, [prefix("push"), prefix("overlay"), prefix("reveal")]);
					domClass.add(this, prefix(this.mode));

					if (nextElement && this._visible) {
						domClass.toggle(nextElement, prefix("translated"), this.mode !== "overlay");
					}

					if (this.mode === "reveal" && !this._visible) {
						// Needed by FF only for the first opening.
						domClass.remove(this, prefix("ontop"));
						domClass.add(this, prefix("under"));
					}
					else if (this.mode === "overlay") {
						domClass.remove(this, prefix("under"));
						domClass.add(this, prefix("ontop"));
					} else {
						domClass.remove(this, [prefix("under"), prefix("ontop")]);
					}

				}

				if ("position" in props) {
					domClass.remove(this, [prefix("start"), prefix("end")]);
					domClass.add(this, prefix(this.position));
					if (nextElement && this._visible) {
						domClass.remove(nextElement, [prefix("start"), prefix("end")]);
						domClass.add(nextElement, prefix(this.position));
					}
				}

				domClass.toggle(this, prefix("hidden"), !this._visible);
				domClass.toggle(this, prefix("visible"), this._visible);

				// Re-enable animation
				if (this.animate) {
					this.defer(function () {
						domClass.add(this, prefix("animate"));
						if (nextElement) {
							domClass.add(nextElement, prefix("animate"));
						}
					}, this._timing);
				}
			},

			_openImpl: function () {
				if (!this._visible) {
					this._visible = true;
					domClass.remove(this, prefix("hidden"));
					domClass.add(this, prefix("visible"));

					if (this.mode === "push" || this.mode === "reveal") {
						var nextElement = getNextSibling(this);
						if (nextElement) {
							domClass.remove(nextElement, [prefix("nottranslated"), prefix("start"), prefix("end")]);
							domClass.add(nextElement, [prefix(this.position), prefix("translated")]);
						}
					}
				}
			},

			_hideImpl: function () {
				if (this._visible) {
					this._visible = false;
					this._opening = false;
					domClass.remove(this.ownerDocument.body, prefix("no-select"));
					domClass.remove(this, prefix("visible"));
					domClass.add(this, prefix("hidden"));
					if (this.mode === "push" || this.mode === "reveal") {
						var nextElement = getNextSibling(this);
						if (nextElement) {
							domClass.remove(nextElement, [prefix("translated"), prefix("start"), prefix("end")]);
							domClass.add(nextElement, [prefix(this.position), prefix("nottranslated")]);
						}
					}
				}
			},

			_isLeft: function () {
				return (this.position === "start" && this.isLeftToRight()) ||
					(this.position === "end" && !this.isLeftToRight());
			},

			_pointerDownHandler: function (event) {
				this._originX = event.pageX;
				this._originY = event.pageY;

				if (this._visible || (this._isLeft() && !this._visible && this._originX <= 10) ||
					(!this._isLeft() && !this._visible && this._originX >= this.ownerDocument.width - 10)) {
					this._opening = !this._visible;
					this._pressHandle.remove();
					this._moveHandle = this.on("pointermove", this._pointerMoveHandler.bind(this));
					this._releaseHandle = this.on("pointerup", this._pointerUpHandler.bind(this));

					domClass.add(this.ownerDocument.body, prefix("no-select"));
				}
			},

			_pointerMoveHandler: function (event) {
				if (!this._opening && Math.abs(event.pageY - this._originY) > 10) {
					this._resetInteractions();
				} else {
					var pos = event.pageX;

					if (this._isLeft()) {
						if (this._visible) {
							if (this._originX < pos) {
								this._originX = pos;
							}

							if ((this.swipeClosing && this._originX - pos) > 10) {
								this.close();
								this._originX = pos;
							}
						}
					} else {
						if (this._visible) {
							if (this._originX > pos) {
								this._originX = pos;
							}
							if ((this.swipeClosing && pos - this._originX) > 10) {
								this.close();
								this._originX = pos;
							}
						}
					}
				}
			},

			_pointerUpHandler: function () {
				this._opening = false;
				domClass.remove(this.ownerDocument.body, prefix("no-select"));
				this._resetInteractions();
			},

			_resetInteractions: function () {
				if (this._releaseHandle) {
					this._releaseHandle.remove();
				}
				if (this._moveHandle) {
					this._moveHandle.remove();
				}
				if (this._pressHandle) {
					this._pressHandle.remove();
				}

				if (this.swipeClosing) {
					this._pressHandle = this.on("pointerdown", this._pointerDownHandler.bind(this));
				}

				this._originX = NaN;
				this._originY = NaN;
			}
		});
	});
<commit_msg>fix swipeClosing support (this.close() -> this._close())<commit_after>/** @module deliteful/SidePane */
define([
	"dcl/dcl",
	"dpointer/events",
	"dojo/dom-class",
	"dojo/sniff",
	"delite/register",
	"delite/DisplayContainer",
	"dojo/Deferred",
	"delite/theme!./SidePane/themes/{{theme}}/SidePane_css",
	"requirejs-dplugins/has!bidi?delite/theme!./SidePane/themes/{{theme}}/SidePane_rtl_css"
],
	function (dcl, pointer, domClass, has, register, DisplayContainer, Deferred) {
		function prefix(v) {
			return "-d-side-pane-" + v;
		}
		function setVisibility(node, val) {
			if (val) {
				node.style.visibility = "visible";
				node.style.display = "";
			} else {
				node.style.visibility = "hidden";
				node.style.display = "none";
			}
		}
		function getNextSibling(node) {
			do {
				node = node.nextElementSibling;
			} while (node && node.nodeType !== 1);
			return node;
		}
		/**
		 * A widget displayed on the side of the screen.
		 *
		 * It can be displayed on top of the page
		 * (mode=overlay) or can push the content of the page (mode=push or mode=reveal).
		 * SidePane is a widget hidden by default.
		 * This widget must be a sibling of html's body element.
		 * If mode is set to "push" or "reveal", the width of the SidePane can't be changed in the markup
		 * (15em by default).
		 * However it can be changed in SidePane.less (@PANE_WIDTH variable).
		 * In "push" and "reveal" mode, the pushed element is the first sibling of the SidePane which has
		 * of type element (nodeType == 1) and not a SidePane.
		 * @example
		 *
		 *   <d-side-pane>
		 *       SidePane content
		 *   </d-side-pane>
		 *

		 *       Main application
		 *

		 *
		 * @class module:deliteful/SidePane
		 * @augments module:delite/DisplayContainer
		 */
		return register("d-side-pane", [HTMLElement, DisplayContainer],
			/** @lends module:deliteful/SidePane#*/ {
			/**
			 * The name of the CSS class of this widget.
			 * @member {string}
			 * @default "d-side-pane"
			 */
			baseClass: "d-side-pane",

			/**
			 * Can be "overlay", "reveal" or "push".
			 * In overlay mode, the pane is shown on top of the page.
			 * In reveal and push modes, The page is moved to make the pane visible. The difference between
			 * these two modes is the animated transition: in reveal mode, the pane does not move, it is
			 * already under the page. In push mode, the pane slide with the page.
			 * @member {string}
			 * @default "push"
			 */
			mode: "push",

			/**
			 * Can be "start" or "end". If set to "start", the panel is displayed on the
			 * left side in LTR mode.
			 * @member {string}
			 * @default "push"
			 */
			position: "start",

			/**
			 * Enable/Disable animations.
			 * @member {boolean}
			 * @default true
			 */
			animate: true,

			/**
			 * Enables the swipe closing of the pane.
			 * @member {boolean}
			 * @default true
			 */
			swipeClosing: true,

			_transitionTiming: {default: 0, chrome: 50, ios: 20, android: 100, mozilla: 100},
			_timing: 0,
			_visible: false,
			_opening: false,
			_originX: NaN,
			_originY: NaN,

			show: dcl.superCall(function (sup) {
				return function () {
					if (arguments.length > 0) {
						return sup.apply(this, arguments).then(function (value) {
							return this._open().then(function () {
								return value;
							});
						}.bind(this));
					} else {
						return this._open();
					}
				};
			}),

			hide: dcl.superCall(function (sup) {
				return function () {
					if (arguments.length > 0) {
						return sup.apply(this, arguments).then(function (value) {
							return this._close().then(function () {
								return value;
							});
						}.bind(this));
					} else {
						return this._close();
					}
				};
			}),

			/**
			 * Open the pane.
			 * @private
			 */
			_open: function () {
				var deferred = new Deferred();
				var nextElement = getNextSibling(this);
				if (!this._visible) {
					if (this.animate) {
						domClass.add(this, prefix("animate"));
						if (nextElement) {
							domClass.add(nextElement, prefix("animate"));
						}
					}

					if (this.mode === "reveal") {
						if (nextElement) {
							this._setAfterTransitionHandlers(nextElement, {node: nextElement}, deferred);
						}
					} else {
						this._setAfterTransitionHandlers(this, {node: this}, deferred);
					}

					setVisibility(this, true);

					if (this.animate) {
						this.defer(this._openImpl, this._timing);
					} else {
						this._openImpl();
						this.defer(function () {deferred.resolve(); }, this._timing);
					}
				} else {
					deferred.resolve();
				}
				return deferred.promise;
			},

			/**
			 * Close the pane.
			 * @private
			 */
			_close: function () {
				var deferred = new Deferred();
				if (this._visible) {
					if (this.mode === "reveal") {
						var nextElement = getNextSibling(this);
						if (nextElement) {
							this._setAfterTransitionHandlers(nextElement, {node: nextElement});
						}
					} else {
						this._setAfterTransitionHandlers(this, {node: this}, deferred);
					}
					this._hideImpl();
					if (!this.animate) {
						this.defer(function () {setVisibility(this, false); deferred.resolve(); }.bind(this),
							this._timing);
					}
				} else {
					deferred.resolve();
				}
				return deferred.promise;
			},

			_setAfterTransitionHandlers: function (node, event, deferred) {
				var self = this, endProps = {
					node: node,
					handle: function () { self._afterTransitionHandle(endProps); },
					props: event,
					deferred: deferred
				};
				node.addEventListener("webkitTransitionEnd", endProps.handle);
				node.addEventListener("transitionend", endProps.handle); // IE10 + FF
			},

			_afterTransitionHandle: function (item) {
				domClass.remove(this, prefix("under"));
				if (!this._visible) {
					setVisibility(this, false);
				}
				item.node.removeEventListener("webkitTransitionEnd", item.handle);
				item.node.removeEventListener("transitionend", item.handle);
				item.deferred.resolve();
			},

			postCreate: function () {
				setVisibility(this, false);

				// trigger refreshRendering() to run and apply mode & position even if they are the default values
				this.notifyCurrentValue("mode");
				this.notifyCurrentValue("position");
			},

			preCreate: function () {
				this._transitionTiming = {default: 0, chrome: 20, ios: 20, android: 100, mozilla: 100};
				for (var o in this._transitionTiming) {
					if (has(o) && this._timing < this._transitionTiming[o]) {
						this._timing = this._transitionTiming[o];
					}
				}
			},

			buildRendering: function () {
				this.parentNode.style.overflow = "hidden";
				pointer.setTouchAction(this, "none");
				this._resetInteractions();
			},

			refreshRendering: function (props) {
				var nextElement = getNextSibling(this);

				// Always remove animation during a refresh. Avoid to see moving the pane on mode changes.
				// Not very reliable on IE11.
				domClass.remove(this, prefix("animate"));
				if (nextElement) {
					domClass.remove(nextElement, prefix("animate"));
					if (!this.isLeftToRight()) {
						domClass.add(nextElement, "d-rtl");
					}
					else {
						domClass.remove(nextElement, "d-rtl");
					}
				}

				if ("mode" in props) {
					domClass.remove(this, [prefix("push"), prefix("overlay"), prefix("reveal")]);
					domClass.add(this, prefix(this.mode));

					if (nextElement && this._visible) {
						domClass.toggle(nextElement, prefix("translated"), this.mode !== "overlay");
					}

					if (this.mode === "reveal" && !this._visible) {
						// Needed by FF only for the first opening.
						domClass.remove(this, prefix("ontop"));
						domClass.add(this, prefix("under"));
					}
					else if (this.mode === "overlay") {
						domClass.remove(this, prefix("under"));
						domClass.add(this, prefix("ontop"));
					} else {
						domClass.remove(this, [prefix("under"), prefix("ontop")]);
					}

				}

				if ("position" in props) {
					domClass.remove(this, [prefix("start"), prefix("end")]);
					domClass.add(this, prefix(this.position));
					if (nextElement && this._visible) {
						domClass.remove(nextElement, [prefix("start"), prefix("end")]);
						domClass.add(nextElement, prefix(this.position));
					}
				}

				domClass.toggle(this, prefix("hidden"), !this._visible);
				domClass.toggle(this, prefix("visible"), this._visible);

				// Re-enable animation
				if (this.animate) {
					this.defer(function () {
						domClass.add(this, prefix("animate"));
						if (nextElement) {
							domClass.add(nextElement, prefix("animate"));
						}
					}, this._timing);
				}
			},

			_openImpl: function () {
				if (!this._visible) {
					this._visible = true;
					domClass.remove(this, prefix("hidden"));
					domClass.add(this, prefix("visible"));

					if (this.mode === "push" || this.mode === "reveal") {
						var nextElement = getNextSibling(this);
						if (nextElement) {
							domClass.remove(nextElement, [prefix("nottranslated"), prefix("start"), prefix("end")]);
							domClass.add(nextElement, [prefix(this.position), prefix("translated")]);
						}
					}
				}
			},

			_hideImpl: function () {
				if (this._visible) {
					this._visible = false;
					this._opening = false;
					domClass.remove(this.ownerDocument.body, prefix("no-select"));
					domClass.remove(this, prefix("visible"));
					domClass.add(this, prefix("hidden"));
					if (this.mode === "push" || this.mode === "reveal") {
						var nextElement = getNextSibling(this);
						if (nextElement) {
							domClass.remove(nextElement, [prefix("translated"), prefix("start"), prefix("end")]);
							domClass.add(nextElement, [prefix(this.position), prefix("nottranslated")]);
						}
					}
				}
			},

			_isLeft: function () {
				return (this.position === "start" && this.isLeftToRight()) ||
					(this.position === "end" && !this.isLeftToRight());
			},

			_pointerDownHandler: function (event) {
				this._originX = event.pageX;
				this._originY = event.pageY;

				if (this._visible || (this._isLeft() && !this._visible && this._originX <= 10) ||
					(!this._isLeft() && !this._visible && this._originX >= this.ownerDocument.width - 10)) {
					this._opening = !this._visible;
					this._pressHandle.remove();
					this._moveHandle = this.on("pointermove", this._pointerMoveHandler.bind(this));
					this._releaseHandle = this.on("pointerup", this._pointerUpHandler.bind(this));

					domClass.add(this.ownerDocument.body, prefix("no-select"));
				}
			},

			_pointerMoveHandler: function (event) {
				if (!this._opening && Math.abs(event.pageY - this._originY) > 10) {
					this._resetInteractions();
				} else {
					var pos = event.pageX;

					if (this._isLeft()) {
						if (this._visible) {
							if (this._originX < pos) {
								this._originX = pos;
							}

							if ((this.swipeClosing && this._originX - pos) > 10) {
								this._close();
								this._originX = pos;
							}
						}
					} else {
						if (this._visible) {
							if (this._originX > pos) {
								this._originX = pos;
							}
							if ((this.swipeClosing && pos - this._originX) > 10) {
								this._close();
								this._originX = pos;
							}
						}
					}
				}
			},

			_pointerUpHandler: function () {
				this._opening = false;
				domClass.remove(this.ownerDocument.body, prefix("no-select"));
				this._resetInteractions();
			},

			_resetInteractions: function () {
				if (this._releaseHandle) {
					this._releaseHandle.remove();
				}
				if (this._moveHandle) {
					this._moveHandle.remove();
				}
				if (this._pressHandle) {
					this._pressHandle.remove();
				}

				if (this.swipeClosing) {
					this._pressHandle = this.on("pointerdown", this._pointerDownHandler.bind(this));
				}

				this._originX = NaN;
				this._originY = NaN;
			}
		});
	});
<|endoftext|>


<commit_before>var iconv = require('iconv-lite');
var net = require('net');
var util = require('./index');
var logger = require('./logger');
var config = require('../config');
var SafeBuffer = require('safe-buffer');

if (!(config.reqCacheSize > 0) || config.reqCacheSize < 600) {
  config.reqCacheSize = 600;
}

if (!(config.frameCacheSize > 0) || config.frameCacheSize < 512) {
  config.frameCacheSize = 512;
}

var TIMEOUT = 36000;
var CLEAR_INTERVAL = 5000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var MAX_LENGTH = config.reqCacheSize;
var OVERFLOW_LENGTH = MAX_LENGTH * 5;
var MIN_LENGTH = MAX_LENGTH - 100;
var MAX_FRAMES_LENGTH = config.frameCacheSize;
var COUNT = 100;
var count = 0;
var ids = [];
var reqData = {};
var frames = [];
var proxy, binded, timeout, interval;

function disable() {
  proxy.removeListener('request', handleRequest);
  proxy.removeListener('frame', handleFrame);
  ids = [];
  reqData = {};
  frames = [];
  interval && clearInterval(interval);
  interval = null;
  binded = false;
}

function enable() {
  if (!binded) {
    binded = true;
    proxy.on('request', handleRequest);
    proxy.on('frame', handleFrame);
  }
  clearTimeout(timeout);
  timeout = setTimeout(disable, TIMEOUT);
  if (!interval) {
    interval = setInterval(clearCache, CLEAR_INTERVAL);
  }
}

/**
* 如果超过最大缓存数，清理如下请求数据：
* 1. 已经请求结束且结束时间超过10秒
* 2. 请求#1前面的未结束且未被ui读取过的请求
*/
function clearCache() {
  if (frames.length > MAX_FRAMES_LENGTH) {
    frames.splice(0, 100);
  }
  var len = ids.length;
  if (len <= MAX_LENGTH) {
    return;
  }

  var now = Date.now();
  var _ids = [];
  var overflow = len - OVERFLOW_LENGTH;
  if (overflow >= 0) {
    overflow = overflow + MAX_LENGTH * 2;
  }
  for (var i = 0; i < len; i++) {
    var id = ids[i];
    var curData = reqData[id];
    if (i > overflow &&
      (curData.endTime ? now - curData.endTime < CACHE_TIME : now - curData.startTime < TIMEOUT)) {
      _ids.push(id);
    } else {
      delete reqData[id];
      if (--len <= MIN_LENGTH) {
        ids = _ids.concat(ids.slice(i + 1));
        return;
      }
    }
  }
  ids = _ids;
}

function getIds(startTime, count, lastRowId) {
  startTime = startTime || lastRowId;
  if (!startTime) {
    return ids.slice(-count);
  }
  var index = 0;
  if (startTime !== '0') {
    index = ids.indexOf(startTime) + 1;
  }
  return ids.slice(index, index + count);
}

function getBase64Data(res) {
  return 'data:' + res.headers['content-type'].split(';')[0] + ';base64,';
}

function getList(ids) {
  if (!Array.isArray(ids)) {
    return [];
  }
  return ids.map(function(id, i) {
    return reqData[id];
  });
}

function handleRequest(req) {
  var curData = req.data;
  var id = curData.id = curData.id || (curData.startTime + '-' + ++count);
  reqData[id] = curData;
  ids.indexOf(id) === -1 && ids.push(id);
}

function decodeData(frame) {
  if (frame.base64 == null) {
    if (!util.isUTF8(frame.charset)) {
      try {
        frame.bin = SafeBuffer.from(iconv.decode(frame.bin, frame.charset));
      } catch(e) {}
    }
    frame.base64 = frame.bin ? frame.bin.toString('base64') : '';
    frame.bin = '';
  }
  return frame;
}
function handleFrame(data) {
  frames.push(data);
}

function getFrames(curReqId, lastFrameId) {
  if (!curReqId) {
    return;
  }
  var result = [];
  var count = 10;
  for (var i = frames.length - 1; i >= 0; i--) {
    var frame = frames[i];
    if (frame.reqId === curReqId && (lastFrameId ? frame.frameId > lastFrameId : count > 0)) {
      result.push(decodeData(frame));
      if (--count <= 0) {
        break;
      }
    }
  }
  return result.reverse();
}

module.exports = function init(_proxy) {
  proxy = _proxy;
  enable();
/**
* options: {
* 		startTime: timestamp || timestamp + '-' + count
* 		count: 获取新数据的数量
* 		ids: 请未结束的id列表
* }
*
* @param options
*/
  function formatFilter(filter, clientIp) {
    if (!filter.url && !filter.name && !filter.value && !filter.ip) {
      return;
    }
    var url = util.trimStr(filter.url).toLowerCase();
    var name = util.trimStr(filter.name).toLowerCase();
    var value = util.trimStr(filter.value).toLowerCase();
    var ip = util.trimStr(filter.ip);
    var list = [];
    if (ip === 'self') {
      ip = clientIp;
    } else if (ip && !net.isIP(ip)) {
      ip.split(',').forEach(function(item) {
        item = item.trim();
        if (item === 'self') {
          item = clientIp;
        }
        if (net.isIP(item) && list.indexOf(item) === -1) {
          list.push(item);
        }
      });
      ip = null;
    }
    var result;
    if (url) {
      result = {};
      result.url = url;
    }
    if (name && value) {
      result = result || {};
      result.name = name;
      result.value = value;
    }
    if (ip) {
      result = result || {};
      result.ip = ip;
    }
    if (list.length) {
      result = result || {};
      result.ipList = list.slice(0, 16);
    }
    return result;
  }
  function checkClientIp(item, filter) {
    var clientIp = item.req.ip;
    if (filter.ip && clientIp !== filter.ip) {
      return false;
    }
    var ipList = filter.ipList;
    if (!ipList) {
      return true;
    }
    var len = ipList.length;
    if (len < 3) {
      if (ipList[0] === clientIp) {
        return true;
      }
      if (ipList[1] && ipList[1] === clientIp) {
        return true;
      }
    } else {
      for (var i = 0; i < len; i++) {
        var ip = ipList[i];
        if (ip === clientIp) {
          return true;
        }
      }
    }
    return false;
  }
  function checkItem(item, filter) {
    if (!item) {
      return false;
    }
    if (!checkClientIp(item, filter)) {
      return false;
    }
    if (filter.url && item.url.toLowerCase().indexOf(filter.url) === -1) {
      return false;
    }
    if (!filter.name) {
      return true;
    }
    var value = item.req.headers[filter.name];
    if (!value || typeof value !== 'string') {
      if (!Array.isArray(value)) {
        return false;
      }
      value = value.join('\n');
    }
    value = value.toLowerCase();
    if (value.indexOf(filter.value) !== -1) {
      return true;
    }
    return value.indexOf(util.encodeURIComponent(filter.value).toLowerCase()) !== -1;
  }
  proxy.getLastDataId = function() {
    return ids[ids.length - 1];
  };
  proxy.getData = function(options, clientIp) {
    enable();
    options = options || {};
    var filter = formatFilter(options, clientIp);
    var data = {};
    var count = options.count;
    var startTime = options.startTime;
    var clearNetwork = count == 0 || startTime == -2;
    if (!clearNetwork) {
      count = count > 0 && count < COUNT ? +count : COUNT;
    }
    var newIds = (clearNetwork || startTime == -1) ? [] : getIds(startTime, count, options.lastRowId);
    var setData = function(item) {
      if (item) {
        var req = item.req;
        var res = item.res;
        if (Buffer.isBuffer(req.body)) {
          req.body = util.decodeBuffer(req.body);
        }
        if (Buffer.isBuffer(res.body)) {
          if (res.isImage) {
            res.body = getBase64Data(res) + res.body.toString('base64');
          } else {
            res.body = util.decodeBuffer(res.body);
          }
        }
        if (config.secureFilter) {
          try {
            item = config.secureFilter(item, clientIp, filter) || item;
          } catch (e) {
            if (config.debugMode) {
              /* eslint-disable no-console */
              console.log(e);
            }
            logger.error(e);
          }
        }
        data[item.id] = item;
      }
    };
    if (newIds.length > 0) {
      if (filter) {
        var id = newIds[0];
        var index = ids.indexOf(newIds[0]);
        newIds = [];
        while(id && count > 0) {
          var item = reqData[id];
          if (checkItem(item, filter)) {
            setData(item);
            newIds.push(id);
            --count;
          }
          id = ids[++index];
        }
      } else if (!filter) {
        getList(newIds).forEach(setData);
      }
    }
    getList(options.ids).forEach(setData);
    var endId = ids[ids.length - 1];
    return {
      ids: options.ids || [],
      newIds: newIds,
      data: data,
      lastId: clearNetwork ? endId : newIds[newIds.length - 1],
      endId: endId,
      frames: getFrames(options.curReqId, options.lastFrameId)
    };
  };
};
<commit_msg>refactor: code<commit_after>var iconv = require('iconv-lite');
var net = require('net');
var util = require('./index');
var logger = require('./logger');
var config = require('../config');
var SafeBuffer = require('safe-buffer');

if (!(config.reqCacheSize > 0) || config.reqCacheSize < 600) {
  config.reqCacheSize = 600;
}

if (!(config.frameCacheSize > 0) || config.frameCacheSize < 512) {
  config.frameCacheSize = 512;
}

var TIMEOUT = 36000;
var CLEAR_INTERVAL = 5000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var MAX_LENGTH = config.reqCacheSize;
var OVERFLOW_LENGTH = MAX_LENGTH * 5;
var MIN_LENGTH = MAX_LENGTH - 100;
var MAX_FRAMES_LENGTH = config.frameCacheSize;
var COUNT = 100;
var count = 0;
var ids = [];
var reqData = {};
var frames = [];
var proxy, binded, timeout, interval;

function disable() {
  proxy.removeListener('request', handleRequest);
  proxy.removeListener('frame', handleFrame);
  ids = [];
  reqData = {};
  frames = [];
  interval && clearInterval(interval);
  interval = null;
  binded = false;
}

function enable() {
  if (!binded) {
    binded = true;
    proxy.on('request', handleRequest);
    proxy.on('frame', handleFrame);
  }
  clearTimeout(timeout);
  timeout = setTimeout(disable, TIMEOUT);
  if (!interval) {
    interval = setInterval(clearCache, CLEAR_INTERVAL);
  }
}

/**
* 如果超过最大缓存数，清理如下请求数据：
* 1. 已经请求结束且结束时间超过10秒
* 2. 请求#1前面的未结束且未被ui读取过的请求
*/
function clearCache() {
  if (frames.length > MAX_FRAMES_LENGTH) {
    frames.splice(0, 100);
  }
  var len = ids.length;
  if (len <= MAX_LENGTH) {
    return;
  }

  var now = Date.now();
  var _ids = [];
  var overflow = len - OVERFLOW_LENGTH;
  if (overflow >= 0) {
    overflow = overflow + MAX_LENGTH * 2;
  }
  for (var i = 0; i < len; i++) {
    var id = ids[i];
    var curData = reqData[id];
    if (i > overflow &&
      (curData.endTime ? now - curData.endTime < CACHE_TIME : now - curData.startTime < TIMEOUT)) {
      _ids.push(id);
    } else {
      delete reqData[id];
      if (--len <= MIN_LENGTH) {
        ids = _ids.concat(ids.slice(i + 1));
        return;
      }
    }
  }
  ids = _ids;
}

function getIds(startTime, count, lastRowId) {
  startTime = startTime || lastRowId;
  if (!startTime) {
    return ids.slice(-count);
  }
  var index = 0;
  if (startTime !== '0') {
    index = ids.indexOf(startTime) + 1;
  }
  return ids.slice(index, index + count);
}

function getList(ids) {
  if (!Array.isArray(ids)) {
    return [];
  }
  return ids.map(function(id, i) {
    return reqData[id];
  });
}

function handleRequest(req) {
  var curData = req.data;
  var id = curData.id = curData.id || (curData.startTime + '-' + ++count);
  reqData[id] = curData;
  ids.indexOf(id) === -1 && ids.push(id);
}

function decodeData(frame) {
  if (frame.base64 == null) {
    if (!util.isUTF8(frame.charset)) {
      try {
        frame.bin = SafeBuffer.from(iconv.decode(frame.bin, frame.charset));
      } catch(e) {}
    }
    frame.base64 = frame.bin ? frame.bin.toString('base64') : '';
    frame.bin = '';
  }
  return frame;
}
function handleFrame(data) {
  frames.push(data);
}

function getFrames(curReqId, lastFrameId) {
  if (!curReqId) {
    return;
  }
  var result = [];
  var count = 10;
  for (var i = frames.length - 1; i >= 0; i--) {
    var frame = frames[i];
    if (frame.reqId === curReqId && (lastFrameId ? frame.frameId > lastFrameId : count > 0)) {
      result.push(decodeData(frame));
      if (--count <= 0) {
        break;
      }
    }
  }
  return result.reverse();
}

module.exports = function init(_proxy) {
  proxy = _proxy;
  enable();
/**
* options: {
* 		startTime: timestamp || timestamp + '-' + count
* 		count: 获取新数据的数量
* 		ids: 请未结束的id列表
* }
*
* @param options
*/
  function formatFilter(filter, clientIp) {
    if (!filter.url && !filter.name && !filter.value && !filter.ip) {
      return;
    }
    var url = util.trimStr(filter.url).toLowerCase();
    var name = util.trimStr(filter.name).toLowerCase();
    var value = util.trimStr(filter.value).toLowerCase();
    var ip = util.trimStr(filter.ip);
    var list = [];
    if (ip === 'self') {
      ip = clientIp;
    } else if (ip && !net.isIP(ip)) {
      ip.split(',').forEach(function(item) {
        item = item.trim();
        if (item === 'self') {
          item = clientIp;
        }
        if (net.isIP(item) && list.indexOf(item) === -1) {
          list.push(item);
        }
      });
      ip = null;
    }
    var result;
    if (url) {
      result = {};
      result.url = url;
    }
    if (name && value) {
      result = result || {};
      result.name = name;
      result.value = value;
    }
    if (ip) {
      result = result || {};
      result.ip = ip;
    }
    if (list.length) {
      result = result || {};
      result.ipList = list.slice(0, 16);
    }
    return result;
  }
  function checkClientIp(item, filter) {
    var clientIp = item.req.ip;
    if (filter.ip && clientIp !== filter.ip) {
      return false;
    }
    var ipList = filter.ipList;
    if (!ipList) {
      return true;
    }
    var len = ipList.length;
    if (len < 3) {
      if (ipList[0] === clientIp) {
        return true;
      }
      if (ipList[1] && ipList[1] === clientIp) {
        return true;
      }
    } else {
      for (var i = 0; i < len; i++) {
        var ip = ipList[i];
        if (ip === clientIp) {
          return true;
        }
      }
    }
    return false;
  }
  function checkItem(item, filter) {
    if (!item) {
      return false;
    }
    if (!checkClientIp(item, filter)) {
      return false;
    }
    if (filter.url && item.url.toLowerCase().indexOf(filter.url) === -1) {
      return false;
    }
    if (!filter.name) {
      return true;
    }
    var value = item.req.headers[filter.name];
    if (!value || typeof value !== 'string') {
      if (!Array.isArray(value)) {
        return false;
      }
      value = value.join('\n');
    }
    value = value.toLowerCase();
    if (value.indexOf(filter.value) !== -1) {
      return true;
    }
    return value.indexOf(util.encodeURIComponent(filter.value).toLowerCase()) !== -1;
  }
  proxy.getLastDataId = function() {
    return ids[ids.length - 1];
  };
  proxy.getData = function(options, clientIp) {
    enable();
    options = options || {};
    var filter = formatFilter(options, clientIp);
    var data = {};
    var count = options.count;
    var startTime = options.startTime;
    var clearNetwork = count == 0 || startTime == -2;
    if (!clearNetwork) {
      count = count > 0 && count < COUNT ? +count : COUNT;
    }
    var newIds = (clearNetwork || startTime == -1) ? [] : getIds(startTime, count, options.lastRowId);
    var setData = function(item) {
      if (item) {
        var req = item.req;
        var res = item.res;
        if (Buffer.isBuffer(req.body)) {
          req.body = util.decodeBuffer(req.body);
        }
        if (Buffer.isBuffer(res.body)) {
          if (res.isImage) {
            var type = res.headers['content-type'].split(';')[0];
            res.body = 'data:' + type + ';base64,' + res.body.toString('base64');
          } else {
            res.body = util.decodeBuffer(res.body);
          }
        }
        if (config.secureFilter) {
          try {
            item = config.secureFilter(item, clientIp, filter) || item;
          } catch (e) {
            if (config.debugMode) {
              /* eslint-disable no-console */
              console.log(e);
            }
            logger.error(e);
          }
        }
        data[item.id] = item;
      }
    };
    if (newIds.length > 0) {
      if (filter) {
        var id = newIds[0];
        var index = ids.indexOf(newIds[0]);
        newIds = [];
        while(id && count > 0) {
          var item = reqData[id];
          if (checkItem(item, filter)) {
            setData(item);
            newIds.push(id);
            --count;
          }
          id = ids[++index];
        }
      } else if (!filter) {
        getList(newIds).forEach(setData);
      }
    }
    getList(options.ids).forEach(setData);
    var endId = ids[ids.length - 1];
    return {
      ids: options.ids || [],
      newIds: newIds,
      data: data,
      lastId: clearNetwork ? endId : newIds[newIds.length - 1],
      endId: endId,
      frames: getFrames(options.curReqId, options.lastFrameId)
    };
  };
};
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import Paper from 'material-ui/Paper';
import {injectGlobal} from 'styled-components';
import {Grid, Row, Col} from 'react-flexbox-grid';
import SchemaForm from 'react-schema-form';
import {
  PageTemplate,
  Header,
  Footer,
  FileMultimedia,
  FileHeader,
  FileMostRecent,
  Loading,
  FileMultimediaMenu
} from 'components';

import * as FileService from '../../../services/FileService';

class FileMultimediaPage extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      id: null,
      fileComplete: null,
      files: [],
      sections: null
    }
  }

  componentDidMount() {}

  componentWillMount() {

    this.setState({id: this.props.match.params.id})

    FileService.getFileComplete(this.props.match.params.id).then(complete => {
      this.setState({fileComplete: complete});
    });

    FileService.getLastUpdatedRecords().then(data => {
      this.setState({files: data});
    }).catch(err => {
      console.log(err);
    });

    let obj = {
      'Imágenes' : [
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://i.dailymail.co.uk/i/pix/2014/01/08/article-2535743-1A7C03F700000578-450_634x750.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'https://c402277.ssl.cf1.rackcdn.com/photos/1876/images/story_full_width/Snow-Leopard_08.15.2012_Find-Your-Inner-Animal.jpg?1345554887',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://www.erdekesseg.hu/wp-content/uploads/2014/09/allatos-szelfik-00010.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg'
      ],
      'Sonidos' : [
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3'
      ],
      'Otros' : []
    };

    this.setState({sections: obj});

  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props.match.params.id);
  }

  title() {
    return this.state.fileComplete.taxonRecordNameApprovedInUse.taxonRecordName.scientificName.canonicalName.simple;
  }
  subtitle() {
    return this.state.fileComplete.taxonRecordNameApprovedInUse.taxonRecordName.scientificName.canonicalAuthorship.simple;
  }

  render() {

    return (
      <PageTemplate header={<Header/>} footer={<Footer/>} wallpaper='File'>
        {this.state.fileComplete && <Grid className="container">
          <Row className="animated fadeIn">
            <Col xs={12} lg={12}>
              <FileHeader title={this.title()} subtitle={this.subtitle()} id={this.state.id} active="multimedia"/>
              <FileMultimedia complete={this.state.sections}/>
            </Col>
          </Row>
        </Grid> || <Loading text='Cargando multimedia...'/>}
        {this.state.files.length > 0 && <FileMostRecent id={this.state.id} data={this.state.files}/> || <Loading/>}
      </PageTemplate>
    )
  }
}

export default FileMultimediaPage;
<commit_msg>added link to FileMultimediaPage<commit_after>import React, {PropTypes} from 'react';
import Paper from 'material-ui/Paper';
import {injectGlobal} from 'styled-components';
import {Grid, Row, Col} from 'react-flexbox-grid';
import SchemaForm from 'react-schema-form';
import {
  PageTemplate,
  Header,
  Footer,
  FileMultimedia,
  FileHeader,
  FileMostRecent,
  Loading,
  FileMultimediaMenu
} from 'components';

import * as FileService from '../../../services/FileService';

class FileMultimediaPage extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      id: null,
      fileComplete: null,
      files: [],
      sections: null
    }
  }

  componentDidMount() {}

  componentWillMount() {

    this.setState({id: this.props.match.params.id})

    FileService.getFileComplete(this.props.match.params.id).then(complete => {
      this.setState({fileComplete: complete});
    });

    FileService.getLastUpdatedRecords().then(data => {
      this.setState({files: data});
    }).catch(err => {
      console.log(err);
    });

    let obj = {
      'Imágenes' : [
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://i.dailymail.co.uk/i/pix/2014/01/08/article-2535743-1A7C03F700000578-450_634x750.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'https://c402277.ssl.cf1.rackcdn.com/photos/1876/images/story_full_width/Snow-Leopard_08.15.2012_Find-Your-Inner-Animal.jpg?1345554887',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://www.erdekesseg.hu/wp-content/uploads/2014/09/allatos-szelfik-00010.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg',
        'http://illuzone.net/wp-content/uploads/2015/01/Red-Panda-4.jpg'
      ],
      'Sonidos' : [
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3',
        '/demo/sound.mp3'
      ],
      'Otros' : [
        'https://opensource.org/licenses/MIT',
        'https://opensource.org/licenses/MIT',
        'https://opensource.org/licenses/MIT',
        'https://opensource.org/licenses/MIT',
        'https://opensource.org/licenses/MIT',
        'https://opensource.org/licenses/MIT'
      ]
    };

    this.setState({sections: obj});

  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props.match.params.id);
  }

  title() {
    return this.state.fileComplete.taxonRecordNameApprovedInUse.taxonRecordName.scientificName.canonicalName.simple;
  }
  subtitle() {
    return this.state.fileComplete.taxonRecordNameApprovedInUse.taxonRecordName.scientificName.canonicalAuthorship.simple;
  }

  render() {

    return (
      <PageTemplate header={<Header/>} footer={<Footer/>} wallpaper='File'>
        {this.state.fileComplete && <Grid className="container">
          <Row className="animated fadeIn">
            <Col xs={12} lg={12}>
              <FileHeader title={this.title()} subtitle={this.subtitle()} id={this.state.id} active="multimedia"/>
              <FileMultimedia complete={this.state.sections}/>
            </Col>
          </Row>
        </Grid> || <Loading text='Cargando multimedia...'/>}
        {this.state.files.length > 0 && <FileMostRecent id={this.state.id} data={this.state.files}/> || <Loading/>}
      </PageTemplate>
    )
  }
}

export default FileMultimediaPage;
<|endoftext|>


<commit_before>// use strict
'use strict';

// require dependencies
const riot        = require ('riot');
const glob        = require ('glob');
const path        = require ('path');
const prettyError = require ('pretty-error');

// require local dependencies
const config = require ('app/config');

/**
 * create engine class
 */
class engine {
  /**
   * construct riot engine class
   */
  constructor () {
    // require tags
    require ('app/cache/tags.js');

    // bind methods
    this.email  = this.email.bind (this);
    this.render = this.render.bind (this);
  }

  /**
   * render riot tag locally
   *
   * @param  {String}   filePath
   * @param  {*}        options
   * @param  {Function} callback
   *
   * @return {*}
   */
  render (filePath, options, callback) {
    // require riot tag
    options.mountPage = filePath.split ('views/')[1].split (path.sep).join ('-').trim ().replace ('.tag', '') + '-page';

    // set route
    let route = options.route;

    // delete frontend options
    delete options.cache;
    delete options.route;
    delete options._locals;
    delete options.settings;

    // set layout
    options.layout = (options.layout ? options.layout : 'main') + '-layout';

    // start timer
    options.routeEnd = new Date ().getTime ();

    // log timing
    global.logger.log ('debug', options.path + ' loaded in ' + (options.routeEnd - options.routeStart) + 'ms', {
      'class' : route ? 'route ' + route.class + '.' + route.fn : 'no route'
    });

    // check if should json
    if (options.isJSON) {
      // delete isJSON
      delete options.isJSON;

      // return callback
      return callback (null, JSON.stringify ({
        'opts': options
      }));
    }

    // set server option
    options.cdn    = config.cdn || false;
    options.server = true;

    // log render start
    let renderStart = options.routeEnd;

    // do try/catch
    try {
      // render page
      let page = '<!DOCTYPE html>';
      page += '';
      page += '';
      page += '<meta charset="utf-8">';
      page += '<title>' + (options.pagetitle ? options.pagetitle + ' | ' : '') + options.title + '</title>';
      page += '<link rel="stylesheet" href="/public/css/app.min.css' + (config.version ? '?v=' + config.version : '') + '" data-eden="before-head">';
      page += options.head || '';
      page += '';
      page += '';
      page += riot.render (options.layout, options);

      // delete server
      delete options.cdn;
      delete options.server;

      // set before
      let before = options.beforeScript || '';
      let after  = options.afterScript  || '';

      // delete post-render options
      delete options.beforeScript;
      delete options.afterScript;

      // do script section of page
      page += '';
      page += before || '';
      page += '';
      page += after || '';
      page += '';
      page += '';

      // log rendered
      global.logger.log ('debug', options.path + ' rendered in ' + (new Date ().getTime () - renderStart) + 'ms', {
        'class' : route ? 'route ' + route.class + '.' + route.fn : 'no route'
      });

      // return render callback
      return callback (null, page);
    } catch (e) {
      // log error
      var pe = new prettyError ();

      // log error
      console.log (pe.render (e));

      // return render callback
      return callback (e);
    }
  }

  /**
   * create email
   *
   * @param  {String} template
   * @param  {Object} options
   *
   * @return {Promise}
   */
  async email (template, options) {
    // get email template
    template = (template.indexOf ('-email') === -1) ? template + '-email' : template;

    // create email template
    let email = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
    email += '';
    email += '';
    email += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    email += '<meta name="viewport" content="width=device-width, initial-scale=1" />';
    email += options.style || '';
    email += '';
    email += options.bodyTag || '';
    email += riot.render (template, options).replace ('<' + template + '>', '').replace ('</' + template + '>', '');
    email += '';
    email += '';

    // resolve email html
    return email;
  }
}

/**
 * export engine class
 * @type {engine}
 */
module.exports = engine;
<commit_msg>add route type to debug route logger<commit_after>// use strict
'use strict';

// require dependencies
const riot        = require ('riot');
const glob        = require ('glob');
const path        = require ('path');
const prettyError = require ('pretty-error');

// require local dependencies
const config = require ('app/config');

/**
 * create engine class
 */
class engine {
  /**
   * construct riot engine class
   */
  constructor () {
    // require tags
    require ('app/cache/tags.js');

    // bind methods
    this.email  = this.email.bind (this);
    this.render = this.render.bind (this);
  }

  /**
   * render riot tag locally
   *
   * @param  {String}   filePath
   * @param  {*}        options
   * @param  {Function} callback
   *
   * @return {*}
   */
  render (filePath, options, callback) {
    // require riot tag
    options.mountPage = filePath.split ('views/')[1].split (path.sep).join ('-').trim ().replace ('.tag', '') + '-page';

    // set route
    let route = options.route;

    // delete frontend options
    delete options.cache;
    delete options.route;
    delete options._locals;
    delete options.settings;

    // set layout
    options.layout = (options.layout ? options.layout : 'main') + '-layout';

    // start timer
    options.routeEnd = new Date ().getTime ();

    // log timing
    global.logger.log ('debug', options.path + ' loaded in ' + (options.routeEnd - options.routeStart) + 'ms', {
      'class' : route ? 'route {' + route.type + '} ' + route.class + '.' + route.fn : 'no route'
    });

    // check if should json
    if (options.isJSON) {
      // delete isJSON
      delete options.isJSON;

      // return callback
      return callback (null, JSON.stringify ({
        'opts': options
      }));
    }

    // set server option
    options.cdn    = config.cdn || false;
    options.server = true;

    // log render start
    let renderStart = options.routeEnd;

    // do try/catch
    try {
      // render page
      let page = '<!DOCTYPE html>';
      page += '';
      page += '';
      page += '<meta charset="utf-8">';
      page += '<title>' + (options.pagetitle ? options.pagetitle + ' | ' : '') + options.title + '</title>';
      page += '<link rel="stylesheet" href="/public/css/app.min.css' + (config.version ? '?v=' + config.version : '') + '" data-eden="before-head">';
      page += options.head || '';
      page += '';
      page += '';
      page += riot.render (options.layout, options);

      // delete server
      delete options.cdn;
      delete options.server;

      // set before
      let before = options.beforeScript || '';
      let after  = options.afterScript  || '';

      // delete post-render options
      delete options.beforeScript;
      delete options.afterScript;

      // do script section of page
      page += '';
      page += before || '';
      page += '';
      page += after || '';
      page += '';
      page += '';

      // log rendered
      global.logger.log ('debug', options.path + ' rendered in ' + (new Date ().getTime () - renderStart) + 'ms', {
        'class' : route ? 'route {' + route.type + '} ' + route.class + '.' + route.fn : 'no route'
      });

      // return render callback
      return callback (null, page);
    } catch (e) {
      // log error
      var pe = new prettyError ();

      // log error
      console.log (pe.render (e));

      // return render callback
      return callback (e);
    }
  }

  /**
   * create email
   *
   * @param  {String} template
   * @param  {Object} options
   *
   * @return {Promise}
   */
  async email (template, options) {
    // get email template
    template = (template.indexOf ('-email') === -1) ? template + '-email' : template;

    // create email template
    let email = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
    email += '';
    email += '';
    email += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    email += '<meta name="viewport" content="width=device-width, initial-scale=1" />';
    email += options.style || '';
    email += '';
    email += options.bodyTag || '';
    email += riot.render (template, options).replace ('<' + template + '>', '').replace ('</' + template + '>', '');
    email += '';
    email += '';

    // resolve email html
    return email;
  }
}

/**
 * export engine class
 * @type {engine}
 */
module.exports = engine;
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018, 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import sdk from '../../../index';
import Modal from "../../../Modal";
import MatrixClientPeg from "../../../MatrixClientPeg";
import SdkConfig from "../../../SdkConfig";

import PasswordReset from "../../../PasswordReset";

// Phases
// Show controls to configure server details
const PHASE_SERVER_DETAILS = 0;
// Show the forgot password inputs
const PHASE_FORGOT = 1;
// Email is in the process of being sent
const PHASE_SENDING_EMAIL = 2;
// Email has been sent
const PHASE_EMAIL_SENT = 3;
// User has clicked the link in email and completed reset
const PHASE_DONE = 4;

module.exports = React.createClass({
    displayName: 'ForgotPassword',

    propTypes: {
        defaultHsUrl: PropTypes.string,
        defaultIsUrl: PropTypes.string,
        customHsUrl: PropTypes.string,
        customIsUrl: PropTypes.string,
        onLoginClick: PropTypes.func,
        onComplete: PropTypes.func.isRequired,

        // The default server name to use when the user hasn't specified
        // one. This is used when displaying the defaultHsUrl in the UI.
        defaultServerName: PropTypes.string,

        // An error passed along from higher up explaining that something
        // went wrong when finding the defaultHsUrl.
        defaultServerDiscoveryError: PropTypes.string,
    },

    getInitialState: function() {
        return {
            enteredHsUrl: this.props.customHsUrl || this.props.defaultHsUrl,
            enteredIsUrl: this.props.customIsUrl || this.props.defaultIsUrl,
            phase: PHASE_FORGOT,
            email: "",
            password: "",
            password2: "",
            errorText: null,
        };
    },

    submitPasswordReset: function(hsUrl, identityUrl, email, password) {
        this.setState({
            phase: PHASE_SENDING_EMAIL,
        });
        this.reset = new PasswordReset(hsUrl, identityUrl);
        this.reset.resetPassword(email, password).done(() => {
            this.setState({
                phase: PHASE_EMAIL_SENT,
            });
        }, (err) => {
            this.showErrorDialog(_t('Failed to send email') + ": " + err.message);
            this.setState({
                phase: null,
            });
        });
    },

    onVerify: function(ev) {
        ev.preventDefault();
        if (!this.reset) {
            console.error("onVerify called before submitPasswordReset!");
            return;
        }
        this.reset.checkEmailLinkClicked().done((res) => {
            this.setState({ phase: PHASE_DONE });
        }, (err) => {
            this.showErrorDialog(err.message);
        });
    },

    onSubmitForm: function(ev) {
        ev.preventDefault();

        // Don't allow the user to register if there's a discovery error
        // Without this, the user could end up registering on the wrong homeserver.
        if (this.props.defaultServerDiscoveryError) {
            this.setState({errorText: this.props.defaultServerDiscoveryError});
            return;
        }

        if (!this.state.email) {
            this.showErrorDialog(_t('The email address linked to your account must be entered.'));
        } else if (!this.state.password || !this.state.password2) {
            this.showErrorDialog(_t('A new password must be entered.'));
        } else if (this.state.password !== this.state.password2) {
            this.showErrorDialog(_t('New passwords must match each other.'));
        } else {
            const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
            Modal.createTrackedDialog('Forgot Password Warning', '', QuestionDialog, {
                title: _t('Warning!'),
                description:

                        { _t(
                            'Resetting password will currently reset any ' +
                            'end-to-end encryption keys on all devices, ' +
                            'making encrypted chat history unreadable, ' +
                            'unless you first export your room keys and re-import ' +
                            'them afterwards. In future this will be improved.',
                        ) }

,
                button: _t('Continue'),
                extraButtons: [
                    <button key="export_keys" className="mx_Dialog_primary"
                            onClick={this._onExportE2eKeysClicked}>
                        { _t('Export E2E room keys') }
                    </button>,
                ],
                onFinished: (confirmed) => {
                    if (confirmed) {
                        this.submitPasswordReset(
                            this.state.enteredHsUrl, this.state.enteredIsUrl,
                            this.state.email, this.state.password,
                        );
                    }
                },
            });
        }
    },

    _onExportE2eKeysClicked: function() {
        Modal.createTrackedDialogAsync('Export E2E Keys', 'Forgot Password',
            import('../../../async-components/views/dialogs/ExportE2eKeysDialog'),
            {
                matrixClient: MatrixClientPeg.get(),
            },
        );
    },

    onInputChanged: function(stateKey, ev) {
        this.setState({
            [stateKey]: ev.target.value,
        });
    },

    onServerConfigChange: function(config) {
        const newState = {};
        if (config.hsUrl !== undefined) {
            newState.enteredHsUrl = config.hsUrl;
        }
        if (config.isUrl !== undefined) {
            newState.enteredIsUrl = config.isUrl;
        }
        this.setState(newState);
    },

    onLoginClick: function(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.props.onLoginClick();
    },

    showErrorDialog: function(body, title) {
        const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
        Modal.createTrackedDialog('Forgot Password Error', '', ErrorDialog, {
            title: title,
            description: body,
        });
    },

    renderServerDetails() {
        return null;
    },

    renderForgot() {
        const ServerConfig = sdk.getComponent("auth.ServerConfig");

        let serverConfigSection;
        if (!SdkConfig.get()['disable_custom_urls']) {
            serverConfigSection = (
                <ServerConfig ref="serverConfig"
                    defaultHsUrl={this.props.defaultHsUrl}
                    defaultIsUrl={this.props.defaultIsUrl}
                    customHsUrl={this.props.customHsUrl}
                    customIsUrl={this.props.customIsUrl}
                    onServerConfigChange={this.onServerConfigChange}
                    delayTimeMs={0} />
            );
        }

        let errorText = null;
        const err = this.state.errorText || this.props.defaultServerDiscoveryError;
        if (err) {
            errorText =
{ err }
;
        }

        let yourMatrixAccountText = _t('Your account');
        try {
            const parsedHsUrl = new URL(this.state.enteredHsUrl);
            yourMatrixAccountText = _t('Your account on %(serverName)s', {
                serverName: parsedHsUrl.hostname,
            });
        } catch (e) {
            // ignore
        }

        return

                {yourMatrixAccountText}

            {errorText}
            <form onSubmit={this.onSubmitForm}>

                    <input className="mx_Login_field" ref="user" type="text"
                        name="reset_email" // define a name so browser's password autofill gets less confused
                        value={this.state.email}
                        onChange={this.onInputChanged.bind(this, "email")}
                        placeholder={_t('Email')} autoFocus />

                    <input className="mx_Login_field" ref="pass" type="password"
                        name="reset_password"
                        value={this.state.password}
                        onChange={this.onInputChanged.bind(this, "password")}
                        placeholder={_t('Password')} />
                    <input className="mx_Login_field" ref="pass" type="password"
                        name="reset_password_confirm"
                        value={this.state.password2}
                        onChange={this.onInputChanged.bind(this, "password2")}
                        placeholder={_t('Confirm')} />

                {_t(
                    'A verification email will be sent to your inbox to confirm ' +
                    'setting your new password.',
                )}
                <input className="mx_Login_submit" type="submit" value={_t('Send Reset Email')} />
            </form>
            {serverConfigSection}

                {_t('Sign in instead')}

;
    },

    renderSendingEmail() {
        const Spinner = sdk.getComponent("elements.Spinner");
        return <Spinner />;
    },

    renderEmailSent() {
        return

            {_t("An email has been sent to %(emailAddress)s. Once you've followed the " +
                "link it contains, click below.", { emailAddress: this.state.email })}

            <input className="mx_Login_submit" type="button" onClick={this.onVerify}
                value={_t('I have verified my email address')} />

;
    },

    renderDone() {
        return

{_t('Your password has been reset')}.

{_t('You have been logged out of all devices and will no longer receive push notifications. ' +
                'To re-enable notifications, sign in again on each device')}.

            <input className="mx_Login_submit" type="button" onClick={this.props.onComplete}
                value={_t('Return to login screen')} />

;
    },

    render: function() {
        const AuthPage = sdk.getComponent("auth.AuthPage");
        const AuthHeader = sdk.getComponent("auth.AuthHeader");
        const AuthBody = sdk.getComponent("auth.AuthBody");

        let resetPasswordJsx;
        switch (this.state.phase) {
            case PHASE_SERVER_DETAILS:
                resetPasswordJsx = this.renderServerDetails();
                break;
            case PHASE_FORGOT:
                resetPasswordJsx = this.renderForgot();
                break;
            case PHASE_SENDING_EMAIL:
                resetPasswordJsx = this.renderSendingEmail();
                break;
            case PHASE_EMAIL_SENT:
                resetPasswordJsx = this.renderEmailSent();
                break;
            case PHASE_DONE:
                resetPasswordJsx = this.renderDone();
                break;
        }

        return (
            <AuthPage>
                <AuthHeader />
                <AuthBody>

 { _t('Set a new password') }

                    {resetPasswordJsx}
                </AuthBody>
            </AuthPage>
        );
    },
});
<commit_msg>Move server details to a separate phase of forgot password<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017, 2018, 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
import sdk from '../../../index';
import Modal from "../../../Modal";
import MatrixClientPeg from "../../../MatrixClientPeg";
import SdkConfig from "../../../SdkConfig";

import PasswordReset from "../../../PasswordReset";

// Phases
// Show controls to configure server details
const PHASE_SERVER_DETAILS = 0;
// Show the forgot password inputs
const PHASE_FORGOT = 1;
// Email is in the process of being sent
const PHASE_SENDING_EMAIL = 2;
// Email has been sent
const PHASE_EMAIL_SENT = 3;
// User has clicked the link in email and completed reset
const PHASE_DONE = 4;

module.exports = React.createClass({
    displayName: 'ForgotPassword',

    propTypes: {
        defaultHsUrl: PropTypes.string,
        defaultIsUrl: PropTypes.string,
        customHsUrl: PropTypes.string,
        customIsUrl: PropTypes.string,
        onLoginClick: PropTypes.func,
        onComplete: PropTypes.func.isRequired,

        // The default server name to use when the user hasn't specified
        // one. This is used when displaying the defaultHsUrl in the UI.
        defaultServerName: PropTypes.string,

        // An error passed along from higher up explaining that something
        // went wrong when finding the defaultHsUrl.
        defaultServerDiscoveryError: PropTypes.string,
    },

    getInitialState: function() {
        return {
            enteredHsUrl: this.props.customHsUrl || this.props.defaultHsUrl,
            enteredIsUrl: this.props.customIsUrl || this.props.defaultIsUrl,
            phase: PHASE_FORGOT,
            email: "",
            password: "",
            password2: "",
            errorText: null,
        };
    },

    submitPasswordReset: function(hsUrl, identityUrl, email, password) {
        this.setState({
            phase: PHASE_SENDING_EMAIL,
        });
        this.reset = new PasswordReset(hsUrl, identityUrl);
        this.reset.resetPassword(email, password).done(() => {
            this.setState({
                phase: PHASE_EMAIL_SENT,
            });
        }, (err) => {
            this.showErrorDialog(_t('Failed to send email') + ": " + err.message);
            this.setState({
                phase: null,
            });
        });
    },

    onVerify: function(ev) {
        ev.preventDefault();
        if (!this.reset) {
            console.error("onVerify called before submitPasswordReset!");
            return;
        }
        this.reset.checkEmailLinkClicked().done((res) => {
            this.setState({ phase: PHASE_DONE });
        }, (err) => {
            this.showErrorDialog(err.message);
        });
    },

    onSubmitForm: function(ev) {
        ev.preventDefault();

        // Don't allow the user to register if there's a discovery error
        // Without this, the user could end up registering on the wrong homeserver.
        if (this.props.defaultServerDiscoveryError) {
            this.setState({errorText: this.props.defaultServerDiscoveryError});
            return;
        }

        if (!this.state.email) {
            this.showErrorDialog(_t('The email address linked to your account must be entered.'));
        } else if (!this.state.password || !this.state.password2) {
            this.showErrorDialog(_t('A new password must be entered.'));
        } else if (this.state.password !== this.state.password2) {
            this.showErrorDialog(_t('New passwords must match each other.'));
        } else {
            const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
            Modal.createTrackedDialog('Forgot Password Warning', '', QuestionDialog, {
                title: _t('Warning!'),
                description:

                        { _t(
                            'Resetting password will currently reset any ' +
                            'end-to-end encryption keys on all devices, ' +
                            'making encrypted chat history unreadable, ' +
                            'unless you first export your room keys and re-import ' +
                            'them afterwards. In future this will be improved.',
                        ) }

,
                button: _t('Continue'),
                extraButtons: [
                    <button key="export_keys" className="mx_Dialog_primary"
                            onClick={this._onExportE2eKeysClicked}>
                        { _t('Export E2E room keys') }
                    </button>,
                ],
                onFinished: (confirmed) => {
                    if (confirmed) {
                        this.submitPasswordReset(
                            this.state.enteredHsUrl, this.state.enteredIsUrl,
                            this.state.email, this.state.password,
                        );
                    }
                },
            });
        }
    },

    _onExportE2eKeysClicked: function() {
        Modal.createTrackedDialogAsync('Export E2E Keys', 'Forgot Password',
            import('../../../async-components/views/dialogs/ExportE2eKeysDialog'),
            {
                matrixClient: MatrixClientPeg.get(),
            },
        );
    },

    onInputChanged: function(stateKey, ev) {
        this.setState({
            [stateKey]: ev.target.value,
        });
    },

    onServerConfigChange: function(config) {
        const newState = {};
        if (config.hsUrl !== undefined) {
            newState.enteredHsUrl = config.hsUrl;
        }
        if (config.isUrl !== undefined) {
            newState.enteredIsUrl = config.isUrl;
        }
        this.setState(newState);
    },

    onServerDetailsNextPhaseClick(ev) {
        ev.stopPropagation();
        this.setState({
            phase: PHASE_FORGOT,
        });
    },

    onEditServerDetailsClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.setState({
            phase: PHASE_SERVER_DETAILS,
        });
    },

    onLoginClick: function(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.props.onLoginClick();
    },

    showErrorDialog: function(body, title) {
        const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
        Modal.createTrackedDialog('Forgot Password Error', '', ErrorDialog, {
            title: title,
            description: body,
        });
    },

    renderServerDetails() {
        const ServerConfig = sdk.getComponent("auth.ServerConfig");
        const AccessibleButton = sdk.getComponent("elements.AccessibleButton");

        if (SdkConfig.get()['disable_custom_urls']) {
            return null;
        }

        return

            <ServerConfig ref="serverConfig"
                defaultHsUrl={this.props.defaultHsUrl}
                defaultIsUrl={this.props.defaultIsUrl}
                customHsUrl={this.state.enteredHsUrl}
                customIsUrl={this.state.enteredIsUrl}
                onServerConfigChange={this.onServerConfigChange}
                delayTimeMs={0} />
            <AccessibleButton className="mx_Login_submit"
                onClick={this.onServerDetailsNextPhaseClick}
            >
                {_t("Next")}
            </AccessibleButton>

;
    },

    renderForgot() {
        let errorText = null;
        const err = this.state.errorText || this.props.defaultServerDiscoveryError;
        if (err) {
            errorText =
{ err }
;
        }

        let yourMatrixAccountText = _t('Your account');
        try {
            const parsedHsUrl = new URL(this.state.enteredHsUrl);
            yourMatrixAccountText = _t('Your account on %(serverName)s', {
                serverName: parsedHsUrl.hostname,
            });
        } catch (e) {
            // ignore
        }

        // If custom URLs are allowed, wire up the server details edit link.
        let editLink = null;
        if (!SdkConfig.get()['disable_custom_urls']) {
            editLink =
                {_t('Change')}
            ;
        }

        return

                {yourMatrixAccountText}
                {editLink}

            {errorText}
            <form onSubmit={this.onSubmitForm}>

                    <input className="mx_Login_field" ref="user" type="text"
                        name="reset_email" // define a name so browser's password autofill gets less confused
                        value={this.state.email}
                        onChange={this.onInputChanged.bind(this, "email")}
                        placeholder={_t('Email')} autoFocus />

                    <input className="mx_Login_field" ref="pass" type="password"
                        name="reset_password"
                        value={this.state.password}
                        onChange={this.onInputChanged.bind(this, "password")}
                        placeholder={_t('Password')} />
                    <input className="mx_Login_field" ref="pass" type="password"
                        name="reset_password_confirm"
                        value={this.state.password2}
                        onChange={this.onInputChanged.bind(this, "password2")}
                        placeholder={_t('Confirm')} />

                {_t(
                    'A verification email will be sent to your inbox to confirm ' +
                    'setting your new password.',
                )}
                <input className="mx_Login_submit" type="submit" value={_t('Send Reset Email')} />
            </form>

                {_t('Sign in instead')}

;
    },

    renderSendingEmail() {
        const Spinner = sdk.getComponent("elements.Spinner");
        return <Spinner />;
    },

    renderEmailSent() {
        return

            {_t("An email has been sent to %(emailAddress)s. Once you've followed the " +
                "link it contains, click below.", { emailAddress: this.state.email })}

            <input className="mx_Login_submit" type="button" onClick={this.onVerify}
                value={_t('I have verified my email address')} />

;
    },

    renderDone() {
        return

{_t('Your password has been reset')}.

{_t('You have been logged out of all devices and will no longer receive push notifications. ' +
                'To re-enable notifications, sign in again on each device')}.

            <input className="mx_Login_submit" type="button" onClick={this.props.onComplete}
                value={_t('Return to login screen')} />

;
    },

    render: function() {
        const AuthPage = sdk.getComponent("auth.AuthPage");
        const AuthHeader = sdk.getComponent("auth.AuthHeader");
        const AuthBody = sdk.getComponent("auth.AuthBody");

        let resetPasswordJsx;
        switch (this.state.phase) {
            case PHASE_SERVER_DETAILS:
                resetPasswordJsx = this.renderServerDetails();
                break;
            case PHASE_FORGOT:
                resetPasswordJsx = this.renderForgot();
                break;
            case PHASE_SENDING_EMAIL:
                resetPasswordJsx = this.renderSendingEmail();
                break;
            case PHASE_EMAIL_SENT:
                resetPasswordJsx = this.renderEmailSent();
                break;
            case PHASE_DONE:
                resetPasswordJsx = this.renderDone();
                break;
        }

        return (
            <AuthPage>
                <AuthHeader />
                <AuthBody>

 { _t('Set a new password') }

                    {resetPasswordJsx}
                </AuthBody>
            </AuthPage>
        );
    },
});
<|endoftext|>