<?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>ScriptProduction</Rule_Name>
    <AXRID>axcprule:10879976-97c3-4f6e-9f7d-b6c518d1e21f</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-20</Date_of_production>
    <Author></Author>
    <Affiliation></Affiliation>
    <URL></URL>
    <Comment></Comment>
    <Last_Modifications>2006-11-09</Last_Modifications>
    <Terminal_ID></Terminal_ID>
    <Cost></Cost>
    <Work_Item_ID></Work_Item_ID>
  </Header>
  <Schedule>
    <Run>
      <Date>2006-10-26</Date>
      <Time>13:14:22</Time>
      <Periodicity Unit="Day">0</Periodicity>
      <Expiration_Date>2007-10-20</Expiration_Date>
      <Expiration_Time>10:44:22</Expiration_Time>
    </Run>
    <Status>Inactive</Status>
  </Schedule>
  <Definition>
    <AXCP_Rule>
      <Arguments>
        <Parameter Name="from" Type="Integer">7</Parameter>
        <Parameter Name="to" Type="Integer">8</Parameter>
        <Parameter Name="resourcePath" Type="String">x:\resources</Parameter>
      
      </Arguments>
      <Rule_Body>
        <JS_Script name="Main"><![CDATA[/***************************************************************************/
// AXMEDIS JSScript
// This script is provided merely as demonstration tools and provide 
// limited functionalities and robustness with respect to the full tools, 
// and as such should be considered. 
// AXMEDIS declines any responsibility on the use made with the script 
// hereby installed.
// The intellectual property of this script belongs to AXMEDIS, and 
// any total or partial reproduction of it is prohibited 
// without written authorization of AXMEDIS Consortium. 
// AXMEDIS Copyright 2006.

// Please verify the resourcePath value before running the script
// Fix it to the right path (double clicking on the item to open
// the editing dialog
/**************************************************************************/


// Function for creating the Dublin Core information
function createDC(obj,label,format)
{
    dc = obj.getDublinCore();
    dc.addDCElement("creator","AXCP");
    dc.addDCElement("title",label);
    dc.addDCElement("type","Single");
    dc.addDCElement("description","Automatic generation of content");
    dc.addDCElement("format",format);
}

function createResourceArray()
{
    var resArray = getfilelist(resourcePath,"*.*");
    var res = new Array();
    if(from>resArray.lenght)
      return res;
    if(to>resArray.lenght)
      to = resArray.lenght;
    for(i=from; i<to; i++)
      res[i-from]=resArray[i];
    return res;
}

function addPar(obj)
{
   var parGrant = new PARGrantGroup();
   parGrant.addPARGrant(createAPARGrant(obj.AXOID,"mx:play"));
   parGrant.addPARGrant(createB1PARGrant(obj.AXOID,"mx:play","1.00","iso:EUR"));
   parGrant.addPARGrant(createB3PARGrant(obj.AXOID,"mx:play","2007-10-23T00:00:00","2006-10-23T00:00:00",10));
   applyPAR(obj,parGrant);
   return true;
    
}

function adaptResource(res)
{
  var adaptedRes = new Array();
  
    /*if(res instanceof AxResource && res.mimeType.search("video")==0)// it is a video
    {
        adaptedRes[0] = adaptVideoResource(res,"video/mpeg");
    }
    else if(res instanceof AxResource && res.mimeType.search("audio")==0)// it is a video
    {
        adaptedRes[0]= adaptAudioResource(res,"audio/mpeg");
    }
    else*/
    if(res instanceof AxResource &&  res.mimeType.search("image")==0)// it is a video
    {
       
       /* adaptedRes[0]=adaptImageResource(res,"image/gif",100,100);
        adaptedRes[1]=adaptImageResource(res,"image/jpeg",100,100);
        adaptedRes[2]=adaptImageResource(res,"image/png",100,100);
        adaptedRes[3]=adaptImageResource(res,"image/tiff",100,100);*/
        var out=adaptImageResource(res,"image/gif",100,100);
        var i =0;
        if(out!=null)
        {
            adaptedRes[i]=out;
            i++;
        }
        out =adaptImageResource(res,"image/jpeg",100,100);
        if(out!=null)
        {
            adaptedRes[i]=out;
            i++;
        }
        out = adaptImageResource(res,"image/png",100,100);
         if(out!=null)
        {
            adaptedRes[i]=out;
            i++;
        }
        /*out = adaptImageResource(res,"image/tiff",100,100);
         if(out!=null)
        {
            adaptedRes[i]=out;
            i++;
        }*/
         if(i==0)
             return null;
        
    }
    else if(res instanceof AxResource && (res.mimeType.search("text")==0
                || res.mimeType.search("application")==0))// it is a video
    {
        var out=adaptDocumentResource(res,"text/html");
        var i =0;
        if(out!=null)
        {
            adaptedRes[i]=out;
            i++;
        }
        out =adaptDocumentResource(res,"text/plain");
        if(out!=null)
        {
            adaptedRes[i]=out;
            i++;
        }
         if(i==0)
             return null;
       
    }
    else
         return null;        
	
    return adaptedRes;
}

function createMLicense(objid)
{
    var creatorID = AXCID;
    var userID =AXDID;
    var licenses = new Array();
    var filename = objid.replace(/:/g,"_");
    var grantA = createAGrant(objid.replace("\n",""),"mx:play");
    var grantB1 = createB1Grant(objid,"mx:play","1.00","iso:EUR");
    var grantB3 = createB3Grant(objid,"mx:play","2006-10-23T00:00:00","2007-08-13T00:00:00");
    print("Creating License MA");
    licenses[0] = createMotherLicense(creatorID,userID,grantA);
    licenses[0].StoreLicenseToFile("c:\\factory\\license\\"+filename+"_MA.xml");
    //licenses[0].sendLicenseToPMS();
    print("Creating License MB1");
    licenses[1] = createMotherLicense(creatorID,userID,grantB1);
    licenses[1].StoreLicenseToFile("c:\\factory\\license\\"+filename+"_MB1.xml");
    //licenses[1].sendLicenseToPMS();
    print("Creating License MB3");
    licenses[2] = createMotherLicense(creatorID,userID,grantB3);
    licenses[2].StoreLicenseToFile("c:\\factory\\license\\"+filename+"_MB3.xml");
    //licenses[2].sendLicenseToPMS();
    return true;
}



function createAxmedisObjectFromResource(resource)
{
   
    var resTitle = title;
    print("Creating MASTER Copy of AXMEDIS Object");
    var masterObj = new AxmedisObject();
    print("Embedding resource into MASTER Axmedis Object");  
    masterObj.addContent(resource); 
    var label = resTitle+"_MASTER_";
    createDC(masterObj,label,resource.mimeType);
    if(!fillObjectCreatorCredentials(masterObj))
      return false;
    var axInfo = masterObj.getAxInfo();
    axInfo.distributorAXDID=AXDID;
    creatorID = axInfo.getObjectCreatorAXCID();
    print("Adding PAR to MASTER (A,B1,B3 type)");
    if(!addPar(masterObj))
        return false;
    var saverEndPoint = "http://192.168.0.108:8080/LoaderSaver/save";
    var user = "test";
    var passwd = "test";
    var usingftp = true; 
    var externalurl = "ftp://192.168.0.108";
    var internalurl = "";
    var lockEndPoint = "http://192.168.0.108:8080/LockUnlockWS/lockunlock";
    print("Uploading non protected MASTER object on DB: "+masterObj.AXOID);
    if(!masterObj.uploadToDB(saverEndPoint,user,passwd,usingftp,externalurl,internalurl,lockEndPoint))
    {
        var error = "Upload request failure: "+masterObj.AXOID;
        print(error);
        return false;
    }
     var filename = masterObj.AXOID.replace(/:/g,"_")+"_master.axm";
     masterObj.save("c:\\factory\\"+filename);
   appendToFile(productionFilePath,masterObj.AXOID+"\n");
    
  /* masterObj.save("c:\\test.axm");
   execute("c:\\test.axm");*/
   masterObj.dispose();
   masterObj = null;
   return true;
    
}


function createADAPTEDAxmedisObjectFromResource(resource)
{
    print("Start content adaptation for adapted objects");
    var res = adaptResource(resource);
    if(res==null)
        createADAPTEDAxmedisObject(resource);
    else 
    {
        for(i in res)
        {
            createADAPTEDAxmedisObject(res[i]);
        }
    }
        
 }
 
function createADAPTEDAxmedisObject(resource)
{
    print("Creating ADAPTED Version of AXMEDIS Object");
    var adaptedObj = new AxmedisObject();
    adaptedObj.addContent(resource);
    
  var resTitle = title; 
  var label = resTitle+"_ADAPTED_FINAL";
  print("Creating Dublin Core Metadata");
  createDC(adaptedObj,label,resource.mimeType);
  print("Filling creator Metadata");
  if(!fillObjectCreatorCredentials(adaptedObj))
     return false;
  var axInfo = adaptedObj.getAxInfo();
  axInfo.distributorAXDID=AXDID;
  print("Adding PAR (A,B1,B3 type) to ADAPTED object");
  if(!addPar(adaptedObj))
     return false;
  print("Uploading unprotected ADAPTED object on Factory DB");
  var saverEndPoint = "http://192.168.0.108:8080/LoaderSaver/save";
    var user = "test";
    var passwd = "test";
    var usingftp = true; 
    var externalurl = "ftp://192.168.0.108";
    var internalurl = "";
    var lockEndPoint = "http://192.168.0.108:8080/LockUnlockWS/lockunlock";
    if(!adaptedObj.uploadToDB(saverEndPoint,user,passwd,usingftp,externalurl,internalurl,lockEndPoint))
    {
       var error = "Upload request failure: "+adaptedObj.AXOID;
       print(error);
    }
  var filename = adaptedObj.AXOID.replace(/:/g,"_")+"_adapted.axm";
  adaptedObj.save("c:\\factory\\"+filename);
  /* Protection and upload on DB and DBF */
  print("Adapted Object: Asking for definitive AXOID to AXCS");
  if(!adaptedObj.obtainDefinitiveAXOID())
  {
        var error = "Adapted Object: Definitive AXOID request failure: "+adaptedObj.AXOID;
        print(error);
        return false;
  }
  var adaptedAXOID = adaptedObj.AXOID;
  
  print("Uploading unprotected ADAPTED object on Factory DB");
  filename = adaptedAXOID.replace(/:/g,"_")+"_adapted_definitive.axm";
  adaptedObj.save("c:\\factory\\"+filename);

  print("Applying Protection Info to ADAPTED object");
    if(protectObject(adaptedObj,0))
    { 
        print("Registering ADAPTED object to AXCS");
        adaptedObj.registerToAXCS();
        print("Uploading protected ADAPTED object in Distribution DB");
        var filenameP = adaptedAXOID.replace(/:/g,"_")+"_PROTECTED.axm";
        adaptedObj.save("c:\\factory\\"+filenameP);
        if(!adaptedObj.uploadToDB(saverEndPoint,user,passwd,usingftp,externalurl,internalurl,lockEndPoint))
        {
            var error = "Upload request failure: "+adaptedAXOID;
            print(error);
            return false;
        }
    }
    
   
   appendToFile(productionFilePath,adaptedAXOID+"\n");
      
   adaptedObj.dispose();
   adaptedObj = null;
   print("Creating Licenses (MA,MB1 and MB3)");
   createMLicense(adaptedAXOID);
   return true;
}

// Function for creating the Axmedis Object by composing and converting resources
function main()
{
  var resources = createResourceArray();
  if(resources.lenght==0)
      return false;
  for(j=0; j<resources.length; j++)
  { 
      var resource = new AxResource()
      resource.load(resources[j]);
      print("resource type = "+resource.mimeType);
      title = resource.contentID;
      if(createAxmedisObjectFromResource(resource))
      {
          print("MASTER Copy created!");
          resource.flush();
          resource = null;
          var resourceA = new AxResource()
          resourceA.load(resources[j]);
          if(createADAPTEDAxmedisObjectFromResource(resourceA))
              print("ADAPTED Copies created!");
          resourceA.flush();
          resourceA = null;
      }
      else
      {
          resource.flush();
          resource = null;
      }
  }
  return true;
}

var productionFilePath = "X:\\production.txt"; // shared folder
var AXCID = "URN:AXMEDIS:00001:BUS:00000000-0000-0000-0000-000000000000";
var AXDID = "URN:AXMEDIS:00001:BUS:3A2F35F1-5E91-314C-A51A-D07D75C216C7";
var producedaxoid = new Array();
var creatorID = AXCID;
var userID = AXDID;
var title = "";
//a = main();
createMLicense("URN:AXMEDIS:00001:OBJ:3A2F35F1-5E91-314C-A51A-D07D75C216C7")]]>
        </JS_Script>
        <JS_Script name="utility">
          
          <![CDATA[function createTempDir(path)
{
    if(!existsDir(path))
        makeDir(path);
}
function removeTempDir(path)
{
    if(existsDir(path))
        removeDirRecursively(path);
}
function removeDirRecursively(path)
{
    var files = getAllFiles(path);
    for(k=0; k<files.length; k++)
         removeFile(files[k]);
    var subDirs = listDir(path);
    for(i=0;i<subDirs.length;i++)
        removeDirRecursively(subDirs[i]);
    removeDir(path);
}
function unzipFile(starter_zip)
{
    var Zipper = new ZipArchiver();
    Zipper.openZipArchive(starter_zip);
    Zipper.unzip(); 
    return true;
}
/* 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);
}
/*
Get the filename (or last level dir) in a filename
"\\" is assumed as path separator
*/
function filefrompath (
    file
    )
{
if (file=="")
{
    return (file);
}
var trim=file.length+1;
    for (l=file.length; l>=0; l--)
    {
        if (file[l] == "\\") {break;}
        trim= trim-1;
    }
file = file.slice (trim);
return (file)
}
/*
Get first level subdirs of a directory
Returns an array with the subdirs or null upon unsuccess
*/
function subdirs (
dir
)
{
    print ("Searching for subdirs in \""+dir +"\"...");
    if (!existsDir (dir))
    {
    print ("ERROR: \""+dir +"\" doesn't exist");
    return (null);
    }
    var list = listDir (dir)
    for (i in list)
    {
        print (list[i]);
    }
    return (list);
}]]>
        </JS_Script>
        <JS_Script name="parGenerator">
          
          <![CDATA[/***********************************************************
*   PARGrant: functions for creating PAR for A license    *
************************************************************/
function createAPARGrant(resId, right)
{ 
     var grant = new PARGrant();
     var rights = new Right();
     rights.setRight(right);
     var res = new PARResource();
     res.resourceId = resId;
     res.diType = 1;
     grant.setPARResource(res);
     grant.setRight(rights);
     return grant;
}
/***********************************************************
*   PARGrant: functions for creating PAR for Bx license    *
************************************************************/
function createB3PARGrant(resId, right, notAfter, notBefore,count)
{
        var grant = new PARGrant();
        var rights = new Right();
        var timecondition = new Interval();                                    
        var limit = new LNumber();
        var res = new PARResource();
        res.resourceId = resId;
        res.diType = 1;    
        limit.count = count;
        rights.setRight(right)
        timecondition.notBefore = notBefore;
        timecondition.notAfter = notAfter;
        grant.addCondition(timecondition);
        grant.addCondition(limit);
        grant.setRight(rights);
        grant.setPARResource(res);
        return grant;
}
function createB2PARGrant(resId, right, time)
{
        var grant = new PARGrant();
        var rights = new Right();
        var res = new PARResource();
        res.resourceId = resId;
        res.diType = 1;        
        rights.setRight(right);
        grant.setPARResource(res);
        grant.addCondition(timecondition);
        grant.addCondition(limit);
        grant.setRight(right);
        return grant;
}
function createB1PARGrant(resId, right, amount, currency)
{ 
     var grant = new PARGrant();
     var fee = new Fee();
     var rights = new Right();
     rights.setRight(right);
     fee.amount = parseFloat(amount);
     //fee.amount = 1.00;
     fee.currency = currency; //"iso:EUR";
     fee.tipoFee = 1;
     var res = new PARResource();
     res.resourceId = resId;
     res.diType = 1;
     grant.setPARResource(res);
     grant.addCondition(fee);
     grant.setRight(rights);
     return grant;
}]]>
        </JS_Script>
        <JS_Script name="adaptation">
          
          <![CDATA[/***************************************************************************/
// AXMEDIS JSScript
// This script is provided merely as demonstration tools and provide 
// limited functionalities and robustness with respect to the full tools, 
// and as such should be considered. 
// AXMEDIS declines any responsibility on the use made with the script 
// hereby installed.
// The intellectual property of this script belongs to AXMEDIS, and 
// any total or partial reproduction of it is prohibited 
// without written authorization of AXMEDIS Consortium. 
// AXMEDIS Copyright 2006.
// Please verify the resourcePath value before running the script
// Fix it to the right path (double clicking on the item to open
// the editing dialog
/**************************************************************************/
function adaptImageResource(res,outFormat,height,width)
{
  print("Creating adapted image resource");   
  var h =  new Array(1);
  var w =  new Array(1);
  var mimeType = outFormat;
  var outRes = new AxResource();
  outRes.contentID = res.contentID;
  h[0]=0;
  w[0]=0;
   if(ImageProcessing.GetInfo(res,h,w)=="SUCCESS")
   {
        print("Original resource size is "+h+"x"+w);
        print("Resizing the resource at "+height+"x"+width);
        ImageProcessing.Resize(res,height,width,false,outRes);
        
        if(res.mimeType!=mimeType)
        { 
            print("Converting the resource in "+mimeType);
            ImageProcessing.Conversion(outRes,mimeType,outRes);
        }
        return outRes;
    }
    else
        return null;
}
function adaptDocumentResource(res,outFormat)
{
   var outRes = new AxResource();
   outRes.contentID = res.contentID;
    print("Creating adapted document");
    var mime = new Array();
    mime[0]="application/pdf";
    mime[1]="application/postscript";
    mime[2]="application/rtf";
    mime[3]="text/plain";
    mime[4]="text/html";
    mime[5]="application/msword";
    if(res.mimeType!=outFormat)
    {     
        mimeTypeIn =res.mimeType;
        var found = false;
        for(i=0; i<mime.length && !found; i++)
        {
            if(mime[i]==mimeTypeIn)
                found=true;
        }
        if(!found)
            return null;
        print("Converting the resource in "+outFormat);
        if(TextDocsAdaptation.DocumentConversion(res,outFormat,outRes)=="SUCCESS")
            return outRes;
        else
            return null;
    }
    else  
       return null;
}
function adaptVideoResource(res,outFormat)
{
    print("Creating adapted video");
    var outRes = new AxResource();
    outRes.contentID = res.contentID;
    print("Creating adapted video");
    if(res.mimeType=="video/mpeg" || res.mimeType=="video/avi")
    {     
        print("Converting the resource in "+outFormat);
        var ret = VideoAdaptation.AX_ffmpegTranscoder(
        res,outRes,outFormat,"default",0,0,100,100,0,0,0,false,false,true);
        print(ret);
        if(ret.search("Success")==0)
        {
            //outRes.save("c:\\prova.mpeg");
            return outRes;
        }
        else
            return res;
    }
    else  
       return res;
 
  
}
function adaptAudioResource(res,outFormat)
{
  print("Creating adapted audio");   
  var h0 =  new Array(1);
  var h1 =  new Array(1);
  var h2 =  new Array(1);
  var h3 =  new Array(1);
  var h4 =  new Array(1);
  var w =  new Array(1);
  h0[0]="pippo";
  h1[0]=0;
  h2[0]=0;
  h3[0]=0;
  h4[0]="pluto";
  w[0]=0;
 var outRes = new AxResource();
 outRes.contentID = res.contentID;
        
        if(RingtoneAdaptation.getInfo(res,h0,h1,h2,h3,h4)=="SUCCESS")
        {
            print("Original resource mimeType is "+h0);
            print("Original resource samplig Rate is "+h1);
            print("Original resource channels is "+h2);
            print("Original resource bitRate "+h3);
            print("Original resource duration "+h4);
       
            if(h0[0]!=outFormat)
            { 
                print("Converting the resource in "+outFormat);
                RingtoneAdaptation.convert(res,outFormat,outRes);
                RingtoneAdaptation.getInfo(outRes,h0,h1,h2,h3,h4);
                print("New resource mimeType is "+h0);
                print("New resource samplig Rate is "+h1);
                print("New resource channels is "+h2);
                print("New resource bitRate "+h3);
                print("New resource duration "+h4);
                return outRes;
            }
           else
               return res;
        }
        else
            return res;
  
}]]>
        </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>
        <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 = 2;
     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 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)
{
    
    var params = new Array();
    //params[0]=20;
    var order = 1;
    var toolID ="";
    if(Math.round(Math.random())==0)
    {
        toolID = "urn:axmedis:ipmp:tool:id:0003";
        params[0]=Math.round(Math.random()*100/2);
    }
    else
    {
        toolID = "urn:axmedis:ipmp:tool:id:0001";
        var n = Math.round(Math.random()*255);
        var key=n.toString(36);
        for(i=0; i<55; i++)
        {
            n = Math.round(Math.random()*255);
            key = key+n.toString(36);
        }
        params[0]=key;
    }
    return obj.setProtectionInfo(toolID,order,params);
}
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 postLicense2(lic)
{
//"192.168.0.108"
    
    var PMSClientEndpoint="https://192.168.0.108:8502/PMS/";
    var PMSClientCertificate="client.pem";
    var PMSClientCertificatePsw="axmedis";
    var PMSClientCA="cacert.pem";
    lic.sendLicenseToPMS(PMSClientEndpoint,PMSClientCertificate,PMSClientCertificatePsw,PMSClientCA);;
}
function fillObjectCreatorCredentials(obj)
{
    var axcsUri = "http://192.168.0.108:8080/AXCSUserRegistrator/services/UserRegistrator";
    var axcs = new AXCSClient(axcsUri);
    var creatorMetadata = axcs.getUserData("mario","xxxxx",AXCID);
    
    var info = obj.getAxInfo();
    info.setObjectCreatorAXCID(AXCID);
    
    for(i in creatorMetadata)
    {   
        print(creatorMetadata[i][0]+"="+creatorMetadata[i][1]);
        var field = creatorMetadata[i][0];
        var val = creatorMetadata[i][1];
        if(field=="refName")
            info.setObjectCreatorName(val);
        else if(field=="webSite")
            info.setObjectCreatorURL(val);
        else if(field=="company")
            info.setObjectCreatorCompany(val);
        else if(field=="webSite")
            info.setObjectCreatorCompanyURL(val);
        else if(field=="nationality")
            info.setObjectCreatorNationality(val);
    }
    info.objectLastModificationDate = info.objectCreationDate;
    return true;
 }]]>
        </JS_Script>
      </Rule_Body>
      <Dependencies>
        <Dependency>
          <Plug_In_name>RingtoneAdaptation</Plug_In_name>
          <Version>1.001</Version>
        </Dependency>
        <Dependency>
          <Plug_In_name>ImageProcessing</Plug_In_name>
          <Version>1.001</Version>
        </Dependency>
        <Dependency>
          <Plug_In_name>TextDocsAdaptation</Plug_In_name>
          <Version>1.001</Version>
        </Dependency>
        <Dependency>
          <Plug_In_name>VideoAdaptation</Plug_In_name>
          <Version>1.001</Version>
        </Dependency>
      </Dependencies>
    </AXCP_Rule>
  </Definition>
</Rule>

