<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  var Sunstone = require('sunstone');
  var Notifier = require('utils/notifier');
  var Locale = require('utils/locale');
  var CommonActions = require('utils/common-actions');
  var OpenNebulaResource = require('opennebula/marketplaceapp');
  var OpenNebula = require('opennebula');
  var OpenNebulaAction = require('opennebula/action');

  var RESOURCE = "MarketPlaceApp";
  var XML_ROOT = "MARKETPLACEAPP";
  var TAB_ID = require('./tabId');
  var CREATE_DIALOG_ID = require('./form-panels/create/formPanelId');
  var EXPORT_DIALOG_ID = require('./form-panels/export/formPanelId');
  var CONFIRM_DIALOG_ID = require('utils/dialogs/generic-confirm/dialogId');

  var _commonActions = new CommonActions(OpenNebulaResource, RESOURCE, TAB_ID,
    XML_ROOT, Locale.tr("MarketPlace App created"));

  var _actions = {
    "MarketPlaceApp.create" : _commonActions.create(CREATE_DIALOG_ID),
    "MarketPlaceApp.create_dialog" : _commonActions.showCreate(CREATE_DIALOG_ID),
    "MarketPlaceApp.download_opennebula_dialog" : {
      type: "custom",
      call: function() {
        var selected_nodes = Sunstone.getDataTable(TAB_ID).elements();
        if (selected_nodes.length != 1) {
          Notifier.notifyMessage("Please select one (and just one) app to export.");
          return false;
        }

        var resourceId = "" + selected_nodes[0];

        Sunstone.resetFormPanel(TAB_ID, EXPORT_DIALOG_ID);
        Sunstone.showFormPanel(TAB_ID, EXPORT_DIALOG_ID, "export",
          function(formPanelInstance, context) {
            formPanelInstance.setResourceId(context, resourceId);
          });
      }
    },
    "MarketPlaceApp.export" : {
      type: "multiple",
      call: OpenNebulaResource.export,
      callback: function(req, response) {
        if (response['IMAGE'] !== undefined) {
          $.each(response['IMAGE'], function(i, image) {
            if (image.error != undefined){
              Notifier.notifyError(image.error.message);
            } else {
              Notifier.notifyCustom(Locale.tr("Image created"), " ID: " + image.ID, false);
            }
          });
        };

        if (response['VMTEMPLATE'] !== undefined) {
          $.each(response['VMTEMPLATE'], function(i, vmTemplate) {
            if (vmTemplate.error != undefined) {
              Notifier.notifyError(vmTemplate.error.message);
            } else if (vmTemplate.ID != -1) {
              Notifier.notifyCustom(Locale.tr("VM Template created"), " ID: " + vmTemplate.ID, false);
            }
          });
        };

        Sunstone.hideFormPanel(TAB_ID);
        OpenNebulaAction.clear_cache("IMAGE");
        OpenNebulaAction.clear_cache("VMTEMPLATE");
      },
      elements: function(opts) {
        return Sunstone.getDataTable(TAB_ID).elements(opts);
      },
      error: function(request, response){
        // without tab id param to work for both templates and vms tab
        Sunstone.hideFormPanelLoading();
        Notifier.onError(request, response);
      },
      notify: true
    },
    "MarketPlaceApp.download_local": {
      type: "multiple",
      call: function(params) {
        var selected_nodes = Sunstone.getDataTable(TAB_ID).elements();

        $.each(selected_nodes, function() {
          window.open("http://localhost:9869/marketplaceapp/"+this+"/download?csrftoken="+csrftoken, "_blank");
        });
      },
      elements: function(opts) {
        return Sunstone.getDataTable(TAB_ID).elements(opts);
      },
      error: Notifier.onError
    },
    "MarketPlaceApp.list" : _commonActions.list(),
    "MarketPlaceApp.show" : _commonActions.show(),
    "MarketPlaceApp.refresh" : _commonActions.refresh(),

    "MarketPlaceApp.delete" : {
      type: "multiple",
      call : function(params){
        OpenNebulaResource.show({
          data : {
              id: params.data.id
          },
          success: function(request,app_json){
            var zone = app_json[XML_ROOT].ZONE_ID;

            if (zone != config.zone_id){
              Sunstone.getDialog(CONFIRM_DIALOG_ID).setParams({
                header : Locale.tr("Error"),
                body : Locale.tr(
                  "This MarketPlace App resides in Zone ") +
                  zone + " (" + OpenNebula.Zone.getName(zone) + ")" +
                  Locale.tr(". To delete it you need to switch to that Zone from the zone selector in the top-right corner." ),
                question : "",
                buttons : [
                  Locale.tr("Ok"),
                ],
                submit : [
                  function(){
                    $("a#zonelector").focus().click();
                    return false;
                  }
                ]
              });

              Sunstone.getDialog(CONFIRM_DIALOG_ID).reset();
              Sunstone.getDialog(CONFIRM_DIALOG_ID).show();
            } else {
              _commonActions.del().call(params);
            }
          },
          error: Notifier.onError
        });
      },
      callback : _commonActions.del().callback,
      elements: _commonActions.del().elements,
      error: _commonActions.del().error,
      notify: _commonActions.del().notify
    },

    "MarketPlaceApp.chown": _commonActions.multipleAction('chown'),
    "MarketPlaceApp.chgrp": _commonActions.multipleAction('chgrp'),
    "MarketPlaceApp.chmod": _commonActions.singleAction('chmod'),
    "MarketPlaceApp.enable": _commonActions.multipleAction('enable'),
    "MarketPlaceApp.disable": _commonActions.multipleAction('disable'),
    //"MarketPlaceApp.update" : _commonActions.updateTemplate(),
    "MarketPlaceApp.update_template" : _commonActions.updateTemplate(),
    "MarketPlaceApp.append_template" : _commonActions.appendTemplate(),
    "MarketPlaceApp.rename": _commonActions.singleAction('rename')
  }

  return _actions;
});
<commit_msg>Fix marketplaceapp download url<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  var Sunstone = require('sunstone');
  var Notifier = require('utils/notifier');
  var Locale = require('utils/locale');
  var CommonActions = require('utils/common-actions');
  var OpenNebulaResource = require('opennebula/marketplaceapp');
  var OpenNebula = require('opennebula');
  var OpenNebulaAction = require('opennebula/action');

  var RESOURCE = "MarketPlaceApp";
  var XML_ROOT = "MARKETPLACEAPP";
  var TAB_ID = require('./tabId');
  var CREATE_DIALOG_ID = require('./form-panels/create/formPanelId');
  var EXPORT_DIALOG_ID = require('./form-panels/export/formPanelId');
  var CONFIRM_DIALOG_ID = require('utils/dialogs/generic-confirm/dialogId');

  var _commonActions = new CommonActions(OpenNebulaResource, RESOURCE, TAB_ID,
    XML_ROOT, Locale.tr("MarketPlace App created"));

  var _actions = {
    "MarketPlaceApp.create" : _commonActions.create(CREATE_DIALOG_ID),
    "MarketPlaceApp.create_dialog" : _commonActions.showCreate(CREATE_DIALOG_ID),
    "MarketPlaceApp.download_opennebula_dialog" : {
      type: "custom",
      call: function() {
        var selected_nodes = Sunstone.getDataTable(TAB_ID).elements();
        if (selected_nodes.length != 1) {
          Notifier.notifyMessage("Please select one (and just one) app to export.");
          return false;
        }

        var resourceId = "" + selected_nodes[0];

        Sunstone.resetFormPanel(TAB_ID, EXPORT_DIALOG_ID);
        Sunstone.showFormPanel(TAB_ID, EXPORT_DIALOG_ID, "export",
          function(formPanelInstance, context) {
            formPanelInstance.setResourceId(context, resourceId);
          });
      }
    },
    "MarketPlaceApp.export" : {
      type: "multiple",
      call: OpenNebulaResource.export,
      callback: function(req, response) {
        if (response['IMAGE'] !== undefined) {
          $.each(response['IMAGE'], function(i, image) {
            if (image.error != undefined){
              Notifier.notifyError(image.error.message);
            } else {
              Notifier.notifyCustom(Locale.tr("Image created"), " ID: " + image.ID, false);
            }
          });
        };

        if (response['VMTEMPLATE'] !== undefined) {
          $.each(response['VMTEMPLATE'], function(i, vmTemplate) {
            if (vmTemplate.error != undefined) {
              Notifier.notifyError(vmTemplate.error.message);
            } else if (vmTemplate.ID != -1) {
              Notifier.notifyCustom(Locale.tr("VM Template created"), " ID: " + vmTemplate.ID, false);
            }
          });
        };

        Sunstone.hideFormPanel(TAB_ID);
        OpenNebulaAction.clear_cache("IMAGE");
        OpenNebulaAction.clear_cache("VMTEMPLATE");
      },
      elements: function(opts) {
        return Sunstone.getDataTable(TAB_ID).elements(opts);
      },
      error: function(request, response){
        // without tab id param to work for both templates and vms tab
        Sunstone.hideFormPanelLoading();
        Notifier.onError(request, response);
      },
      notify: true
    },
    "MarketPlaceApp.download_local": {
      type: "multiple",
      call: function(params) {
        var selected_nodes = Sunstone.getDataTable(TAB_ID).elements();

        $.each(selected_nodes, function() {
          window.open("/marketplaceapp/"+this+"/download?csrftoken="+csrftoken, "_blank");
        });
      },
      elements: function(opts) {
        return Sunstone.getDataTable(TAB_ID).elements(opts);
      },
      error: Notifier.onError
    },
    "MarketPlaceApp.list" : _commonActions.list(),
    "MarketPlaceApp.show" : _commonActions.show(),
    "MarketPlaceApp.refresh" : _commonActions.refresh(),

    "MarketPlaceApp.delete" : {
      type: "multiple",
      call : function(params){
        OpenNebulaResource.show({
          data : {
              id: params.data.id
          },
          success: function(request,app_json){
            var zone = app_json[XML_ROOT].ZONE_ID;

            if (zone != config.zone_id){
              Sunstone.getDialog(CONFIRM_DIALOG_ID).setParams({
                header : Locale.tr("Error"),
                body : Locale.tr(
                  "This MarketPlace App resides in Zone ") +
                  zone + " (" + OpenNebula.Zone.getName(zone) + ")" +
                  Locale.tr(". To delete it you need to switch to that Zone from the zone selector in the top-right corner." ),
                question : "",
                buttons : [
                  Locale.tr("Ok"),
                ],
                submit : [
                  function(){
                    $("a#zonelector").focus().click();
                    return false;
                  }
                ]
              });

              Sunstone.getDialog(CONFIRM_DIALOG_ID).reset();
              Sunstone.getDialog(CONFIRM_DIALOG_ID).show();
            } else {
              _commonActions.del().call(params);
            }
          },
          error: Notifier.onError
        });
      },
      callback : _commonActions.del().callback,
      elements: _commonActions.del().elements,
      error: _commonActions.del().error,
      notify: _commonActions.del().notify
    },

    "MarketPlaceApp.chown": _commonActions.multipleAction('chown'),
    "MarketPlaceApp.chgrp": _commonActions.multipleAction('chgrp'),
    "MarketPlaceApp.chmod": _commonActions.singleAction('chmod'),
    "MarketPlaceApp.enable": _commonActions.multipleAction('enable'),
    "MarketPlaceApp.disable": _commonActions.multipleAction('disable'),
    //"MarketPlaceApp.update" : _commonActions.updateTemplate(),
    "MarketPlaceApp.update_template" : _commonActions.updateTemplate(),
    "MarketPlaceApp.append_template" : _commonActions.appendTemplate(),
    "MarketPlaceApp.rename": _commonActions.singleAction('rename')
  }

  return _actions;
});
<|endoftext|>


