hackedteam/rcs-console

View on GitHub
src/it/ht/rcs/console/system/view/nia/RuleForm.mxml

Summary

Maintainability
Test Coverage
<?xml version="1.0" encoding="utf-8"?>
<utils:TitleWindowSaveCancel xmlns:fx="http://ns.adobe.com/mxml/2009"
                             xmlns:s="library://ns.adobe.com/flex/spark"
                             xmlns:utils="it.ht.rcs.console.utils.*"
                             xmlns:mx="library://ns.adobe.com/flex/mx"
                             xmlns:itemfield="it.ht.rcs.console.utils.itemfield.*"
                             creationComplete="init()" creationPolicy="all" currentState="normal"
                             save="save()" title="{mode=='edit'? R.get('EDIT_RULE'): R.get('RULE_DUPLICATE')}">
  
  
  <fx:Script>
    <![CDATA[
      import it.ht.rcs.console.monitor.controller.LicenseManager;
      import it.ht.rcs.console.network.model.Injector;
      import it.ht.rcs.console.network.model.InjectorRule;
      import it.ht.rcs.console.utils.AlertPopUp;
      import it.ht.rcs.console.utils.itemfield.ItemFieldEvent;
      
      import locale.R;
      
      import mx.managers.PopUpManager;
      import mx.utils.StringUtil;
      
      [Bindable]
      public var rule:InjectorRule;
      public var injector:Injector;
      [Bindable]
      public var mode:String = 'edit';
      
      private var fileReference:FileReference;
      private var fileChanged:Boolean = false;
      
      [Bindable]
      private var _selectedTarget:Object;
      
      public function init():void
      {
        
        if (mode == 'create') {
          title=R.get('RULE_ADD')
          rule = new InjectorRule(InjectorRule.defaultInjectorRule());
          
        } else if (mode == 'edit' || mode=="duplicate") {
          
          title=mode=='edit'? R.get('EDIT_RULE'): R.get('RULE_DUPLICATE')
            
          ident.selectedItem = rule.ident;
          action.selectedItem = rule.action;
          
          if(ident.selectedItem=="TACTICAL")
          {
            ident_param.text="*"
            ident_param.enabled=false;
          }
          else{
            ident_param.enabled=true;
          }
          if(action.selectedItem=="INJECT-HTML-FLASH" )
          {
            resource.text="supported video sites"
            resource.enabled=false;
          }
          else{
            resource.text=rule.resource;
            resource.enabled=true;
          }
          
          
          if (rule.target_id && rule.target_id.length == 1 && rule.target_id[0])
          for each (var t:Object in target.dataProvider) {
            if (t._id == rule.target_id[0]) {
              target.selectedItemId = t._id;
              break;
            }
          }
          
          if (rule.action == 'REPLACE' || rule.action == 'INJECT-HTML-FILE') {
            
            if(mode=='edit')
            {
              currentState = 'fileSelected';
              fileName.text = rule.action_param_name;
            }
            
            if(mode=='duplicate')
            {
              currentState = 'normal';
              fileChanged = false
            }
            
           
            
          } else {
            
            for each (var b:Object in agent.dataProvider) {
              if (b._id == rule.action_param) {
                agent.selectedItemId = b._id;
                break;
              }
            }
            
          }
        //end edit/duplicate
        }
    /*     else if()
        {
        
        } */
        
      }
      
      private function save():void
      {

        if (hasValidationErrors())
          return;
        
        if (action.selectedItem != 'REPLACE' && action.selectedItem != 'INJECT-HTML-FILE')
          manageInject();
        
        else if (fileChanged)
          manageReplaceWithUpload();
        
        else
          manageReplace();
      }
      
      private function hasValidationErrors():Boolean
      {
        var hasError:Boolean = false;
        
        target.errorString = '';
        if (!target.selectedItem) {
          target.errorString = 'Please select a target';
          hasError = true;
        }
        
        agent.errorString = '';
        if (action.selectedItem != 'REPLACE' && action.selectedItem != 'INJECT-HTML-FILE' && !agent.selectedItem) {
          agent.errorString = 'Please select an agent';
          hasError = true;
        }
        
        if (resource.text=="") {
          resource.errorString ='Please fill resource pattern'
          hasError = true;
        }
        
        if (resource.text.indexOf("http://")!=-1) {
          resource.errorString ='Please do not use http:// in pattern'
          hasError = true;
        }
        
        if (action.selectedItem == 'REPLACE' && (mode=="create" || mode=="duplicate") && !fileChanged) {
          browseBtn.errorString = 'Please select a file';
          hasError = true;
        }
        
        
        return hasError;
      }
      
      private function populateCommonProperties():void
      {
        rule.enabled = isEnabled.selected;
        rule.disable_sync = sync.selected;
        rule.probability = probability.value;
        rule.ident = ident.selectedItem;
        rule.ident_param = ident_param.text;
        rule.resource = resource.text;
        rule.action = action.selectedItem;
        
        if (mode == 'create' || target.selectedItem._id != rule.target_id[0])
          rule.target_id = [target.selectedItem._id];
      }
      
      private function manageInject():void
      {
        populateCommonProperties();
        rule.action_param = agent.selectedItem ? agent.selectedItem._id : null;
        rule.action_param_name = agent.selectedItem ? agent.selectedItem._id : null;
        
        saveRule();
      }
      
      private function manageReplace():void
      {
        populateCommonProperties();
        
        saveRule();
      }
      
      private var uploadPopup:UploadPopup;
      private function manageReplaceWithUpload():void
      {
        fileReference.addEventListener(HTTPStatusEvent.HTTP_STATUS, onUploadError);
        fileReference.addEventListener(IOErrorEvent.IO_ERROR, onUploadError);
        fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadError);
        fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
        
        uploadPopup = PopUpManager.createPopUp(this.parentDocument as DisplayObject, UploadPopup, true) as UploadPopup;
        uploadPopup.fileReference = fileReference;
        PopUpManager.centerPopUp(uploadPopup);
      }
      
      private function onUploadComplete(event:DataEvent):void
      {
        PopUpManager.removePopUp(uploadPopup);
        
        populateCommonProperties();
        rule.action_param = event.data;
        rule.action_param_name = StringUtil.trim( fileReference.name)//fileReference.name;

        saveRule();
      }
      
      private function onUploadError(event:Event):void
      {
        PopUpManager.removePopUp(uploadPopup);
        AlertPopUp.show(event.type);
      }
      
      private function browse():void
      {
        fileReference = new FileReference();
        fileReference.addEventListener(Event.SELECT, fileSelection);
        fileReference.browse();
      }
      
      private function fileSelection(event:Event):void
      {
     
        browseBtn.errorString=''
        browseBtn.validateNow()
        currentState = 'fileSelected';
        fileName.text = event.target.name;
        fileChanged = true;
      }
      
      private function saveRule():void
      {
        if (mode == 'create' || mode=="duplicate" )
          injector.rulesManager.addRule(injector._id, rule, function(rule:InjectorRule):void { close(); });
        else
          close();
      }
      
      private function onTargetSelection(event:ItemFieldEvent):void
      {
        _selectedTarget = event.selectedItem;
        agent.selectedItemId = null;
      }
      
      private function  onIdentChange():void
      {
        if(ident.selectedItem=="TACTICAL") {
          ident_param.text="*"
          ident_param.enabled=false;
        } else{
          ident_param.enabled=true;
        }
      }
      
      private function  onActionChange():void
      {
        currentState="normal";
        if(action.selectedItem=="INJECT-HTML-FLASH")
        {
          resource.text="supported video sites"
          resource.enabled=false;
        }
        else{
          resource.text="";
          resource.enabled=true;
        }
      }
      
      protected function formatProbability(value:Number):String
      {
        if(value==0)
          return "once only";
        if(value==100)
          return "everytime";
        else
          return value+"% of the time";
      }
      
    ]]>
  </fx:Script>
  
  
  <utils:states>
    <s:State name="normal"/>
    <s:State name="fileSelected"/>
  </utils:states>
  
  <s:Form id="ruleForm" defaultButton="{saveButton}">
    
    <s:FormItem label="{R.get('ENABLED')}">
      <s:CheckBox id="isEnabled" selected="{rule.enabled}"/>
    </s:FormItem>
    
    <s:FormItem label="{R.get('DISABLE_ON_SYNC')}">
      <s:CheckBox id="sync" selected="{rule.disable_sync}"/>
    </s:FormItem>
    
    <s:FormItem label="{R.get('PROBABILITY')}">
      <s:HSlider id="probability" width="200" maximum="100" minimum="0" snapInterval="1" stepSize="1" dataTipFormatFunction="formatProbability"
                 value="{rule.probability}"/>
    </s:FormItem>
    
    <s:FormItem label="{R.get('TARGET')}">
      <itemfield:ItemField id="target" width="200" kinds="{['target']}" itemSelected="onTargetSelection(event)"
                           selectedItemId="{rule.target_id}"/>
    </s:FormItem>
    
    <s:FormItem label="{R.get('IDENT')}">
      <s:DropDownList id="ident" width="200" requireSelection="true" change="onIdentChange()">
        <s:dataProvider>
          <s:ArrayCollection>
            <fx:String>STATIC-IP</fx:String>
            <fx:String>STATIC-RANGE</fx:String>
            <fx:String>STATIC-MAC</fx:String>
            <fx:String>DHCP</fx:String>
            <fx:String>RADIUS-LOGIN</fx:String>
            <fx:String>RADIUS-CALLID</fx:String>
            <fx:String>RADIUS-SESSID</fx:String>
            <fx:String>RADIUS-TECHKEY</fx:String>
            <fx:String>STRING-CLIENT</fx:String>
            <fx:String>STRING-SERVER</fx:String>
            <fx:String>TACTICAL</fx:String>
          </s:ArrayCollection>
        </s:dataProvider>
      </s:DropDownList>
    </s:FormItem>
    
    <s:FormItem label="{R.get('USER_PATTERN')}">
      <s:TextInput id="ident_param" width="200" text="{rule.ident_param}"/>
    </s:FormItem>
    
  
    
    <s:FormItem label="{R.get('ACTION')}">
      <s:DropDownList id="action" width="200" change="onActionChange()"
                      requireSelection="true">
         <s:dataProvider>
           <s:ArrayCollection>
             <fx:String>INJECT-EXE</fx:String>
             <fx:String>INJECT-HTML-FLASH</fx:String>
             <fx:String>INJECT-HTML-FILE</fx:String>
             <fx:String>REPLACE</fx:String>
           </s:ArrayCollection>
         </s:dataProvider>
       </s:DropDownList>
    </s:FormItem>
    <s:Spacer height="10" visible="{action.selectedIndex==0}"
              includeInLayout="{action.selectedIndex==0}"/>
    <s:TextArea left="10" top="10" width="100%" height="65" right="10" borderVisible="false"
                contentBackgroundAlpha="0.0" editable="false" color="#ff0000"
                text="{R.get('BUILD_MELTED_WARNING')}"
                visible="{action.selectedIndex==0}"
                includeInLayout="{action.selectedIndex==0}"
                />
    
    
    <s:FormItem label="{R.get('RESOURCE_PATTERN')}">
      <s:TextInput id="resource" width="200" text="{rule.resource}"/>
    </s:FormItem>
    
    <s:FormItem visible="{action.selectedItem != 'REPLACE' &amp;&amp; action.selectedItem != 'INJECT-HTML-FILE'}" label="{R.get('FACTORY')}"
                includeInLayout="{action.selectedItem != 'REPLACE' &amp;&amp; action.selectedItem != 'INJECT-HTML-FILE'}">
      <itemfield:ItemField id="agent" width="200" kinds="{['factory']}" types="{['desktop']}"
                           selectedItemId="{rule.action_param}" path="{_selectedTarget}"/> <!--  -->
    </s:FormItem>
   
    <s:FormItem visible="{action.selectedItem == 'REPLACE' || action.selectedItem == 'INJECT-HTML-FILE'}" label="{R.get('FILE')}"
                includeInLayout="{action.selectedItem == 'REPLACE' || action.selectedItem == 'INJECT-HTML-FILE'}">
      <s:Button excludeFrom="fileSelected" width="100" label="{R.get('BROWSE')}..." click="browse()" id="browseBtn"/>
      <s:Label id="fileName" includeIn="fileSelected" width="200" buttonMode="true" click="browse()"
               maxDisplayedLines="1" paddingTop="8" toolTip="{R.get('CLICK_TO_CHANGE_FILE')}"
               verticalAlign="middle"/>
    </s:FormItem>    
  </s:Form>

</utils:TitleWindowSaveCancel>