<?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>ScriptSecondProduction</Rule_Name>
    <AXRID>axcprule:05ef01af-e7bf-4d86-bd07-84ff68098dfb</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-10-24</Last_Modifications>
    <Terminal_ID></Terminal_ID>
    <Cost></Cost>
    <Work_Item_ID></Work_Item_ID>
  </Header>
  <Schedule>
    <Run>
      <Date>2006-10-20</Date>
      <Time>10:44:22</Time>
      <Periodicity Unit="Day">0</Periodicity>
      <Expiration_Date>2006-10-20</Expiration_Date>
      <Expiration_Time>10:44:22</Expiration_Time>
    </Run>
    <Status>Inactive</Status>
  </Schedule>
  <Definition>
    <AXCP_Rule>
      <Arguments>
        <selection name="selection" timestamp="2006-10-23T19:13:35-00:00" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Selection-v1-6.xsd">
          <query name="Query(0)" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="QUERY-v1-6.xsd">
            <source>
              <location>AXDB</location>
    </source>
            <result>
              <AXInfofield>DCMI:format</AXInfofield>
              <AXInfofield>DCMI:title</AXInfofield>
    </result>
            <AXinfoQuery>
              <querycondition>
                <nesting>        
                  <test>
                    <field>DCMI:format</field>
                    <operator>CONTAINS</operator>
                    <value>audio/mpeg</value>
          </test>
                </nesting>
              </querycondition>
            </AXinfoQuery>
          </query>
        </selection>
      </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 retrieveAXOIDfromSelection()
{
    selection.resolveQuery("test","test",0);
    return selection.getAXDBResult();
}

// 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","Collection");
    dc.addDCElement("description","Automatic generation of content");
    dc.addDCElement("format",format);
}


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-23","2006-10-23",6));
   applyPAR(obj,parGrant);
   return true;
    
}

function createMLicense(obj)
{
    var licenses = new Array();
    var grantA = createAGrant(obj.AXOID,"mx:play");
    var grantB1 = createB1Grant(obj.AXOID,"mx:play","2.00","iso:EUR");
    var grantB3 = createB3Grant(obj.AXOID,"mx:play","2007-10-23","2006-10-23",6);
    licenses[0] = createMotherLicense(creatorID,userID,grantA);
    licenses[1] = createMotherLicense(creatorID,userID,grantB1);
    licenses[2] = createMotherLicense(creatorID,userID,grantB3);
    for(i in licenses)
        postLicense(licenses[i].getXMLLicense());
    
    return true;
}



function createCompositeAxmedisObject(axmedisRes)
{
    print("Creating COMPOSITE AXMEDIS Object");
    var newObj = new AxmedisObject();
    for(i in axmedisRes)
    {
        if(axmedisRes[i] instanceof AxmedisObject)
            newObj.addContent(axmedisRes[i]);
    }
    
  var label = title;
  createDC(newObj,label,"");
  if(!fillObjectCreatorCredentials(newObj))
      return false;
  
  print("Adding PAR (A,B1,B3 type) to COMPOSITE object");
  if(!addPar(newObj))
      return false;
  print("Uploading unprotected COMPOSITE object on Factory DB");
  if(!newObj.uploadToDB())
  {
       var error = "Upload request failure: "+newObj.AXOID;
       print(error);
  }
  
  print("Composite Object: Asking for definitive AXOID to AXCS");
  if(!newObj.obtainDefinitiveAXOID())
  {
        var error = "Composite Object: Definitive AXOID request failure: "+newObj.AXOID;
        print(error);
        return false;
  }
  print("Creating and posting Licenses (MA,MB1 and MB3)");
  createMLicense(newObj);
  var compositeAXOID = newObj.AXOID;
  print("Applying Protection Info to COMPOSITE object");
    if(protectObject(newObj,0))
    { 
        //Settings for uploading object on the Distribution DB
        var saverEndPoint = "http://violino.dsi.unifi.it:8080/LoaderSaver/save";
        var user = "test";
        var passwd = "test";
        var usingftp = true; 
        var externalurl = "ftp://violino.dsi.unifi.it";
        var internalurl = "";
        var lockEndPoint = "http://violino.dsi.unifi.it:8080/LockUnlockWS/lockunlock";
        print("Registering COMPOSITE object to AXCS");
        newObj.registerToAXCS();
        print("Uploading protected COMPOSITE object on Factory DB");
        if(!newObj.uploadToDB())
        {
            var error = "Upload request failure: "+compositeAXOID;
            print(error);
        }
        print("Uploading protected COMPOSITE object in Distribution DB");
        if(!newObj.uploadToDB(saverEndPoint,user,passwd,usingftp,externalurl,internalurl,lockEndPoint))
        {
            var error = "Upload request failure: "+compositeAXOID;
            print(error);
            return false;
        } 
    }
    
   
    appendToFile(productionFilePath,newObj.AXOID+"\n");
   
   
   newObj.dispose();
   newObj = null;
   return true;
}

// Function for creating the Axmedis Object by composing and converting resources
function main()
{
    var axoids = retrieveAXOIDfromSelection();
    if(axoids==null || axoids.lenght==0)
        return true
  var count = axoids.length-(axoids.length%3);
  
  for(j=0; j<count; j=j+3)
  { 
      var obj = new Array();
      print("Retrieving object #"+j);
      obj[0] = new AxmedisObject();
      if(!obj[0].load(axoids[j]))
        print("Impossible to retrieve object #"+j);
      else
      {
          obj[0].dispose();
          obj[0] = null;
      }
      
      print("Retrieving object #"+j+1);
      obj[1] = new AxmedisObject();
      if(!obj[1].load(axoids[j+1]))
        print("Impossible to retrieve object #"+(j+1));
      else
      {
          obj[1].dispose();
          obj[1] = null;
      }
        
      print("Retrieving object #"+j+2);
      obj[2] = new AxmedisObject();
      if(!obj[2].load(axoids[j+2]))
        print("Impossible to retrieve object #"+(j+2));
      else
      {
          obj[2].dispose();
          obj[2] = null;
      }
        
      title = "Collection #"+(j-2);
      if(createCompositeAxmedisObject(obj))
         print("COMPOSITE OBJECT created!");
     
      if(obj[0] != null)
      {
          obj[0].dispose();
          obj[0] = null;
      }
      if(obj[1] != null)
      {
          obj[1].dispose();
          obj[1] = null;
      }
      if(obj[2] != null)
      {
          obj[2].dispose();
          obj[2] = null;
      }
  }
  return true;
}

var productionFilePath = "X:\\production2.txt"; // shared folder
var AXDID = "URN:AXMEDIS:00001:BUS:3A2F35F1-5E91-314C-A51A-D07D75C216C7";
var AXCID = "URN:AXMEDIS:00001:BUS:00000000-0000-0000-0000-000000000000"; 
var creatorID = AXCID;
var userID = AXDID;
var title = "";
a = main();]]>
        </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="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 fillObjectCreatorCredentials(obj)
{
    var axcsUri = "http://cobalto: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>
        <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="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, count)
{
        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 = count;
        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>
      </Rule_Body>
      <Dependencies/>
    </AXCP_Rule>
  </Definition>
</Rule>