<commit_before>/*! CanvasTextWrapper (https://github.com/namniak/CanvasTextWrapper)
 *  Version:  0.1.0
 *
 *  MIT License (http://www.opensource.org/licenses/mit-license.html)
 *  Copyright (c) 2014 Vadim Namniak
 */
!function(){"use strict";var a={font:"18px Arial, sans-serif",textAlign:"left",verticalAlign:"top",paddingX:0,paddingY:0,fitParent:!1,lineBreak:"auto"};window.CanvasTextWrapper=function(b,c,d){if(!(this instanceof CanvasTextWrapper))throw new TypeError('CanvasTextWrapper constructor failed. Use "new" keyword when instantiating.');this.canvas=b,this.text=c;for(var e in a)this[e]=d&&d[e]?d[e]:a[e];this.lineHeight=parseInt(this.font.replace(/^\D+/g,""),10),this.validate(),this.context=this.canvas.getContext("2d"),this.context.font=this.font,this.context.textBaseline="bottom",this.drawText()},CanvasTextWrapper.prototype={drawText:function(){var a=this.canvas,b=a.getContext("2d"),c=this.fitParent===!1?a.width:a.parentNode.clientWidth,d=c-2*this.paddingX,e=this.text.split(/\s+/),f=[],g={x:0,y:0};this.checkWordsLength(b,e,d),this.breakTextIntoLines(b,f,e,d);var h=f.length*this.lineHeight;this.setTextVerticalAlign(g,h);for(var i=0;i<f.length;i++)this.setTextHorizontalAlign(b,g,c,f[i]),g.y=parseInt(g.y)+parseInt(this.lineHeight),b.fillText(f[i],g.x,g.y)},checkWordsLength:function(a,b,c){for(var d=0;d<b.length;d++){var e="",f=a.measureText(b[d]).width;if(f>c){for(var g=0;a.measureText(e+b[d][g]).width<=c&&g<b[d].length;g++)e+=b[d][g];var h=b[d].slice(0,g),i=b[d].slice(g);b.splice(d,1,h,i)}}},breakTextIntoLines:function(a,b,c,d){for(var e=0,f=0;e<c.length;f++)if(b[f]="","auto"===this.lineBreak){for(;a.measureText(b[f]+c[e]).width<=d&&e<c.length;)b[f]+=c[e]+" ",e++;b[f]=b[f].trim()}else"word"===this.lineBreak&&(b[f]=c[e],e++)},setTextHorizontalAlign:function(a,b,c,d){b.x="center"===this.textAlign?(c-a.measureText(d).width)/2:"right"===this.textAlign?c-a.measureText(d).width-this.paddingX:this.paddingX},setTextVerticalAlign:function(a,b){var c=this.fitParent===!1?this.canvas.height:this.canvas.parentNode.clientHeight;a.y="middle"===this.verticalAlign?(c-b)/2:"bottom"===this.verticalAlign?c-b-this.paddingY:this.paddingY},validate:function(){if(!(this.canvas instanceof HTMLCanvasElement))throw new TypeError("From CanvasTextWrapper(): Element passed as the first parameter is not an instance of HTMLCanvasElement.");if("string"!=typeof this.text)throw new TypeError("From CanvasTextWrapper(): The second, dedicated for the text, parameter must be a string.");if(isNaN(this.lineHeight))throw new TypeError('From CanvasTextWrapper(): Cannot parse font size as an Integer. Check "font" property\'s value.');if("left"!==this.textAlign&&"center"!==this.textAlign&&"right"!==this.textAlign)throw new TypeError('From CanvasTextWrapper(): Unsupported horizontal align value is used. Property "textAlign" can only be set to "left", "center", or "right".');if("top"!==this.verticalAlign&&"middle"!==this.verticalAlign&&"bottom"!==this.verticalAlign)throw new TypeError('From CanvasTextWrapper(): Unsupported vertical align value is used. Property "verticalAlign" can only be set to "top", "middle", or "bottom".');if(isNaN(this.paddingX))throw new TypeError('From CanvasTextWrapper(): Unsupported horizontal padding value is used. Property "paddingX" must be set to a number');if(isNaN(this.paddingY))throw new TypeError('From CanvasTextWrapper(): Unsupported vertical padding value is used. Property "paddingY" must be set to a number.');if("boolean"!=typeof this.fitParent)throw new TypeError('From CanvasTextWrapper(): Property "fitParent" must be set to a Boolean.');if("auto"!==this.lineBreak&&"word"!==this.lineBreak)throw new TypeError('From CanvasTextWrapper(): Unsupported line break value is used. Property "lineBreak" can only be set to "auto", or "word".')}}}();<commit_msg>Delete CanvasTextWrapper.min.js<commit_after><|endoftext|>


<commit_before>var request = require('superagent');

module.exports = function(endpoint) {
	return function(req, res, next) {
		console.log('Forwarding request', req.params, req.body, req.headers);
		request(req.method, endpoint + req.params.path)
			.set(req.headers)
			.send(req.body)
			.end( function(err, resBackend) {
				if(err) {
					if(err.status > 100 && err.status < 999) {
						console.log('Error forwarding request', err);
						res.status(err.status);
					}
					else {
						console.log('Encountered weird response code', err);
						res.status(500);
					}
				}
				else {
					//console.log(res);
					res.send(resBackend);
				}
			});
	}
}<commit_msg>whoops.<commit_after>var request = require('superagent');

module.exports = function(endpoint) {
	return function(req, res, next) {
		console.log('Forwarding request', req.params, req.body, req.headers);
		request(req.method, endpoint + req.params.path)
			.set(req.headers)
			.send(req.body)
			.end( function(err, resBackend) {
				if(err) {
					if(err.status > 100 && err.status < 999) {
						console.log('Error forwarding request', err);
						res.status(err.status).send();
					}
					else {
						console.log('Encountered weird response code', err);
						res.status(500).send();
					}
				}
				else {
					//console.log(res);
					res.send(resBackend);
				}
			});
	}
}<|endoftext|>


<commit_before>/* @flow */

import Logger from 'jitsi-meet-logger';

import { APP_WILL_MOUNT } from '../../app';
import JitsiMeetJS, { LIB_WILL_INIT } from '../lib-jitsi-meet';
import { MiddlewareRegistry } from '../redux';

import JitsiMeetLogStorage from '../../../../modules/util/JitsiMeetLogStorage';

import { SET_LOGGING_CONFIG } from './actionTypes';

declare var APP: Object;

/**
 * The Redux middleware of the feature base/logging.
 *
 * @param {Store} store - The Redux store.
 * @returns {Function}
 * @private
 */
MiddlewareRegistry.register(store => next => action => {
    switch (action.type) {
    case APP_WILL_MOUNT:
        return _appWillMount(store, next, action);

    case LIB_WILL_INIT:
        return _libWillInit(store, next, action);

    case SET_LOGGING_CONFIG:
        return _setLoggingConfig(store, next, action);
    }

    return next(action);
});

/**
 * Notifies the feature base/logging that the action {@link APP_WILL_MOUNT} is
 * being dispatched within a specific Redux {@code store}.
 *
 * @param {Store} store - The Redux store in which the specified {@code action}
 * is being dispatched.
 * @param {Dispatch} next - The Redux {@code dispatch} function to dispatch the
 * specified {@code action} to the specified {@code store}.
 * @param {Action} action - The Redux action {@code APP_WILL_MOUNT} which is
 * being dispatched in the specified {@code store}.
 * @private
 * @returns {Object} The new state that is the result of the reduction of the
 * specified {@code action}.
 */
function _appWillMount({ getState }, next, action) {
    const { config } = getState()['features/base/logging'];

    _setLogLevels(Logger, config);

    // FIXME Until the logic of conference.js is rewritten into the React
    // app we, JitsiMeetJS.init is to not be used for the React app.
    // Consequently, LIB_WILL_INIT will not be dispatched. In the meantime, do
    // the following:
    typeof APP === 'undefined' || _setLogLevels(JitsiMeetJS, config);

    return next(action);
}

