<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Rule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Rule_Axmedis.xsd">
  <Header>
    <Rule_Name>PostingLicense</Rule_Name>
    <AXRID>axcprule:7570dc6b-5643-4c50-a6b3-21a511135b5e</AXRID>
    <Rule_Version></Rule_Version>
    <Rule_Type>AXCP</Rule_Type>
    <Software_Name></Software_Name>
    <Version_of_software></Version_of_software>
    <Date_of_production>2006-10-25</Date_of_production>
    <Author></Author>
    <Affiliation></Affiliation>
    <URL></URL>
    <Comment></Comment>
    <Last_Modifications>2006-10-26</Last_Modifications>
    <Terminal_ID></Terminal_ID>
    <Cost></Cost>
    <Work_Item_ID></Work_Item_ID>
  </Header>
  <Schedule>
    <Run>
      <Date>2006-10-25</Date>
      <Time>21:51:17</Time>
      <Periodicity Unit="Day">0</Periodicity>
      <Expiration_Date>2007-10-25</Expiration_Date>
      <Expiration_Time>16:01:17</Expiration_Time>
    </Run>
    <Status>Inactive</Status>
  </Schedule>
  <Definition>
    <AXCP_Rule>
      <Arguments/>
      <Rule_Body>
        <JS_Script name="main"><![CDATA[function createLicenseFileArray()
{
    var resArray = getfilelist(resourcePath,"*.xml");
    return resArray;
}

function main()
{
    var fileList =  createLicenseFileArray()
    for (i in fileList)
    {
        var xml = readFromFile(fileList[i]);
        print("Posting License on PMS: "+i);
        postLicense(xml);
        /*var lic = new License();
        lic.RetrieveLicenseFromFile(fileList[i]);
        lic.sendLicenseToPMS();*/
        //removeFile(fileList[i]);
    }
    return true;

}

var resourcePath = "c:\\factory\\license\\";
a = main();]]>
        </JS_Script>
        <JS_Script name="licenseGenerator">
          
          <![CDATA[/*******************************************************
* A License Generation functions from MB License *
********************************************************/
// Completed - it works
function createALicense(creatorId,resId,userId)
{
    return createMotherLicense(creatorId,resId,userId,"mx:play",null);
}
/***********************************************************
*   Grant: function for creating grant for A license    *
************************************************************/
function createAGrant(resId, right)
{ 
     var grant = new Grant();
     var rights = new Right();
     rights.setRight(right);
     var res = new Resource();
     res.resourceId = resId;
     res.diType = 1;
     grant.setResource(res);
     grant.setRight(rights);
     return grant;
}
/*******************************************************
* B License Generation functions from MB License *
********************************************************/
//it works but conditions check is missing
function createB1FromMB1License(lic,userId)
{
   var b1Lic = new License();
   var grant = lic.grantgroup.grants[0];
   var principal = grant.getPrincipal();
   var subgrant = grant.resource.ggResource.grants[0];
   var rIssuer = new Issuer();
   rIssuer.setIssuer(principal.name);
   var rGrantGroup=new GrantGroup();
   var rGrant = new Grant()
   rGrant.setPrincipal(grant.principal);
   rGrant.setResource(subgrant.resource);
   rGrant.setRight(subgrant.right);
   rGrantGroup.addGrant(rGrant);
   b1Lic.setGrantGroup(rGrantGroup);
   b1Lic.setIssuer(rIssuer);
   return b1Lic;
}
// Missing the Interval or the way to set the "validityIntervalFloating"
function createB2FromMB2License(lic,userId)
{
   var b2Lic = new License();
   var grant = lic.grantgroup.grants[0];
   var principal = grant.getPrincipal();
   var subgrant = grant.resource.ggResource.grants[0];
   
   var rIssuer = new Issuer();
   rIssuer.setIssuer(principal.name);
   var rGrantGroup=new GrantGroup();
   var rGrant = new Grant()
   rGrant.setPrincipal(grant.principal);
   rGrant.setResource(subgrant.resource);
   rGrant.setRight(subgrant.right);
   rGrantGroup.addGrant(rGrant);
   b2Lic.setGrantGroup(rGrantGroup);
   b2Lic.setIssuer(rIssuer);
   return b2Lic;
}
// Completed - it works
function createB3FromMB3License(lic,userId)
{
   var b3Lic = new License();
   var grant = lic.grantgroup.grants[0];
   var principal = grant.getPrincipal();
   var subgrant = grant.resource.ggResource.grants[0];
   
   var rIssuer = new Issuer();
   rIssuer.setIssuer(principal.name);
   var rGrantGroup=new GrantGroup();
   var rGrant = new Grant()
   rGrant.setPrincipal(grant.principal);
   rGrant.setResource(subgrant.resource);
   rGrant.setRight(subgrant.right);
   rGrantGroup.addGrant(rGrant);
   b3Lic.setGrantGroup(rGrantGroup);
   b3Lic.setIssuer(rIssuer);
   return b3Lic;
}
/****************************************************
*           Bx License Generation functions         *
*****************************************************/
function createB3Grant(resId, right, notAfter, notBefore)
{
        var grant = new Grant();
        var rights = new Right();
        var timecondition = new Interval();                                    
        var limit = new LNumber();
        var res = new Resource();
        res.resourceId = resId;
        res.diType = 1;    
        limit.count = 1;
        rights.setRight(right)
        timecondition.notBefore = notBefore;
        timecondition.notAfter = notAfter;
        grant.addCondition(timecondition);
        grant.addCondition(limit);
        grant.setRight(rights);
        grant.setResource(res);
        return grant;
}
function createB2Grant(resId, right, time)
{
        var grant = new Grant();
        var rights = new Right();
        var res = new Resource();
        res.resourceId = resId;
        res.diType = 1;        
        rights.setRight(right);
        grant.setResource(res);
        grant.addCondition(timecondition);
        grant.addCondition(limit);
        grant.setRight(right);
        return grant;
}
function createB1Grant(resId, right, amount, currency)
{ 
     var grant = new Grant();
     var fee = new Fee();
     var rights = new Right();
     rights.setRight(right);
     fee.amount = parseFloat(amount);
     fee.currency = "iso:EUR";
     fee.tipoFee = 1;
     var res = new Resource();
     res.resourceId = resId;
     res.diType = 1;
     grant.setResource(res);
     grant.addCondition(fee);
     grant.setRight(rights);
     return grant;
}
/****************************************************
*     Bx License Generation function from grant     *
*****************************************************/
function createBxLicense(distributorId,userId,grant)
{
    var license = new License();
    var grantGroup = new GrantGroup();
    var issuer = new Issuer();
    var principal = new Principal();
       
    principal.setName(userId);
    grant.setPrincipal(principal);
    grantGroup.addGrant(grant);
    issuer.setIssuer(distributorId);
    license.setGrantGroup(grantGroup);
    license.setIssuer(issuer);
    return license;
}
/****************************************************
*           Mother License Generation function      *
*****************************************************/
function createMotherLicense(creatorId,userId,grant)
{
    var license = new License();
    var grantGroup = new Array(new GrantGroup(),new GrantGroup());
    var grant0 = new Grant();
    var issuer = new Issuer();
    var rights = new Right();
    var principal = new Principal();
    var res = new Array (new Resource(),new Resource());
    
    //level 1
    grantGroup[1].addGrant(grant);
      
    //level 0 - grant Group
    res[0].setGrantGroup(grantGroup[1]);
    rights.setRight("r:issue");
    principal.setName(userId);
    grant0.setPrincipal(principal);
    grant0.setResource(res[0]);
    grant0.setRight(rights);
    grantGroup[0].addGrant(grant0);
    //level 0 - issuer
    issuer.setIssuer(creatorId);
    license.setGrantGroup(grantGroup[0]);
    license.setIssuer(issuer);
    return license;
}]]>
        </JS_Script>
        <JS_Script name="axlib">
          
          <![CDATA[function createPARFromDRM(xmlDRM, quality)
{
    if(xmlDRM.length == 0)
        return null;
    var jsXML = new REXML(xmlDRM);
    var root = jsXML.rootElement;
    var child = root.childElements[0];
    var node = child.childElements[0];
    var parGrantGroup = new PARGrantGroup();
    if(node.name == "non-free")
    {
        var nonFreeNodes = node.childElements;
        for(i in nonFreeNodes)
        {
            var subNode = nonFreeNodes[i];
            var lowQualityPrice = subNode.childElements[0].getText();
            var highQualityPrice = subNode.childElements[1].getText();
            var price = highQualityPrice;
            if(quality == "high")
                price = lowQualityPrice;
            //var lowAsHighPermission = subNode.childElements[2].getText();
            if(subNode.name == "unlimited")
            {
                
                // create grant
                var grant = new PARGrant();
                var fee = new Fee();
                
                fee.amount = parseFloat(price);
                fee.currency = "iso:EUR";
                fee.tipoFee = 2;                
                grant.addCondition(fee);
                var right = new Right();
                right.setRight("mx:play");
                grant.setRight(right);
                parGrantGroup.addPARGrant(grant);
            }
            else if(subNode.name == "time-based")
            {
                var condition = subNode.childElements[3];
                // create grant
                var grant = new PARGrant();
                var fee = new Fee();
                var timecondition = new Interval();
                fee.amount = parseFloat(price);
                fee.currency = "iso:EUR";               
                if(condition.name == "period")
                {
                    fee.tipoFee = 1;
                    var unit = condition.childElements[0].getText();
                    var period = condition.childElements[1].getText();
                    print("period = "+unit+" "+period);
                }
                else
                { 
                    fee.tipoFee = 1; 
                    var limit = new LNumber();
                    limit.count = 1;
                    timecondition.notBefore = subNode.childElements[3].getText();
                    timecondition.notAfter = subNode.childElements[4].getText();
                    grant.addCondition(timecondition);
                    grant.addCondition(limit);
                }
                grant.addCondition(fee);
                var right = new Right();
                right.setRight("mx:play");
                grant.setRight(right);
                parGrantGroup.addPARGrant(grant);
                
            }
            else if(subNode.name == "one-time-based")
            {
                // create license type
                var grant = new PARGrant();
                var fee = new Fee();
                fee.amount = parseFloat(price);
                fee.currency = "iso:EUR";
                fee.tipoFee = 1;
                grant.addCondition(fee);
                var right = new Right();
                right.setRight("mx:play");
                grant.setRight(right);
                parGrantGroup.addPARGrant(grant);
               
            }
        }
    }   
    else if(node.name == "free")
    {
        isFree = true;
    }
    return parGrantGroup;
  
}
function applyPAR(obj,pars)
{
    var axinfo = obj.getAxInfo();
    axinfo.addPotentialAvailableRights();
    var gGroup = new PARGrantGroup();
    for(i=0;i<pars.grants.length; i++)
        gGroup.addPARGrant(pars.grants[i]); 
        
    var par = new PAR();
    par.setPARGrantGroup(gGroup);
    axinfo.setPotentialAvailableRights(par.getXMLPAR());
}
function protectObject(obj,info)
{
    if(isFree)
        return true;
    var params = new Array();
    params[0]=20;
    var order = 1;
    var toolID = "urn:axmedis:ipmp:tool:id:0003";
    return obj.setProtectionInfo(toolID,order,params);
}
function createLicenseGrantFromDRM(xmlDRM)
{
    if(xmlDRM.length==0)
        return null;
    var jsXML = new REXML(xmlDRM);
    var root = jsXML.rootElement;
    var child = root.childElements[0];
    var node = child.childElements[0];
    var par = new License();
    var grantGroup = new GrantGroup();
    var drm = par.getXMLLicense();
    if(node.name == "non-free")
    {
        var nonFreeNodes = node.childElements;
        for(i in nonFreeNodes)
        {
            var subNode = nonFreeNodes[i];
            var lowQualityPrice = subNode.childElements[0].getText();
            var highQualityPrice = subNode.childElements[1].getText();
            var lowAsHighPermission = subNode.childElements[2].getText();
            if(subNode.name == "unlimited")
            {
                // create grant for MA
                var grant = new Grant();
                grantGroup.addGrant(grant);
            }
            else if(subNode.name == "time-based")
            {
                var condition = subNode.childElements[3];
                // create grant for MB2-MB3
                var grant = new Grant();
                var timecondition = new Interval();
                             
                if(condition.name == "period") //MB2
                {
                    var unit = condition.childElements[0].getText();
                    var period = condition.childElements[1].getText();
                    print("period = "+unit+" "+period);
                }
                else //MB3
                {                      
                    var limit = new LNumber();
                    limit.count = 1;
                    timecondition.notBefore = subNode.childElements[3].getText();
                    timecondition.notAfter = subNode.childElements[4].getText();
                    grant.addCondition(timecondition);
                    grant.addCondition(limit);
                }
               
                grantGroup.addGrant(grant);
                
            }
            else if(subNode.name == "one-time-based")
            {
                // create grant for MB1
                var grant = new Grant();
                var fee = new Fee();
                fee.amount = parseFloat(highQualityPrice);
                fee.currency = "iso:EUR";
                fee.tipoFee = 1;
                grant.addCondition(fee);
                grantGroup.addGrant(grant);
               
            }
        }
    }   
    else if(node.name == "free")
    {
        isFree = true;
    }
    return grantGroup;
  
}
function createMotherLicenses(creator,user,obj,right,grantList)
{
    var lic = new Array();
    var creatorId = creator;
    var userId = user;
    var resId = obj.AXOID;
    for(i=0;i<grantList.grants.length; i++)
    {
        var grant = grantList.grants[i];
        lic[i] = createMotherLicense(creatorId,resId,userId,right,grant);
    }
    return lic
    
}
function postLicense(xml)
{
//"192.168.0.108"
    var PMSClientEndpoint="https://192.168.0.108:8502/PMS/";
    var PMSClientCertificate="client.pem";
    var PMSClientCertificatePsw="axmedis";
    var PMSClientCA="cacert.pem";
    var pms = new PMSClient(PMSClientEndpoint,PMSClientCertificate,PMSClientCertificatePsw,PMSClientCA);
    pms.sendLicense(xml);
}
function test()
{
    var xmlDRMModel = readFromFile("c:\\DRMExample3.xml");
    var highQualityPARs = createPARFromDRM(xmlDRMModel,"high");
  //  var lowQualityPARs = createPARFromDRM(xmlDRMModel,"low");
    var obj = new AxmedisObject()
    applyPAR(obj,highQualityPARs);
    var LicGrants = createLicenseGrantFromDRM(xmlDRMModel);
    var Lic = createMotherLicenses("AXCID:Creator","AXDID:Distributor",obj,"mx:play",LicGrants);
    for(i in Lic)
    {
        print("License number: "+i);
        var xml = Lic[i].getXMLLicense()
        postLicense(xml);
        Lic[i].StoreLicenseToFile("C:\\licenza_"+i+".xml");
    }
}]]>
        </JS_Script>
        <JS_Script name="scanDir">
          
          <![CDATA[/* lists the files (only files, no directories) in a directory
with a certain mask
returns an array with the files.
If no file is found it will return an empty array 
*/
function getfilelist (
getflielist_dir,        //directory 
getflielist_mask        // mask e.g. "*.*"
)
{
  var list = new Array();
  if (!existsDir(getflielist_dir))  // check that the directory exists
  {
	return (list)
  }
  var file = getFirstFile(getflielist_dir, getflielist_mask);
  if (file != null)
  {
    list.push (file);
  }
  while (file != null)
  {
     var nextfile = getNextFile();
     if (nextfile == null)
     {
       break;
     }
     list.push (nextfile);
     nextfile = undefined;
    }
  return (list);
}]]>
        </JS_Script>
      </Rule_Body>
      <Dependencies/>
    </AXCP_Rule>
  </Definition>
</Rule>