/**
 * Initializes logging in the app.
 *
 * @param {Object} loggingConfig - The configuration with which logging is to be
 * initialized.
 * @private
 * @returns {void}
 */
function _initLogging(loggingConfig) {
    // Create the LogCollector and register it as the global log transport. It
    // is done early to capture as much logs as possible. Captured logs will be
    // cached, before the JitsiMeetLogStorage gets ready (statistics module is
    // initialized).
    if (typeof APP === 'object'
            && !APP.logCollector
            && !loggingConfig.disableLogCollector) {
        APP.logCollector = new Logger.LogCollector(new JitsiMeetLogStorage());
        Logger.addGlobalTransport(APP.logCollector);
        JitsiMeetJS.addGlobalLogTransport(APP.logCollector);
    }
}

/**
 * Notifies the feature base/logging that the action {@link LIB_WILL_INIT} is
 * being dispatched within a specific Redux {@code store}.
 *
 * @param {Store} store - The Redux store in which the specified {@code action}
 * is being dispatched.
 * @param {Dispatch} next - The Redux {@code dispatch} function to dispatch the
 * specified {@code action} to the specified {@code store}.
 * @param {Action} action - The Redux action {@code LIB_WILL_INIT} which is
 * being dispatched in the specified {@code store}.
 * @private
 * @returns {Object} The new state that is the result of the reduction of the
 * specified {@code action}.
 */
function _libWillInit({ getState }, next, action) {
    _setLogLevels(JitsiMeetJS, getState()['features/base/logging'].config);

    return next(action);
}

/**
 * Notifies the feature base/logging that the action {@link SET_LOGGING_CONFIG}
 * is being dispatched within a specific Redux {@code store}.
 *
 * @param {Store} store - The Redux store in which the specified {@code action}
 * is being dispatched.
 * @param {Dispatch} next - The Redux {@code dispatch} function to dispatch the
 * specified {@code action} to the specified {@code store}.
 * @param {Action} action - The Redux action {@code SET_LOGGING_CONFIG} which is
 * being dispatched in the specified {@code store}.
 * @private
 * @returns {Object} The new state that is the result of the reduction of the
 * specified {@code action}.
 */
function _setLoggingConfig({ getState }, next, action) {
    const oldValue = getState()['features/base/logging'].config;
    const result = next(action);
    const newValue = getState()['features/base/logging'].config;

    if (oldValue !== newValue) {
        _setLogLevels(Logger, newValue);
        _setLogLevels(JitsiMeetJS, newValue);

        _initLogging(newValue);
    }

    return result;
}

/**
 * Sets the log levels of {@link Logger} or {@link JitsiMeetJS} in accord with
 * a specific configuration.
 *
 * @param {Object} logger - The object on which the log levels are to be set.
 * @param {Object} config - The configuration specifying the log levels to be
 * set on {@code Logger} or {@code JitsiMeetJS}.
 * @private
 * @returns {void}
 */
function _setLogLevels(logger, config) {
    // XXX The loggers of the library lib-jitsi-meet and the application
    // jitsi-meet are separate, so the log levels have to be set in both.

    // First, set the default log level.
    logger.setLogLevel(config.defaultLogLevel);

    // Second, set the log level of each logger explictly overriden by config.
    Object.keys(config).forEach(
        id =>
            id === 'defaultLogLevel' || logger.setLogLevelById(config[id], id));
}
<commit_msg>Fixes sending logs to callstats.<commit_after>/* @flow */

import Logger from 'jitsi-meet-logger';

import { APP_WILL_MOUNT } from '../../app';
import JitsiMeetJS, { LIB_WILL_INIT } from '../lib-jitsi-meet';
import { MiddlewareRegistry } from '../redux';

import JitsiMeetLogStorage from '../../../../modules/util/JitsiMeetLogStorage';

import { SET_LOGGING_CONFIG } from './actionTypes';

declare var APP: Object;

/**
 * The Redux middleware of the feature base/logging.
 *
 * @param {Store} store - The Redux store.
 * @returns {Function}
 * @private
 */
MiddlewareRegistry.register(store => next => action => {
    switch (action.type) {
    case APP_WILL_MOUNT:
        return _appWillMount(store, next, action);

    case LIB_WILL_INIT:
        return _libWillInit(store, next, action);

    case SET_LOGGING_CONFIG:
        return _setLoggingConfig(store, next, action);
    }

    return next(action);
});

/**
 * Notifies the feature base/logging that the action {@link APP_WILL_MOUNT} is
 * being dispatched within a specific Redux {@code store}.
 *
 * @param {Store} store - The Redux store in which the specified {@code action}
 * is being dispatched.
 * @param {Dispatch} next - The Redux {@code dispatch} function to dispatch the
 * specified {@code action} to the specified {@code store}.
 * @param {Action} action - The Redux action {@code APP_WILL_MOUNT} which is
 * being dispatched in the specified {@code store}.
 * @private
 * @returns {Object} The new state that is the result of the reduction of the
 * specified {@code action}.
 */
function _appWillMount({ getState }, next, action) {
    const { config } = getState()['features/base/logging'];

    _setLogLevels(Logger, config);

    // FIXME Until the logic of conference.js is rewritten into the React
    // app we, JitsiMeetJS.init is to not be used for the React app.
    // Consequently, LIB_WILL_INIT will not be dispatched. In the meantime, do
    // the following:
    typeof APP === 'undefined' || _setLogLevels(JitsiMeetJS, config);

    return next(action);
}

/**
 * Initializes logging in the app.
 *
 * @param {Object} loggingConfig - The configuration with which logging is to be
 * initialized.
 * @private
 * @returns {void}
 */
function _initLogging(loggingConfig) {
    // Create the LogCollector and register it as the global log transport. It
    // is done early to capture as much logs as possible. Captured logs will be
    // cached, before the JitsiMeetLogStorage gets ready (statistics module is
    // initialized).
    if (typeof APP === 'object'
            && !APP.logCollector
            && !loggingConfig.disableLogCollector) {
        APP.logCollector = new Logger.LogCollector(new JitsiMeetLogStorage());
        Logger.addGlobalTransport(APP.logCollector);
        JitsiMeetJS.addGlobalLogTransport(APP.logCollector);
    }
}

/**
 * Notifies the feature base/logging that the action {@link LIB_WILL_INIT} is
 * being dispatched within a specific Redux {@code store}.
 *
 * @param {Store} store - The Redux store in which the specified {@code action}
 * is being dispatched.
 * @param {Dispatch} next - The Redux {@code dispatch} function to dispatch the
 * specified {@code action} to the specified {@code store}.
 * @param {Action} action - The Redux action {@code LIB_WILL_INIT} which is
 * being dispatched in the specified {@code store}.
 * @private
 * @returns {Object} The new state that is the result of the reduction of the
 * specified {@code action}.
 */
function _libWillInit({ getState }, next, action) {
    _setLogLevels(JitsiMeetJS, getState()['features/base/logging'].config);

    return next(action);
}

/**
 * Notifies the feature base/logging that the action {@link SET_LOGGING_CONFIG}
 * is being dispatched within a specific Redux {@code store}.
 *
 * @param {Store} store - The Redux store in which the specified {@code action}
 * is being dispatched.
 * @param {Dispatch} next - The Redux {@code dispatch} function to dispatch the
 * specified {@code action} to the specified {@code store}.
 * @param {Action} action - The Redux action {@code SET_LOGGING_CONFIG} which is
 * being dispatched in the specified {@code store}.
 * @private
 * @returns {Object} The new state that is the result of the reduction of the
 * specified {@code action}.
 */
function _setLoggingConfig({ getState }, next, action) {
    const result = next(action);
    const newValue = getState()['features/base/logging'].config;

    // TODO Generally, we'll want to _setLogLevels and _initLogging only if the
    // logging config values actually change.
    // XXX Unfortunately, we don't currently have a (nice) way of determining
    // whether _setLogLevels or _initLogging have been invoked so we have to
    // invoke them unconditionally even if none of the values have actually
    // changed.
    _setLogLevels(Logger, newValue);
    _setLogLevels(JitsiMeetJS, newValue);

    _initLogging(newValue);

    return result;
}

/**
 * Sets the log levels of {@link Logger} or {@link JitsiMeetJS} in accord with
 * a specific configuration.
 *
 * @param {Object} logger - The object on which the log levels are to be set.
 * @param {Object} config - The configuration specifying the log levels to be
 * set on {@code Logger} or {@code JitsiMeetJS}.
 * @private
 * @returns {void}
 */
function _setLogLevels(logger, config) {
    // XXX The loggers of the library lib-jitsi-meet and the application
    // jitsi-meet are separate, so the log levels have to be set in both.

    // First, set the default log level.
    logger.setLogLevel(config.defaultLogLevel);

    // Second, set the log level of each logger explictly overriden by config.
    Object.keys(config).forEach(
        id =>
            id === 'defaultLogLevel' || logger.setLogLevelById(config[id], id));
}
<|endoftext|>


<commit_before>import Session from '../session';
Session.setSession();
window.location.replace(document.location.hostname);
<commit_msg>redirect from test<commit_after>import Session from '../session';
Session.setSession();
let redirect = window.location.protocol + "//" + window.location.hostname;
window.location.href = (redirect === "http://127.0.0.1")? redirect+":5000":redirect;
<|endoftext|>


<commit_before>/**********************************************************************************
 * $URL$
 * $Id$
 ***********************************************************************************
 *
 * Copyright (c) 2007 The Sakai Foundation.
 *
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 *
 * 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.
 *
 **********************************************************************************/

// functions for Sludge applications

function setMainFrameHeightFancy(id)
{
	// only if we have a parent with an element by our id
	if (parent && parent.document && parent.document.getElementById(id))
	{
		// reset the scroll
		parent.window.scrollTo(0,0);

		// the frame is in a parent window this high
		var windowHeight = parent.window.innerHeight;

		// the parent's content is taking this height
		var parentContentHeight= parent.document.body.offsetHeight;

		// if the parent's content is larger than its window, we need the overall scroll for the portal
		if (parentContentHeight > windowHeight)
		{
			// if we have a menu, it is this high
			var menuHeight  = 0;
			if (document.getElementById('sludge_menu'))
			{
				menuHeight = document.getElementById('sludge_menu').offsetHeight;
			}

			// if we have buttons, they are this high
			var buttonsHeight = 0;
			if (document.getElementById('sludge_buttons'))
			{
				buttonsHeight = document.getElementById('sludge_buttons').offsetHeight;
			}

			// if we have guts, they are this high
			var gutsHeight = 0;
			if (document.getElementById('sludge_guts'))
			{
				gutsHeight = document.getElementById('sludge_guts').offsetHeight;
			}

			var ourHeight = menuHeight + buttonsHeight + gutsHeight;

			// set our frame height
			parent.document.getElementById(id).style.height = ourHeight + "px";
		}

		// otherwise we can expand and do inner-scrolling in our guts
		else
		{
			// the frame starts this far down from the top
			var frameTop = parent.document.getElementById(id).offsetTop;

			// the parent needs this footer area reserved at the bottom
			var footerHeight = 0;
			if (parent.document.getElementById('footer'))
			{
				footerHeight = parent.document.getElementById('footer').offsetHeight + 50;
			}

			// we can extend down from our top to the bottom, leaving room for the footer
			var newHeight = windowHeight - frameTop - footerHeight;
			if (newHeight < 1) newHeight = 1;

			// set our frame height
			parent.document.getElementById(id).style.height = newHeight + "px";

			// adjust the guts of our display to fill it between the menu and buttons
			setGutsHeight(newHeight);
		}
	}

	// otherwise just adjust the guts of our display to fill it between the menu and buttons
	else
	{
		setGutsHeight(window.innerHeight);
	}
}

function setGutsHeight(frameHeight)
{
	// if we have a menu, it is this high
	var menuHeight  = 0;
	if (document.getElementById('sludge_menu'))
	{
		menuHeight = document.getElementById('sludge_menu').offsetHeight;
	}

	// if we have buttons, they are this high
	var buttonsHeight = 0;
	if (document.getElementById('sludge_buttons'))
	{
		buttonsHeight = document.getElementById('sludge_buttons').offsetHeight;
	}

	// the guts can then fill the frame
	var gutsHeight = frameHeight - menuHeight - buttonsHeight;
	if (gutsHeight < 1) gutsHeight = 1;

	// resize the guts and reset its scroll
	if (document.getElementById('sludge_guts'))
	{
		document.getElementById('sludge_guts').style.height=gutsHeight + "px";
		document.getElementById('sludge_guts').scrollTop=0;
	}
}

function trim(s)
{
	return s.replace(/^\s+/g, "").replace(/\s+$/g, "");
}
<commit_msg>removed the sludge js<commit_after><|endoftext|>


<commit_before>module.exports = {
  title: 'Icon badge',
  label: 'Icon badge',
  context: {
    action: 'Read',
    icon: 'quote'
  },
  variants: [
    {
      name: 'small',
      context: {
        action: 'Show more',
        icon: 'plus-thin',
        modifiers: ['small']
      }
    },
    {
      name: 'light',
      context: {
        action: 'More events',
        icon: 'plus-thin',
        modifiers: ['light']
      }
    },
    {
      name: 'themed',
      context: {
        action: 'Show more',
        icon: 'plus',
        themed: ['background-color', 'background-color--hover']
      }
    },
    {
      name: 'short icon',
      context: {
        action: 'view',
        icon: 'view',
        modifiers: ['short']
      }
    }
  ]
};
<commit_msg>fix refs to old svg icons<commit_after>module.exports = {
  title: 'Icon badge',
  label: 'Icon badge',
  context: {
    action: 'Read',
    icon: 'quote'
  },
  variants: [
    {
      name: 'small',
      context: {
        action: 'Show more',
        icon: 'plus',
        modifiers: ['small']
      }
    },
    {
      name: 'light',
      context: {
        action: 'More events',
        icon: 'plus',
        modifiers: ['light']
      }
    },
    {
      name: 'themed',
      context: {
        action: 'Show more',
        icon: 'plus',
        themed: ['background-color', 'background-color--hover']
      }
    },
    {
      name: 'short icon',
      context: {
        action: 'view',
        icon: 'view',
        modifiers: ['short']
      }
    }
  ]
};
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ActionMenu from '../ActionMenu';
import { EditButton, ReadItNowButton } from '../IconButton';
import Permissioned from '../Permissioned';
import { PERMISSION_ADMIN } from '../../../lib/auth';
import SVGAndCSVMenu from '../SVGAndCSVMenu';
import { fetchStory } from '../../../actions/storyActions';
import DataCard from '../DataCard';
import StoryEntitiesContainer from '../story/StoryEntitiesContainer';
import StoryNytThemesContainer from '../story/StoryNytThemesContainer';
import messages from '../../../resources/messages';
import withAsyncFetch from '../hocs/AsyncContainer';
import { urlToTools } from '../../../lib/urlUtil';
import { TAG_SET_NYT_THEMES } from '../../../lib/tagUtil';
import { trimToMaxLength } from '../../../lib/stringUtil';
import { storyPubDateToTimestamp } from '../../../lib/dateUtil';
import StatBar from '../statbar/StatBar';

const localMessages = {
  title: { id: 'admin.story.title', defaultMessage: 'Story Info: ' },
  close: { id: 'admin.story.inContext.close', defaultMessage: 'Close' },
  readThisStory: { id: 'admin.story.readThisStory', defaultMessage: 'Read This Story' },
  editThisStory: { id: 'admin.story.editThisStory', defaultMessage: 'Edit This Story' },
  fullDescription: { id: 'admin.story.fullDescription', defaultMessage: 'Published in {media} on {publishDate} in {language}' },
  published: { id: 'admin.story.published', defaultMessage: 'Published in {media}' },
  readCachedCopy: { id: 'admin.story.details.readCached', defaultMessage: 'Read Cached Text (admin only)' },
  viewCachedHtml: { id: 'admin.story.details.viewCachedHtml', defaultMessage: 'View Cached HTML (admin only)' },
  storyOptions: { id: 'admin.story.details.storyOptions', defaultMessage: 'Story Options' },
};

class SelectedStoryContainer extends React.Component {
  goToUpdateUrl = (storyId) => {
    window.location = `admin/story/${storyId}/update`;
  }

  goToCachedUrl = (storyId) => {
    window.location = `/admin/story/${storyId}/cached`;
  }

  downloadCsv = (storyId) => {
    window.location = `/api/admin/story/${storyId}/samples.csv`;
  }

  render() {
    const { selectedStory, selectedStoryId, handleStoryEditClick, handleStoryCachedTextClick } = this.props;
    const { formatDate, formatMessage } = this.props.intl;

    let content = null;
    if (selectedStoryId) {
      content = (

          <DataCard className="admin-story-view">
            <Row>
              <Col lg={12}>

                  <FormattedMessage {...localMessages.title} />
                  {trimToMaxLength(selectedStory.title, 80)}

                <ActionMenu actionTextMsg={localMessages.storyOptions}>
                  <MenuItem onClick={() => window.open(selectedStory.url, '_blank')}>
                    <ListItemText><FormattedMessage {...localMessages.readThisStory} /></ListItemText>
                    <ListItemIcon><ReadItNowButton /></ListItemIcon>
                  </MenuItem>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryCachedTextClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.readCachedCopy} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => window.open(`/api/stories/${selectedStoryId}/raw.html`, '_blank')}>
                      <ListItemText><FormattedMessage {...localMessages.viewCachedHtml} /></ListItemText>
                    </MenuItem>
                  </Permissioned>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryEditClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.editThisStory} /></ListItemText>
                      <ListItemIcon><EditButton tooltip={formatMessage(localMessages.editThisStory)} /></ListItemIcon>
                    </MenuItem>
                  </Permissioned>
                  <SVGAndCSVMenu downloadCsv={this.downloadCsv} />
                </ActionMenu>
              </Col>
            </Row>
            <Row>
              <Col lg={12}>
                <StatBar
                  columnWidth={2}
                  stats={[
                    { message: messages.sourceName,
                      data: (

                          {selectedStory.media_name || selectedStory.media.name}

                      ),
                    },
                    { message: messages.storyDate,
                      data: formatDate(storyPubDateToTimestamp(selectedStory.publish_date)),
                    },
                    { message: messages.language,
                      data: selectedStory.language ? selectedStory.language : '?',
                    },
                    { message: messages.mediaType,
                      data: selectedStory.media.metadata.media_type ? selectedStory.media.metadata.media_type.label : '?',
                      helpTitleMsg: messages.mediaTypeHelpTitle,
                      helpContentMsg: messages.mediaTypeHelpContent,
                    },
                    { message: messages.pubCountry,
                      data: selectedStory.media.metadata.pub_country ? selectedStory.media.metadata.pub_country.label : '?',
                    },
                    { message: messages.pubState,
                      data: selectedStory.media.metadata.pub_state ? selectedStory.media.metadata.pub_state.label : '?' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <StoryEntitiesContainer storyId={selectedStoryId} />
              </Col>
              <Col lg={3}>
                <StoryNytThemesContainer
                  storyId={selectedStoryId}
                  tags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id === TAG_SET_NYT_THEMES) : []}
                  hideFullListOption
                />
              </Col>
            </Row>
          </DataCard>

      );
    }
    return content;
  }
}

SelectedStoryContainer.propTypes = {
  // from parent
  asyncFetch: PropTypes.func.isRequired,
  // from store
  fetchStatus: PropTypes.string.isRequired,
  selectedStory: PropTypes.object.isRequired,
  selectedStoryId: PropTypes.number,
  // from context
  intl: PropTypes.object.isRequired,
  handleStoryCachedTextClick: PropTypes.func.isRequired,
  handleStoryEditClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.story.info.fetchStatus,
  selectedStory: state.story.info,
  selectedStoryId: parseInt(state.story.info.stories_id, 10),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  asyncFetch: () => {
    if (ownProps.params && ownProps.params.id !== undefined) {
      dispatch(fetchStory(parseInt(ownProps.params.id, 10)));
    }
  },
  handleStoryCachedTextClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/cached`));
  },
  handleStoryEditClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/update`));
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    withAsyncFetch(
      SelectedStoryContainer
    )
  )
);
<commit_msg>#1369 download<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ActionMenu from '../ActionMenu';
import { EditButton, ReadItNowButton } from '../IconButton';
import Permissioned from '../Permissioned';
import { PERMISSION_ADMIN } from '../../../lib/auth';
import SVGAndCSVMenu from '../SVGAndCSVMenu';
import { fetchStory } from '../../../actions/storyActions';
import DataCard from '../DataCard';
import StoryEntitiesContainer from '../story/StoryEntitiesContainer';
import StoryNytThemesContainer from '../story/StoryNytThemesContainer';
import messages from '../../../resources/messages';
import withAsyncFetch from '../hocs/AsyncContainer';
import { urlToTools } from '../../../lib/urlUtil';
import { TAG_SET_NYT_THEMES } from '../../../lib/tagUtil';
import { trimToMaxLength } from '../../../lib/stringUtil';
import { storyPubDateToTimestamp } from '../../../lib/dateUtil';
import StatBar from '../statbar/StatBar';

const localMessages = {
  title: { id: 'admin.story.title', defaultMessage: 'Story Info: ' },
  close: { id: 'admin.story.inContext.close', defaultMessage: 'Close' },
  readThisStory: { id: 'admin.story.readThisStory', defaultMessage: 'Read This Story' },
  editThisStory: { id: 'admin.story.editThisStory', defaultMessage: 'Edit This Story' },
  fullDescription: { id: 'admin.story.fullDescription', defaultMessage: 'Published in {media} on {publishDate} in {language}' },
  published: { id: 'admin.story.published', defaultMessage: 'Published in {media}' },
  readCachedCopy: { id: 'admin.story.details.readCached', defaultMessage: 'Read Cached Text (admin only)' },
  viewCachedHtml: { id: 'admin.story.details.viewCachedHtml', defaultMessage: 'View Cached HTML (admin only)' },
  storyOptions: { id: 'admin.story.details.storyOptions', defaultMessage: 'Story Options' },
};

class SelectedStoryContainer extends React.Component {
  goToUpdateUrl = (storyId) => {
    window.location = `admin/story/${storyId}/update`;
  }

  goToCachedUrl = (storyId) => {
    window.location = `/admin/story/${storyId}/cached`;
  }

  downloadCsv = (storyId) => {
    window.location = `/api/admin/story/${storyId}/samples.csv`;
  }

  render() {
    const { selectedStory, selectedStoryId, handleStoryEditClick, handleStoryCachedTextClick } = this.props;
    const { formatDate, formatMessage } = this.props.intl;

    let content = null;
    if (selectedStoryId) {
      content = (

          <DataCard className="admin-story-view">
            <Row>
              <Col lg={12}>

                  <FormattedMessage {...localMessages.title} />
                  {trimToMaxLength(selectedStory.title, 80)}

                <ActionMenu actionTextMsg={localMessages.storyOptions}>
                  <MenuItem onClick={() => window.open(selectedStory.url, '_blank')}>
                    <ListItemText><FormattedMessage {...localMessages.readThisStory} /></ListItemText>
                    <ListItemIcon><ReadItNowButton /></ListItemIcon>
                  </MenuItem>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryCachedTextClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.readCachedCopy} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => window.open(`/api/stories/${selectedStoryId}/raw.html`, '_blank')}>
                      <ListItemText><FormattedMessage {...localMessages.viewCachedHtml} /></ListItemText>
                    </MenuItem>
                  </Permissioned>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryEditClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.editThisStory} /></ListItemText>
                      <ListItemIcon><EditButton tooltip={formatMessage(localMessages.editThisStory)} /></ListItemIcon>
                    </MenuItem>
                  </Permissioned>
                  <SVGAndCSVMenu downloadCsv={() => this.downloadCsv(selectedStoryId)} />
                </ActionMenu>
              </Col>
            </Row>
            <Row>
              <Col lg={12}>
                <StatBar
                  columnWidth={2}
                  stats={[
                    { message: messages.sourceName,
                      data: (

                          {selectedStory.media_name || selectedStory.media.name}

                      ),
                    },
                    { message: messages.storyDate,
                      data: formatDate(storyPubDateToTimestamp(selectedStory.publish_date)),
                    },
                    { message: messages.language,
                      data: selectedStory.language ? selectedStory.language : '?',
                    },
                    { message: messages.mediaType,
                      data: selectedStory.media.metadata.media_type ? selectedStory.media.metadata.media_type.label : '?',
                      helpTitleMsg: messages.mediaTypeHelpTitle,
                      helpContentMsg: messages.mediaTypeHelpContent,
                    },
                    { message: messages.pubCountry,
                      data: selectedStory.media.metadata.pub_country ? selectedStory.media.metadata.pub_country.label : '?',
                    },
                    { message: messages.pubState,
                      data: selectedStory.media.metadata.pub_state ? selectedStory.media.metadata.pub_state.label : '?' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <StoryEntitiesContainer storyId={selectedStoryId} />
              </Col>
              <Col lg={3}>
                <StoryNytThemesContainer
                  storyId={selectedStoryId}
                  tags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id === TAG_SET_NYT_THEMES) : []}
                  hideFullListOption
                />
              </Col>
            </Row>
          </DataCard>

      );
    }
    return content;
  }
}

SelectedStoryContainer.propTypes = {
  // from parent
  asyncFetch: PropTypes.func.isRequired,
  // from store
  fetchStatus: PropTypes.string.isRequired,
  selectedStory: PropTypes.object.isRequired,
  selectedStoryId: PropTypes.number,
  // from context
  intl: PropTypes.object.isRequired,
  handleStoryCachedTextClick: PropTypes.func.isRequired,
  handleStoryEditClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.story.info.fetchStatus,
  selectedStory: state.story.info,
  selectedStoryId: parseInt(state.story.info.stories_id, 10),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  asyncFetch: () => {
    if (ownProps.params && ownProps.params.id !== undefined) {
      dispatch(fetchStory(parseInt(ownProps.params.id, 10)));
    }
  },
  handleStoryCachedTextClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/cached`));
  },
  handleStoryEditClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/update`));
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    withAsyncFetch(
      SelectedStoryContainer
    )
  )
);
<|endoftext|>


<commit_before>const isMobile = {
  Android: () => navigator.userAgent.match(/Android/i),
  BlackBerry: () => navigator.userAgent.match(/BlackBerry/i),
  iOS: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
  Opera: () => navigator.userAgent.match(/Opera Mini/i),
  Windows: () => navigator.userAgent.match(/IEMobile/i),
  any: () => (
    isMobile.Android() ||
    isMobile.BlackBerry() ||
    isMobile.iOS() ||
    isMobile.Opera() ||
    isMobile.Windows()
  )
};

const imageOverlayContainer = document.querySelector('.b-image-overlay__container');
const body = document.querySelector('body');
const figCaption = document.querySelector('.b-image-overlay__figcaption');

const offensiveConcealer = () => {
  if (document.querySelector('.b-image-overlay__preview-concealer')) {
    document.querySelector('.b-image-overlay__preview-concealer').onclick = (e) => {
      e.stopPropagation();
    };
    document.querySelector('.b-image-overlay__preview-concealer-button').onclick = (e) => {
      e.stopPropagation();
      document.querySelector('.b-image-overlay__preview--offensive').classList.remove('b-image-overlay__preview--offensive');
      document.querySelector('.b-image-overlay__preview-concealer').remove();
      document.querySelectorAll('.b-image-overlay__preview--hidden').forEach(el => el.classList.remove('b-image-overlay__preview--hidden'));
    };
  }
};

const openObjectOverlay = () => {
  imageOverlayContainer.classList.add('b-image-overlay__container--active');
  body.style.overflowY = 'hidden';
  body.style.position = 'fixed';
  const scrollY = window.pageYOffset;
  imageOverlayContainer.style.top = `${scrollY}px`;
  imageOverlayContainer.style.height = `${window.innerHeight}px`;
  if (window.innerWidth <= 1000 && isMobile.any()) {
    figCaption.style.marginBottom = `${screen.height - window.innerHeight}px`;
  } else {
    figCaption.style.marginBottom = '0px';
  }
  document.querySelector('.b-image-carousel__image-preview-container').focus();
};

const closeObjectOverlay = () => {
  document.querySelector('.b-image-overlay__container').classList.remove('b-image-overlay__container--active');
  document.querySelector('body').style.overflowY = 'auto';
  document.querySelector('body').style.position = 'relative';
};

const initObjectOverlay = () => {
  offensiveConcealer();

  if (document.querySelector('.b-image-overlay')) {
    document.querySelector('.b-image-overlay__close-container').onclick = () => closeObjectOverlay();

    window.addEventListener('resize', () => {
      imageOverlayContainer.style.height = `${window.innerHeight}px`;
      // what follows is a hack for mobile phone browsers, if this does not look good on desktop,
      // trust me it works on phones...
      if (window.innerWidth <= 1000 && isMobile.any()) {
        figCaption.style.marginBottom = `${screen.height - window.innerHeight}px`;
      } else {
        figCaption.style.marginBottom = '0px';
      }
    });

    window.addEventListener('keydown', (e) => {
      if (e.keyCode === 27) {
        if (!document.querySelector('.b-image-overlay').classList.contains('b-image-overlay--unfocus')) {
          closeObjectOverlay();
        } else {
          document.querySelector('.b-image-overlay').classList.remove('b-image-overlay--unfocus');
        }
      }

      if (
        !document.querySelector('.b-image-overlay').classList.contains('b-image-overlay--unfocus') &&
        e.keyCode === 9
      ) {
        // stackoverflow answer 60031728
        const focusable = Array.from(document.querySelector('.b-image-overlay__content').querySelectorAll('button')).filter(
          el => !el.getAttribute('disabled')
        ).filter(
          el => !el.closest('.js-modal')
        );

        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        const shift = e.shiftKey;

        if (focusable.length) {
          if (shift && document.activeElement === first) {
            last.focus();
            e.preventDefault();
          } else if (!shift && document.activeElement === last) {
            first.focus();
            e.preventDefault();
          }
        }
      }
    });

    document.querySelector('.b-image-overlay').addEventListener('openObjectOverlay', openObjectOverlay);

    document.querySelector('.b-image-overlay__container').addEventListener('jsModalOpen', () => {
      document.querySelector('.b-image-overlay__close-container').style.display = 'none';
    });

    document.querySelector('.b-image-overlay__container').addEventListener('jsModalClosed', () => {
      document.querySelector('.b-image-overlay__close-container').style.display = 'block';
    });

    Array.from(document.querySelectorAll('.b-image-overlay__preview')).forEach((el) => {
      el.onclick = (e) => {
        e.preventDefault();
        if (!e.target.classList.contains('b-image-overlay__preview--offensive')) {
          e.target.dispatchEvent(new CustomEvent('openObjectOverlay', { bubbles: true }));
        }
      };
    });
  }
};

initObjectOverlay();
<commit_msg>changing the body style modification when modal open<commit_after>const isMobile = {
  Android: () => navigator.userAgent.match(/Android/i),
  BlackBerry: () => navigator.userAgent.match(/BlackBerry/i),
  iOS: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
  Opera: () => navigator.userAgent.match(/Opera Mini/i),
  Windows: () => navigator.userAgent.match(/IEMobile/i),
  any: () => (
    isMobile.Android() ||
    isMobile.BlackBerry() ||
    isMobile.iOS() ||
    isMobile.Opera() ||
    isMobile.Windows()
  )
};

const imageOverlayContainer = document.querySelector('.b-image-overlay__container');
const body = document.querySelector('body');
const figCaption = document.querySelector('.b-image-overlay__figcaption');

const offensiveConcealer = () => {
  if (document.querySelector('.b-image-overlay__preview-concealer')) {
    document.querySelector('.b-image-overlay__preview-concealer').onclick = (e) => {
      e.stopPropagation();
    };
    document.querySelector('.b-image-overlay__preview-concealer-button').onclick = (e) => {
      e.stopPropagation();
      document.querySelector('.b-image-overlay__preview--offensive').classList.remove('b-image-overlay__preview--offensive');
      document.querySelector('.b-image-overlay__preview-concealer').remove();
      document.querySelectorAll('.b-image-overlay__preview--hidden').forEach(el => el.classList.remove('b-image-overlay__preview--hidden'));
    };
  }
};

const openObjectOverlay = () => {
  imageOverlayContainer.classList.add('b-image-overlay__container--active');
  body.style.overflowY = 'hidden';
  // body.style.position = 'fixed';
  const scrollY = window.pageYOffset;
  imageOverlayContainer.style.top = `${scrollY}px`;
  imageOverlayContainer.style.height = `${window.innerHeight}px`;
  if (window.innerWidth <= 1000 && isMobile.any()) {
    figCaption.style.marginBottom = `${screen.height - window.innerHeight}px`;
  } else {
    figCaption.style.marginBottom = '0px';
  }
  document.querySelector('.b-image-carousel__image-preview-container').focus();
};

const closeObjectOverlay = () => {
  document.querySelector('.b-image-overlay__container').classList.remove('b-image-overlay__container--active');
  document.querySelector('body').style.overflowY = 'auto';
  document.querySelector('body').style.position = 'relative';
};

const initObjectOverlay = () => {
  offensiveConcealer();

  if (document.querySelector('.b-image-overlay')) {
    document.querySelector('.b-image-overlay__close-container').onclick = () => closeObjectOverlay();

    window.addEventListener('resize', () => {
      imageOverlayContainer.style.height = `${window.innerHeight}px`;
      // what follows is a hack for mobile phone browsers, if this does not look good on desktop,
      // trust me it works on phones...
      if (window.innerWidth <= 1000 && isMobile.any()) {
        figCaption.style.marginBottom = `${screen.height - window.innerHeight}px`;
      } else {
        figCaption.style.marginBottom = '0px';
      }
    });

    window.addEventListener('keydown', (e) => {
      if (e.keyCode === 27) {
        if (!document.querySelector('.b-image-overlay').classList.contains('b-image-overlay--unfocus')) {
          closeObjectOverlay();
        } else {
          document.querySelector('.b-image-overlay').classList.remove('b-image-overlay--unfocus');
        }
      }

      if (
        !document.querySelector('.b-image-overlay').classList.contains('b-image-overlay--unfocus') &&
        e.keyCode === 9
      ) {
        // stackoverflow answer 60031728
        const focusable = Array.from(document.querySelector('.b-image-overlay__content').querySelectorAll('button')).filter(
          el => !el.getAttribute('disabled')
        ).filter(
          el => !el.closest('.js-modal')
        );

        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        const shift = e.shiftKey;

        if (focusable.length) {
          if (shift && document.activeElement === first) {
            last.focus();
            e.preventDefault();
          } else if (!shift && document.activeElement === last) {
            first.focus();
            e.preventDefault();
          }
        }
      }
    });

    document.querySelector('.b-image-overlay').addEventListener('openObjectOverlay', openObjectOverlay);

    document.querySelector('.b-image-overlay__container').addEventListener('jsModalOpen', () => {
      document.querySelector('.b-image-overlay__close-container').style.display = 'none';
    });

    document.querySelector('.b-image-overlay__container').addEventListener('jsModalClosed', () => {
      document.querySelector('.b-image-overlay__close-container').style.display = 'block';
    });

    Array.from(document.querySelectorAll('.b-image-overlay__preview')).forEach((el) => {
      el.onclick = (e) => {
        e.preventDefault();
        if (!e.target.classList.contains('b-image-overlay__preview--offensive')) {
          e.target.dispatchEvent(new CustomEvent('openObjectOverlay', { bubbles: true }));
        }
      };
    });
  }
};

initObjectOverlay();
<|endoftext|>


<commit_before>/*
Copyright 2019 The Matrix.org Foundation C.I.C.

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 * as sdk from '../../../index';
import {verificationMethods} from 'matrix-js-sdk/src/crypto';
import VerificationQRCode from "../elements/crypto/VerificationQRCode";
import {VerificationRequest} from "matrix-js-sdk/src/crypto/verification/request/VerificationRequest";
import {MatrixClientPeg} from "../../../MatrixClientPeg";

export default class VerificationPanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {};
        this._hasVerifier = !!props.request.verifier;
    }

    render() {
        return

                { this.renderStatus() }

;
    }

    renderStatus() {
        const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
        const Spinner = sdk.getComponent('elements.Spinner');
        const {request: req} = this.props;
        const request: VerificationRequest = req;

        if (request.requested) {
            return (
Waiting for {request.otherUserId} to accept ... <Spinner />
);
        } else if (request.ready) {
            const verifyButton = <AccessibleButton kind="primary" onClick={this._startSAS}>
                Verify by emoji
            </AccessibleButton>;

            const crossSigningInfo = MatrixClientPeg.get().getStoredCrossSigningForUser(request.otherUserId);
            const myKeyId = MatrixClientPeg.get().getCrossSigningId();
            if (request.requestEvent && request.requestEvent.getId() && crossSigningInfo) {
                const qrCodeKeys = [
                    [MatrixClientPeg.get().getDeviceId(), MatrixClientPeg.get().getDeviceEd25519Key()],
                    [myKeyId, MatrixClientPeg.get().getCrossSigningId()],
                ];
                const qrCode = <VerificationQRCode
                    keyholderUserId={MatrixClientPeg.get().getUserId()}
                    requestEventId={request.requestEvent.getId()}
                    otherUserKey={crossSigningInfo.getId("master")}
                    secret={request.encodedSharedSecret}
                    keys={qrCodeKeys}
                />;
                return (
{request.otherUserId} is ready, start {verifyButton} or have them scan: {qrCode}
);
            }

            return (
{request.otherUserId} is ready, start {verifyButton}
);
        } else if (request.started) {
            if (this.state.sasWaitingForOtherParty) {
                return
Waiting for {request.otherUserId} to confirm ...
;
            } else if (this.state.sasEvent) {
                const VerificationShowSas = sdk.getComponent('views.verification.VerificationShowSas');
                return (

                    <VerificationShowSas
                        sas={this.state.sasEvent.sas}
                        onCancel={this._onSasMismatchesClick}
                        onDone={this._onSasMatchesClick}
                    />

);
            } else {
                return (
Setting up SAS verification...
);
            }
        } else if (request.done) {
            return
verified {request.otherUserId}!!
;
        } else if (request.cancelled) {
            return
cancelled by {request.cancellingUserId}!
;
        }
    }

    _startSAS = async () => {
        const verifier = this.props.request.beginKeyVerification(verificationMethods.SAS);
        try {
            await verifier.verify();
        } catch (err) {
            console.error(err);
        } finally {
            this.setState({sasEvent: null});
        }
    };

    _onSasMatchesClick = () => {
        this.setState({sasWaitingForOtherParty: true});
        this.state.sasEvent.confirm();
    };

    _onSasMismatchesClick = () => {
        this.state.sasEvent.cancel();
    };

    _onVerifierShowSas = (sasEvent) => {
        this.setState({sasEvent});
    };

    _onRequestChange = async () => {
        const {request} = this.props;
        if (!this._hasVerifier && !!request.verifier) {
            request.verifier.on('show_sas', this._onVerifierShowSas);
            try {
                // on the requester side, this is also awaited in _startSAS,
                // but that's ok as verify should return the same promise.
                await request.verifier.verify();
            } catch (err) {
                console.error("error verify", err);
            }
        } else if (this._hasVerifier && !request.verifier) {
            request.verifier.removeListener('show_sas', this._onVerifierShowSas);
        }
        this._hasVerifier = !!request.verifier;
        this.forceUpdate();
    };

    componentDidMount() {
        this.props.request.on("change", this._onRequestChange);
    }

    componentWillUnmount() {
        this.props.request.off("change", this._onRequestChange);
    }
}
<commit_msg>less duplication<commit_after>/*
Copyright 2019 The Matrix.org Foundation C.I.C.

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 * as sdk from '../../../index';
import {verificationMethods} from 'matrix-js-sdk/src/crypto';
import VerificationQRCode from "../elements/crypto/VerificationQRCode";
import {VerificationRequest} from "matrix-js-sdk/src/crypto/verification/request/VerificationRequest";
import {MatrixClientPeg} from "../../../MatrixClientPeg";

export default class VerificationPanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {};
        this._hasVerifier = !!props.request.verifier;
    }

    render() {
        return

                { this.renderStatus() }

;
    }

    renderStatus() {
        const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
        const Spinner = sdk.getComponent('elements.Spinner');
        const {request: req} = this.props;
        const request: VerificationRequest = req;

        if (request.requested) {
            return (
Waiting for {request.otherUserId} to accept ... <Spinner />
);
        } else if (request.ready) {
            const verifyButton = <AccessibleButton kind="primary" onClick={this._startSAS}>
                Verify by emoji
            </AccessibleButton>;

            const crossSigningInfo = MatrixClientPeg.get().getStoredCrossSigningForUser(request.otherUserId);
            const myKeyId = MatrixClientPeg.get().getCrossSigningId();
            if (request.requestEvent && request.requestEvent.getId() && crossSigningInfo) {
                const qrCodeKeys = [
                    [MatrixClientPeg.get().getDeviceId(), MatrixClientPeg.get().getDeviceEd25519Key()],
                    [myKeyId, myKeyId],
                ];
                const qrCode = <VerificationQRCode
                    keyholderUserId={MatrixClientPeg.get().getUserId()}
                    requestEventId={request.requestEvent.getId()}
                    otherUserKey={crossSigningInfo.getId("master")}
                    secret={request.encodedSharedSecret}
                    keys={qrCodeKeys}
                />;
                return (
{request.otherUserId} is ready, start {verifyButton} or have them scan: {qrCode}
);
            }

            return (
{request.otherUserId} is ready, start {verifyButton}
);
        } else if (request.started) {
            if (this.state.sasWaitingForOtherParty) {
                return
Waiting for {request.otherUserId} to confirm ...
;
            } else if (this.state.sasEvent) {
                const VerificationShowSas = sdk.getComponent('views.verification.VerificationShowSas');
                return (

                    <VerificationShowSas
                        sas={this.state.sasEvent.sas}
                        onCancel={this._onSasMismatchesClick}
                        onDone={this._onSasMatchesClick}
                    />

);
            } else {
                return (
Setting up SAS verification...
);
            }
        } else if (request.done) {
            return
verified {request.otherUserId}!!
;
        } else if (request.cancelled) {
            return
cancelled by {request.cancellingUserId}!
;
        }
    }

    _startSAS = async () => {
        const verifier = this.props.request.beginKeyVerification(verificationMethods.SAS);
        try {
            await verifier.verify();
        } catch (err) {
            console.error(err);
        } finally {
            this.setState({sasEvent: null});
        }
    };

    _onSasMatchesClick = () => {
        this.setState({sasWaitingForOtherParty: true});
        this.state.sasEvent.confirm();
    };

    _onSasMismatchesClick = () => {
        this.state.sasEvent.cancel();
    };

    _onVerifierShowSas = (sasEvent) => {
        this.setState({sasEvent});
    };

    _onRequestChange = async () => {
        const {request} = this.props;
        if (!this._hasVerifier && !!request.verifier) {
            request.verifier.on('show_sas', this._onVerifierShowSas);
            try {
                // on the requester side, this is also awaited in _startSAS,
                // but that's ok as verify should return the same promise.
                await request.verifier.verify();
            } catch (err) {
                console.error("error verify", err);
            }
        } else if (this._hasVerifier && !request.verifier) {
            request.verifier.removeListener('show_sas', this._onVerifierShowSas);
        }
        this._hasVerifier = !!request.verifier;
        this.forceUpdate();
    };

    componentDidMount() {
        this.props.request.on("change", this._onRequestChange);
    }

    componentWillUnmount() {
        this.props.request.off("change", this._onRequestChange);
    }
}
<|endoftext|>


<commit_before>/*
Copyright 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 {_t} from "../../../../languageHandler";
import PropTypes from "prop-types";
import SettingsStore, {SettingLevel} from "../../../../settings/SettingsStore";
import MatrixClientPeg from "../../../../MatrixClientPeg";
import LabelledToggleSwitch from "../../elements/LabelledToggleSwitch";
const Modal = require("../../../../Modal");
const sdk = require("../../../../index");

export class LabsSettingToggle extends React.Component {
    static propTypes = {
        featureId: PropTypes.string.isRequired,
    };

    async _onLazyLoadChanging(enabling) {
        // don't prevent turning LL off when not supported
        if (enabling) {
            const supported = await MatrixClientPeg.get().doesServerSupportLazyLoading();
            if (!supported) {
                await new Promise((resolve) => {
                    const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
                    Modal.createDialog(QuestionDialog, {
                        title: _t("Lazy loading members not supported"),
                        description:

                                { _t("Lazy loading is not supported by your " +
                                    "current homeserver.") }

,
                        button: _t("OK"),
                        onFinished: resolve,
                    });
                });
                return false;
            }
        }
        return true;
    }

    _onChange = async (checked) => {
        await SettingsStore.setFeatureEnabled(this.props.featureId, checked);
        this.forceUpdate();
    };

    render() {
        const label = _t(SettingsStore.getDisplayName(this.props.featureId));
        const value = SettingsStore.isFeatureEnabled(this.props.featureId);
        return <LabelledToggleSwitch value={value} label={label} onChange={this._onChange} />;
    }
}

export default class LabsSettingsTab extends React.Component {
    constructor() {
        super();
    }

    render() {
        const SettingsFlag = sdk.getComponent("views.elements.SettingsFlag");
        const flags = SettingsStore.getLabsFeatures().map(f => <LabsSettingToggle featureId={f} key={f} />);
        return (

{_t("Labs")}

                    {flags}
                    <SettingsFlag name={"enableWidgetScreenshots"} level={SettingLevel.ACCOUNT} />

        );
    }
}
<commit_msg>remove homeserver ll check on toggling lab setting<commit_after>/*
Copyright 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 {_t} from "../../../../languageHandler";
import PropTypes from "prop-types";
import SettingsStore, {SettingLevel} from "../../../../settings/SettingsStore";
import MatrixClientPeg from "../../../../MatrixClientPeg";
import LabelledToggleSwitch from "../../elements/LabelledToggleSwitch";
const Modal = require("../../../../Modal");
const sdk = require("../../../../index");

export class LabsSettingToggle extends React.Component {
    static propTypes = {
        featureId: PropTypes.string.isRequired,
    };

    _onChange = async (checked) => {
        await SettingsStore.setFeatureEnabled(this.props.featureId, checked);
        this.forceUpdate();
    };

    render() {
        const label = _t(SettingsStore.getDisplayName(this.props.featureId));
        const value = SettingsStore.isFeatureEnabled(this.props.featureId);
        return <LabelledToggleSwitch value={value} label={label} onChange={this._onChange} />;
    }
}

export default class LabsSettingsTab extends React.Component {
    constructor() {
        super();
    }

    render() {
        const SettingsFlag = sdk.getComponent("views.elements.SettingsFlag");
        const flags = SettingsStore.getLabsFeatures().map(f => <LabsSettingToggle featureId={f} key={f} />);
        return (

{_t("Labs")}

                    {flags}
                    <SettingsFlag name={"enableWidgetScreenshots"} level={SettingLevel.ACCOUNT} />

        );
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010 Google Inc.
 *
 * 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.
 */

addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'getelementbyid_and_getelementsbyname',

chrome_comp.CompDetect.NonScanDomBaseDetector,

function constructor(rootNode) {
  var that = this;
  var ids;
  var commonNames;
  var namesOfEmbed;
  var namesOfFrameAndParam;

  this.getElementById_ = function(result, originalArguments, callStack) {
    var arg0 = originalArguments[0];
    var lowerCaseArg0 = arg0.toLowerCase();
    var lowerCaseIds = getIds();

    // Handle SD9002
    if (!result && lowerCaseIds.indexOf(lowerCaseArg0) >= 0) {
      addProblem('SD9002');
    }

    // Handle SD9001, document.getElementById(case-sensitive name)
    // Still works in IE67Q
    var names = getNames();
    if (!result && names.commonNames.concat(names.namesOfEmbed)
        .indexOf(lowerCaseArg0) >= 0) {
      // Caller is null when call document.getElementById() in window scope
      var caller = arguments.callee.caller.caller;
      // Filter jQuery
      if (!(caller && caller.caller && /jQuery/.test(caller.caller.caller)))
        addProblem('SD9001');
    }

    function addProblem(id) {
      that.addProblem(id, {
        nodes: [this],
        details: 'document.getElementById(' + arg0 + ')',
        needsStack: true,
        severityLevel: 3
      });
    }
  };

  // Handle SD9012
  this.getElementsByName_ = function(result, originalArguments, callStack) {
    var arg0 = originalArguments[0];
    var names = getNames();

    if (result.length == 0 && names.commonNames
        .concat(names.namesOfFrameAndParam).indexOf(arg0.toLowerCase()) >= 0) {
      that.addProblem('SD9012', {
        nodes: [this],
        details: 'document.getElementsByName(' + arg0 + ')',
        needsStack: true
      });
    }
  };

  // May has problem when updating document tree dynamically after window
  // loading
  // Get all elements with id attribute in the document
  function getIds() {
    if (!ids) {
      ids = [];
      var elements = document.querySelectorAll('[id]');
      Array.prototype.forEach.call(elements, function(element) {
        ids.push(element.getAttribute('id').toLowerCase());
      });
    }
    return ids;
  }

  // Get names of specified element in the document
  function getNames() {
    if (!commonNames) {
      commonNames = [];
      namesOfEmbed = [];
      namesOfFrameAndParam = [];

      var elements = document.querySelectorAll('[name]');
      var commonTags = ['A', 'APPLET', 'BUTTON', 'FORM', 'IFRAME', 'IMG',
          'INPUT', 'MAP', 'META', 'OBJECT', 'SELECT', 'TEXTAREA'];

      Array.prototype.forEach.call(elements, function(element) {
        var tagName = element.tagName;
        var name = element.getAttribute('name').toLowerCase();
        if (commonTags.indexOf(tagName) >= 0)
          commonNames.push(name);
        else if (tagName == 'EMBED')
          namesOfEmbed.push(name)
        else if (tagName == 'FRAME' || tagName == 'PARAM')
          namesOfFrameAndParam.push(name);
      });
    }
    return {
      'commonNames': commonNames,
      'namesOfEmbed': namesOfEmbed,
      'namesOfFrameAndParam': namesOfFrameAndParam
    };
  }
}, //constructor

function setUp() {
  chrome_comp.CompDetect.registerExistingMethodHook(
      Document.prototype, 'getElementById', this.getElementById_);
  chrome_comp.CompDetect.registerExistingMethodHook(
      Document.prototype, 'getElementsByName', this.getElementsByName_);
},

function cleanUp() {
  chrome_comp.CompDetect.unregisterExistingMethodHook(
      Document.prototype, 'getElementById', this.getElementById_);
  chrome_comp.CompDetect.unregisterExistingMethodHook(
      Document.prototype, 'getElementsByName', this.getElementsByName_);
}
); // declareDetector

});<commit_msg>加入非法值过滤 -- by qianbaokun<commit_after>/*
 * Copyright 2010 Google Inc.
 *
 * 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.
 */

addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'getelementbyid_and_getelementsbyname',

chrome_comp.CompDetect.NonScanDomBaseDetector,

function constructor(rootNode) {
  var that = this;
  var ids;
  var commonNames;
  var namesOfEmbed;
  var namesOfFrameAndParam;

  this.getElementById_ = function(result, originalArguments, callStack) {
    var arg0 = originalArguments[0];
    if (arg0 == undefined)
      return;
    var lowerCaseArg0 = arg0.toLowerCase();
    var lowerCaseIds = getIds();

    // Handle SD9002
    if (!result && lowerCaseIds.indexOf(lowerCaseArg0) >= 0) {
      addProblem('SD9002');
    }

    // Handle SD9001, document.getElementById(case-sensitive name)
    // Still works in IE67Q
    var names = getNames();
    if (!result && names.commonNames.concat(names.namesOfEmbed)
        .indexOf(lowerCaseArg0) >= 0) {
      // Caller is null when call document.getElementById() in window scope
      var caller = arguments.callee.caller.caller;
      // Filter jQuery
      if (!(caller && caller.caller && /jQuery/.test(caller.caller.caller)))
        addProblem('SD9001');
    }

    function addProblem(id) {
      that.addProblem(id, {
        nodes: [this],
        details: 'document.getElementById(' + arg0 + ')',
        needsStack: true,
        severityLevel: 3
      });
    }
  };

  // Handle SD9012
  this.getElementsByName_ = function(result, originalArguments, callStack) {
    var arg0 = originalArguments[0];
    var names = getNames();

    if (result.length == 0 && names.commonNames
        .concat(names.namesOfFrameAndParam).indexOf(arg0.toLowerCase()) >= 0) {
      that.addProblem('SD9012', {
        nodes: [this],
        details: 'document.getElementsByName(' + arg0 + ')',
        needsStack: true
      });
    }
  };

  // May has problem when updating document tree dynamically after window
  // loading
  // Get all elements with id attribute in the document
  function getIds() {
    if (!ids) {
      ids = [];
      var elements = document.querySelectorAll('[id]');
      Array.prototype.forEach.call(elements, function(element) {
        ids.push(element.getAttribute('id').toLowerCase());
      });
    }
    return ids;
  }

  // Get names of specified element in the document
  function getNames() {
    if (!commonNames) {
      commonNames = [];
      namesOfEmbed = [];
      namesOfFrameAndParam = [];

      var elements = document.querySelectorAll('[name]');
      var commonTags = ['A', 'APPLET', 'BUTTON', 'FORM', 'IFRAME', 'IMG',
          'INPUT', 'MAP', 'META', 'OBJECT', 'SELECT', 'TEXTAREA'];

      Array.prototype.forEach.call(elements, function(element) {
        var tagName = element.tagName;
        var name = element.getAttribute('name').toLowerCase();
        if (commonTags.indexOf(tagName) >= 0)
          commonNames.push(name);
        else if (tagName == 'EMBED')
          namesOfEmbed.push(name)
        else if (tagName == 'FRAME' || tagName == 'PARAM')
          namesOfFrameAndParam.push(name);
      });
    }
    return {
      'commonNames': commonNames,
      'namesOfEmbed': namesOfEmbed,
      'namesOfFrameAndParam': namesOfFrameAndParam
    };
  }
}, //constructor

function setUp() {
  chrome_comp.CompDetect.registerExistingMethodHook(
      Document.prototype, 'getElementById', this.getElementById_);
  chrome_comp.CompDetect.registerExistingMethodHook(
      Document.prototype, 'getElementsByName', this.getElementsByName_);
},

function cleanUp() {
  chrome_comp.CompDetect.unregisterExistingMethodHook(
      Document.prototype, 'getElementById', this.getElementById_);
  chrome_comp.CompDetect.unregisterExistingMethodHook(
      Document.prototype, 'getElementsByName', this.getElementsByName_);
}
); // declareDetector

});<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth.ruler',
  name: 'AddPasswordHistoryAction',
  documentation: 'Adds an entry into the status history of a transaction',

  implements: ['foam.nanos.ruler.RuleAction'],

  javaImports: [
    'foam.nanos.logger.Logger',
    'foam.nanos.auth.HistoricPassword',
    'foam.nanos.auth.User',
    'java.util.Date'
  ],

  constants: [
    {
      name: 'MAXIMUM_HISTORIC_PASSWORDS',
      type: 'Long',
      value: 10
    }
  ],

  methods: [
    {
      name: 'applyAction',
      javaCode: `
        User user = (User) obj;
        HistoricPassword[] historicPasswordsOld = user.getPasswordHistory();

        // compute how large the new array should be and where it should start copying from
        int newArrayLength = historicPasswordsOld.length + 1;
        int startCopyingIndex = 0;
        int copyLength = historicPasswordsOld.length;

        // only store up to the maximum number of password history records
        if (historicPasswordsOld.length >= MAXIMUM_HISTORIC_PASSWORDS) {
          newArrayLength = (int) MAXIMUM_HISTORIC_PASSWORDS;
          startCopyingIndex = 1;
          copyLength = (int) MAXIMUM_HISTORIC_PASSWORDS - 1;
        }

        // copy the old array into a new array
        HistoricPassword[] historicPasswordNew = new HistoricPassword[newArrayLength];
        System.arraycopy(historicPasswordsOld, startCopyingIndex, historicPasswordNew, 0, copyLength);

        // add the new entry to the end of the array
        HistoricPassword historicPassword = new HistoricPassword();
        historicPassword.setPassword(user.getPassword());
        historicPassword.setTimeStamp(new Date());
        historicPasswordNew[historicPasswordNew.length-1] = historicPassword;
        user.setPasswordHistory(historicPasswordNew);
      `
    }
  ]
});<commit_msg>Code review comments 001<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth.ruler',
  name: 'AddPasswordHistoryAction',
  documentation: 'Adds an entry into the password history of a user',

  implements: ['foam.nanos.ruler.RuleAction'],

  javaImports: [
    'foam.nanos.logger.Logger',
    'foam.nanos.auth.HistoricPassword',
    'foam.nanos.auth.User',
    'java.util.Date'
  ],

  constants: [
    {
      name: 'MAXIMUM_HISTORIC_PASSWORDS',
      type: 'Long',
      value: 10
    }
  ],

  methods: [
    {
      name: 'applyAction',
      javaCode: `
        User user = (User) obj;
        HistoricPassword[] historicPasswordsOld = user.getPasswordHistory();

        // compute how large the new array should be and where it should start copying from
        int newArrayLength = historicPasswordsOld.length + 1;
        int startCopyingIndex = 0;
        int copyLength = historicPasswordsOld.length;

        // only store up to the maximum number of password history records
        if (historicPasswordsOld.length >= MAXIMUM_HISTORIC_PASSWORDS) {
          newArrayLength = (int) MAXIMUM_HISTORIC_PASSWORDS;
          startCopyingIndex = 1;
          copyLength = (int) MAXIMUM_HISTORIC_PASSWORDS - 1;
        }

        // copy the old array into a new array
        HistoricPassword[] historicPasswordNew = new HistoricPassword[newArrayLength];
        System.arraycopy(historicPasswordsOld, startCopyingIndex, historicPasswordNew, 0, copyLength);

        // add the new entry to the end of the array
        HistoricPassword historicPassword = new HistoricPassword();
        historicPassword.setPassword(user.getPassword());
        historicPassword.setTimeStamp(new Date());
        historicPasswordNew[historicPasswordNew.length-1] = historicPassword;
        user.setPasswordHistory(historicPasswordNew);
      `
    }
  ]
});<|endoftext|>