Commit 38fb78da authored by Tristan Cavelier's avatar Tristan Cavelier

OfficeJS updated to work with the latest version of JIO - conflict solver not implemented

parent 97c53972
...@@ -10,13 +10,14 @@ ...@@ -10,13 +10,14 @@
<script type="text/javascript" src="lib/jquery/jquery.js"></script> <script type="text/javascript" src="lib/jquery/jquery.js"></script>
<script type="text/javascript" src="lib/jstorage/jstorage.js"></script> <script type="text/javascript" src="lib/jstorage/jstorage.js"></script>
<script type="text/javascript" src="lib/renderjs/renderjs.js"></script> <script type="text/javascript" src="lib/renderjs/renderjs.js"></script>
<script type="text/javascript" src="lib/md5/md5.js"></script>
<script type="text/javascript" src="lib/jio/localorcookiestorage.min.js"></script>
<script type="text/javascript" src="lib/jio/jio.min.js"></script> <script type="text/javascript" src="lib/jio/jio.min.js"></script>
<script type="text/javascript" src="lib/base64/base64.js"></script>
<script type="text/javascript" src="lib/sjcl/sjcl.min.js"></script> <script type="text/javascript" src="lib/sjcl/sjcl.min.js"></script>
<script type="text/javascript" src="lib/jsSha2/sha2.js"></script> <script type="text/javascript" src="lib/jsSha2/sha2.js"></script>
<script type="text/javascript" src="lib/jio/jio.storage.min.js"></script> <script type="text/javascript" src="lib/jio/localstorage.js"></script>
<script type="text/javascript" src="lib/jio/indexstorage.js"></script>
<script type="text/javascript" src="lib/jio/revisionstorage.js"></script>
<script type="text/javascript" src="lib/jio/replicaterevisionstorage.js"></script>
</head> </head>
<body> <body>
......
/*! JIO - v0.1.0 - 2012-10-12 (function(scope,hex_md5){"use strict";var localstorage;if(typeof localStorage!=="undefined"){localstorage={getItem:function(item){var value=localStorage.getItem(item);return value===null?null:JSON.parse(value)},setItem:function(item,value){return localStorage.setItem(item,JSON.stringify(value))},removeItem:function(item){delete localStorage[item]},clone:function(){return JSON.parse(JSON.stringify(localStorage))}}}else{(function(){var pseudo_localStorage={};localstorage={getItem:function(item){var value=pseudo_localStorage[item];return value===undefined?null:JSON.parse(pseudo_localStorage[item])},setItem:function(item,value){pseudo_localStorage[item]=JSON.stringify(value)},removeItem:function(item){delete pseudo_localStorage[item]},clone:function(){return JSON.parse(JSON.stringify(pseudo_localStorage))}}})()}var jioException=function(spec,my){var that={};spec=spec||{};my=my||{};that.name="jioException";that.message=spec.message||"Unknown Reason.";that.toString=function(){return that.name+": "+that.message};return that};var invalidCommandState=function(spec,my){var that=jioException(spec,my),command=spec.command;spec=spec||{};that.name="invalidCommandState";that.toString=function(){return that.name+": "+command.getLabel()+", "+that.message};return that};var invalidStorage=function(spec,my){var that=jioException(spec,my),type=spec.storage.getType();spec=spec||{};that.name="invalidStorage";that.toString=function(){return that.name+": "+'Type "'+type+'", '+that.message};return that};var invalidStorageType=function(spec,my){var that=jioException(spec,my),type=spec.type;that.name="invalidStorageType";that.toString=function(){return that.name+": "+type+", "+that.message};return that};var jobNotReadyException=function(spec,my){var that=jioException(spec,my);that.name="jobNotReadyException";return that};var tooMuchTriesJobException=function(spec,my){var that=jioException(spec,my);that.name="tooMuchTriesJobException";return that};var invalidJobException=function(spec,my){var that=jioException(spec,my);that.name="invalidJobException";return that};var jio=function(spec){var storage=function(spec,my){var that={},priv={};spec=spec||{};my=my||{};priv.type=spec.type||"";Object.defineProperty(that,"getType",{configurable:false,enumerable:false,writable:false,value:function(){return priv.type}});that.execute=function(command){that.success=command.success;that.error=command.error;that.retry=command.retry;that.end=command.end;if(that.validate(command)){command.executeOn(that)}};that.isValid=function(){return true};that.validate=function(){var mess=that.validateState();if(mess){that.error({status:0,statusText:"Invalid Storage",error:"invalid_storage",message:mess,reason:mess});return false}return true};that.serialized=function(){var o=that.specToStore()||{};o.type=that.getType();return o};that.specToStore=function(){return{}};that.validateState=function(){return""};that.post=function(){setTimeout(function(){that.error({status:0,statusText:"Not Implemented",error:"not_implemented",message:'"Post" command is not implemented',reason:"Command not implemented"})})};that.put=function(){setTimeout(function(){that.error({status:0,statusText:"Not Implemented",error:"not_implemented",message:'"Put" command is not implemented',reason:"Command not implemented"})})};that.putAttachment=function(){setTimeout(function(){that.error({status:0,statusText:"Not Implemented",error:"not_implemented",message:'"PutAttachment" command is not implemented',reason:"Command not implemented"})})};that.get=function(){setTimeout(function(){that.error({status:0,statusText:"Not Implemented",error:"not_implemented",message:'"Get" command is not implemented',reason:"Command not implemented"})})};that.allDocs=function(){setTimeout(function(){that.error({status:0,statusText:"Not Implemented",error:"not_implemented",message:'"AllDocs" command is not implemented',reason:"Command not implemented"})})};that.remove=function(){setTimeout(function(){that.error({status:0,statusText:"Not Implemented",error:"not_implemented",message:'"Remove" command is not implemented',reason:"Command not implemented"})})};that.check=function(command){setTimeout(function(){that.success({ok:true,id:command.getDocId()})})};that.repair=function(command){setTimeout(function(){that.success({ok:true,id:command.getDocId()})})};that.success=function(){};that.retry=function(){};that.error=function(){};that.end=function(){};priv.newCommand=function(method,spec){var o=spec||{};o.label=method;return command(o,my)};priv.storage=my.storage;delete my.storage;that.addJob=function(method,storage_spec,doc,option,success,error){var command_opt={doc:doc,options:option,callbacks:{success:success,error:error}};jobManager.addJob(job({storage:priv.storage(storage_spec||{}),command:priv.newCommand(method,command_opt)},my))};return that};var allDocsCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"allDocs"};that.executeOn=function(storage){storage.allDocs(that)};that.canBeRestored=function(){return false};that.validateState=function(){return true};return that};var checkCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"check"};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}return true};that.executeOn=function(storage){storage.check(that)};that.canBeRestored=function(){return false};return that};var command=function(spec,my){var that={},priv={};spec=spec||{};my=my||{};priv.commandlist={post:postCommand,put:putCommand,get:getCommand,remove:removeCommand,allDocs:allDocsCommand,getAttachment:getAttachmentCommand,putAttachment:putAttachmentCommand,removeAttachment:removeAttachmentCommand,check:checkCommand,repair:repairCommand};if(spec.label&&priv.commandlist[spec.label]){priv.label=spec.label;delete spec.label;return priv.commandlist[priv.label](spec,my)}priv.tried=0;priv.doc=spec.doc||{};if(typeof priv.doc!=="object"){priv.doc={_id:priv.doc.toString()}}priv.option=spec.options||{};priv.callbacks=spec.callbacks||{};priv.success=[priv.callbacks.success||function(){}];priv.error=[priv.callbacks.error||function(){}];priv.retry=function(){that.error({status:13,statusText:"Fail Retry",error:"fail_retry",message:"Impossible to retry.",reason:"Impossible to retry."})};priv.end=function(){};priv.on_going=false;that.serialized=function(){var o={};o.label=that.getLabel();o.tried=priv.tried;o.doc=that.cloneDoc();o.option=that.cloneOption();return o};that.getLabel=function(){return"command"};that.getDocId=function(){return priv.doc._id};that.getAttachmentId=function(){return priv.doc._attachment};that.getAttachmentData=function(){return priv.doc._data||""};that.getAttachmentLength=function(){return(priv.doc._data||"").length};that.getAttachmentMimeType=function(){return priv.doc._mimetype};that.md5SumAttachmentData=function(){return hex_md5(priv.doc._data||"")};that.getDocInfo=function(infoname){return priv.doc[infoname]};that.getOption=function(optionname){return priv.option[optionname]};that.validate=function(storage){if(typeof priv.doc._id==="string"&&!priv.doc._id.match("^[^/]+([/][^/]+)?$")){that.error({status:21,statusText:"Invalid Document Id",error:"invalid_document_id",message:'The document id must be like "abc" or "abc/def".',reason:'The document id is no like "abc" or "abc/def"'});return false}if(!that.validateState()){return false}return storage.validate()};that.validateState=function(){return true};that.canBeRetried=function(){return priv.option.max_retry===undefined||priv.option.max_retry===0||priv.tried<priv.option.max_retry};that.getTried=function(){return priv.tried};that.execute=function(storage){if(!priv.on_going){if(that.validate(storage)){priv.tried+=1;priv.on_going=true;storage.execute(that)}}};that.executeOn=function(storage){};that.success=function(return_value){var i;priv.on_going=false;for(i=0;i<priv.success.length;i+=1){priv.success[i](return_value)}priv.end(doneStatus());priv.success=[];priv.error=[]};that.retry=function(return_error){priv.on_going=false;if(that.canBeRetried()){priv.retry()}else{that.error(return_error)}};that.error=function(return_error){var i;priv.on_going=false;for(i=0;i<priv.error.length;i+=1){priv.error[i](return_error)}priv.end(failStatus());priv.success=[];priv.error=[]};that.end=function(){priv.end(doneStatus())};that.addCallbacks=function(success,error){if(arguments.length>1){priv.success.push(success||function(){});priv.error.push(error||function(){})}else{priv.success.push(function(response){(success||function(){})(undefined,response)});priv.error.push(function(err){(success||function(){})(err,undefined)})}};that.onSuccessDo=function(fun){if(fun){priv.success=fun}else{return priv.success}};that.onErrorDo=function(fun){if(fun){priv.error=fun}else{return priv.error}};that.onEndDo=function(fun){priv.end=fun};that.onRetryDo=function(fun){priv.retry=fun};that.canBeRestored=function(){return true};that.clone=function(){return command(that.serialized(),my)};that.cloneOption=function(){return JSON.parse(JSON.stringify(priv.option))};that.cloneDoc=function(){return JSON.parse(JSON.stringify(priv.doc))};return that};var getAttachmentCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"getAttachment"};that.executeOn=function(storage){storage.getAttachment(that)};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}if(typeof that.getAttachmentId()!=="string"){that.error({status:22,statusText:"Attachment Id Required",error:"attachment_id_required",message:"The attachment id must be set",reason:"Attachment id not set"});return false}if(that.getAttachmentId()===""){that.error({status:23,statusText:"Invalid Attachment Id",error:"invalid_attachment_id",message:"The attachment id must not be an empty string",reason:"Attachment id is empty"})}return true};return that};var getCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"get"};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}return true};that.executeOn=function(storage){storage.get(that)};that.canBeRestored=function(){return false};return that};var postCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"post"};that.validateState=function(){return true};that.executeOn=function(storage){storage.post(that)};return that};var putAttachmentCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"putAttachment"};that.executeOn=function(storage){storage.putAttachment(that)};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}if(typeof that.getAttachmentId()!=="string"){that.error({status:22,statusText:"Attachment Id Required",error:"attachment_id_required",message:"The attachment id must be set",reason:"Attachment id not set"});return false}if(that.getAttachmentId()===""){that.error({status:23,statusText:"Invalid Attachment Id",error:"invalid_attachment_id",message:"The attachment id must not be an empty string",reason:"Attachment id is empty"})}return true};return that};var putCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"put"};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}return true};that.executeOn=function(storage){storage.put(that)};return that};var removeAttachmentCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"removeAttachment"};that.executeOn=function(storage){storage.removeAttachment(that)};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}if(typeof that.getAttachmentId()!=="string"){that.error({status:22,statusText:"Attachment Id Required",error:"attachment_id_required",message:"The attachment id must be set",reason:"Attachment id not set"});return false}if(that.getAttachmentId()===""){that.error({status:23,statusText:"Invalid Attachment Id",error:"invalid_attachment_id",message:"The attachment id must not be an empty string",reason:"Attachment id is empty"})}return true};return that};var removeCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"remove"};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}return true};that.executeOn=function(storage){storage.remove(that)};return that};var repairCommand=function(spec,my){var that=command(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"repair"};that.validateState=function(){if(!(typeof that.getDocId()==="string"&&that.getDocId()!=="")){that.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"The document id is not provided",reason:"Document id is undefined"});return false}return true};that.executeOn=function(storage){storage.repair(that)};return that};var doneStatus=function(spec,my){var that=jobStatus(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"done"};that.canStart=function(){return false};that.canRestart=function(){return false};that.isDone=function(){return true};return that};var failStatus=function(spec,my){var that=jobStatus(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"fail"};that.canStart=function(){return false};that.canRestart=function(){return true};return that};var initialStatus=function(spec,my){var that=jobStatus(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"initial"};that.canStart=function(){return true};that.canRestart=function(){return true};return that};var jobStatus=function(spec,my){var that={};spec=spec||{};my=my||{};that.getLabel=function(){return"job status"};that.canStart=function(){};that.canRestart=function(){};that.serialized=function(){return{label:that.getLabel()}};that.isWaitStatus=function(){return false};that.isDone=function(){return false};return that};var onGoingStatus=function(spec,my){var that=jobStatus(spec,my);spec=spec||{};my=my||{};that.getLabel=function(){return"on going"};that.canStart=function(){return false};that.canRestart=function(){return false};return that};var waitStatus=function(spec,my){var that=jobStatus(spec,my),priv={};spec=spec||{};my=my||{};priv.job_id_array=spec.job_id_array||[];priv.threshold=0;that.getLabel=function(){return"wait"};priv.refreshJobIdArray=function(){var tmp_job_id_array=[],i;for(i=0;i<priv.job_id_array.length;i+=1){if(jobManager.jobIdExists(priv.job_id_array[i])){tmp_job_id_array.push(priv.job_id_array[i])}}priv.job_id_array=tmp_job_id_array};that.waitForJob=function(job){var i;for(i=0;i<priv.job_id_array.length;i+=1){if(priv.job_id_array[i]===job.getId()){return}}priv.job_id_array.push(job.getId())};that.dontWaitForJob=function(job){var i,tmp_job_id_array=[];for(i=0;i<priv.job_id_array.length;i+=1){if(priv.job_id_array[i]!==job.getId()){tmp_job_id_array.push(priv.job_id_array[i])}}priv.job_id_array=tmp_job_id_array};that.waitForTime=function(ms){priv.threshold=Date.now()+ms};that.stopWaitForTime=function(){priv.threshold=0};that.canStart=function(){priv.refreshJobIdArray();return priv.job_id_array.length===0&&Date.now()>=priv.threshold};that.canRestart=function(){return that.canStart()};that.serialized=function(){return{label:that.getLabel(),waitfortime:priv.threshold,waitforjob:priv.job_id_array}};that.isWaitStatus=function(){return true};return that};var job=function(spec){var that={},priv={};spec=spec||{};priv.id=jobIdHandler.nextId();priv.command=spec.command;priv.storage=spec.storage;priv.status=initialStatus();priv.date=new Date;if(!priv.storage){throw invalidJobException({job:that,message:"No storage set"})}if(!priv.command){throw invalidJobException({job:that,message:"No command set"})}that.getCommand=function(){return priv.command};that.getStatus=function(){return priv.status};that.getId=function(){return priv.id};that.getStorage=function(){return priv.storage};that.getDate=function(){return priv.date};that.isReady=function(){if(priv.command.getTried()===0){return priv.status.canStart()}return priv.status.canRestart()};that.serialized=function(){return{id:priv.id,date:priv.date.getTime(),status:priv.status.serialized(),command:priv.command.serialized(),storage:priv.storage.serialized()}};that.waitForJob=function(job){if(priv.status.getLabel()!=="wait"){priv.status=waitStatus({})}priv.status.waitForJob(job)};that.dontWaitFor=function(job){if(priv.status.getLabel()==="wait"){priv.status.dontWaitForJob(job)}};that.waitForTime=function(ms){if(priv.status.getLabel()!=="wait"){priv.status=waitStatus({})}priv.status.waitForTime(ms)};that.stopWaitForTime=function(){if(priv.status.getLabel()==="wait"){priv.status.stopWaitForTime()}};that.eliminated=function(){priv.command.error({status:10,statusText:"Stopped",error:"stopped",message:"This job has been stopped by another one.",reason:"this job has been stopped by another one"})};that.notAccepted=function(){priv.command.onEndDo(function(){priv.status=failStatus();jobManager.terminateJob(that)});priv.command.error({status:11,statusText:"Not Accepted",error:"not_accepted",message:"This job is already running.",reason:"this job is already running"})};that.update=function(job){priv.command.addCallbacks(job.getCommand().onSuccessDo()[0],job.getCommand().onErrorDo()[0]);priv.date=new Date(job.getDate().getTime())};that.execute=function(){if(!that.getCommand().canBeRetried()){throw tooMuchTriesJobException({job:that,message:"The job was invoked too much time."})}if(!that.isReady()){throw jobNotReadyException({job:that,message:"Can not execute this job."})}priv.status=onGoingStatus();priv.command.onRetryDo(function(){var ms=priv.command.getTried();ms=ms*ms*200;if(ms>1e4){ms=1e4}that.waitForTime(ms)});priv.command.onEndDo(function(status){priv.status=status;jobManager.terminateJob(that)});priv.command.execute(priv.storage)};return that};var announcement=function(spec,my){var that={},callback_a=[],announcer=spec.announcer||{};spec=spec||{};my=my||{};that.add=function(callback){callback_a.push(callback)};that.remove=function(callback){var i,tmp_callback_a=[];for(i=0;i<callback_a.length;i+=1){if(callback_a[i]!==callback){tmp_callback_a.push(callback_a[i])}}callback_a=tmp_callback_a};that.register=function(){announcer.register(that)};that.unregister=function(){announcer.unregister(that)};that.trigger=function(args){var i;for(i=0;i<callback_a.length;i+=1){callback_a[i].apply(null,args)}};return that};var activityUpdater=function(spec,my){var that={},priv={};spec=spec||{};my=my||{};priv.id=spec.id||0;priv.interval=400;priv.interval_id=null;priv.touch=function(){localstorage.setItem("jio/id/"+priv.id,Date.now())};that.setId=function(id){priv.id=id};that.setIntervalDelay=function(ms){priv.interval=ms};that.getIntervalDelay=function(){return priv.interval};that.start=function(){if(!priv.interval_id){priv.touch();priv.interval_id=setInterval(function(){priv.touch()},priv.interval)}};that.stop=function(){if(priv.interval_id!==null){clearInterval(priv.interval_id);priv.interval_id=null}};return that}();var announcer=function(spec,my){var that={},announcement_o={};spec=spec||{};my=my||{};that.register=function(name){if(!announcement_o[name]){announcement_o[name]=announcement()}};that.unregister=function(name){if(announcement_o[name]){delete announcement_o[name]}};that.at=function(name){return announcement_o[name]};that.on=function(name,callback){that.register(name);that.at(name).add(callback)};that.trigger=function(name,args){that.at(name).trigger(args)};return that}();var jobIdHandler=function(spec){var that={},id=0;spec=spec||{};that.nextId=function(){id=id+1;return id};return that}();var jobManager=function(spec){var that={},job_array_name="jio/job_array",priv={};spec=spec||{};priv.id=spec.id;priv.interval_id=null;priv.interval=200;priv.job_array=[];priv.getJobArrayName=function(){return job_array_name+"/"+priv.id};priv.getJobArray=function(){return localstorage.getItem(priv.getJobArrayName())||[]};priv.copyJobArrayToLocal=function(){var new_a=[],i;for(i=0;i<priv.job_array.length;i+=1){new_a.push(priv.job_array[i].serialized())}localstorage.setItem(priv.getJobArrayName(),new_a)};priv.removeJob=function(job){var i,tmp_job_array=[];for(i=0;i<priv.job_array.length;i+=1){if(priv.job_array[i]!==job){tmp_job_array.push(priv.job_array[i])}}priv.job_array=tmp_job_array;priv.copyJobArrayToLocal()};that.setId=function(id){priv.id=id};that.start=function(){var i;if(priv.interval_id===null){priv.interval_id=setInterval(function(){priv.restoreOldJio();for(i=0;i<priv.job_array.length;i+=1){that.execute(priv.job_array[i])}},priv.interval)}};that.stop=function(){if(priv.interval_id!==null){clearInterval(priv.interval_id);priv.interval_id=null;if(priv.job_array.length===0){localstorage.removeItem(priv.getJobArrayName())}}};priv.restoreOldJio=function(){var i,jio_id_a;priv.lastrestore=priv.lastrestore||0;if(priv.lastrestore>Date.now()-2e3){return}jio_id_a=localstorage.getItem("jio/id_array")||[];for(i=0;i<jio_id_a.length;i+=1){priv.restoreOldJioId(jio_id_a[i])}priv.lastrestore=Date.now()};priv.restoreOldJioId=function(id){var jio_date;jio_date=localstorage.getItem("jio/id/"+id)||0;if(new Date(jio_date).getTime()<Date.now()-1e4){priv.restoreOldJobFromJioId(id);priv.removeOldJioId(id);priv.removeJobArrayFromJioId(id)}};priv.restoreOldJobFromJioId=function(id){var i,command_object,jio_job_array;jio_job_array=localstorage.getItem("jio/job_array/"+id)||[];for(i=0;i<jio_job_array.length;i+=1){command_object=command(jio_job_array[i].command);if(command_object.canBeRestored()){that.addJob(job({storage:that.storage(jio_job_array[i].storage),command:command_object}))}}};priv.removeOldJioId=function(id){var i,jio_id_array,new_array=[];jio_id_array=localstorage.getItem("jio/id_array")||[];for(i=0;i<jio_id_array.length;i+=1){if(jio_id_array[i]!==id){new_array.push(jio_id_array[i])}}localstorage.setItem("jio/id_array",new_array);localstorage.removeItem("jio/id/"+id)};priv.removeJobArrayFromJioId=function(id){localstorage.removeItem("jio/job_array/"+id)};that.execute=function(job){try{job.execute()}catch(e){switch(e.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw e}}priv.copyJobArrayToLocal()};that.jobIdExists=function(id){var i;for(i=0;i<priv.job_array.length;i+=1){if(priv.job_array[i].getId()===id){return true}}return false};that.terminateJob=function(job){priv.removeJob(job)};that.addJob=function(job){var result_array=that.validateJobAccordingToJobList(priv.job_array,job);priv.appendJob(job,result_array)};that.validateJobAccordingToJobList=function(job_array,job){var i,result_array=[];for(i=0;i<job_array.length;i+=1){result_array.push(jobRules.validateJobAccordingToJob(job_array[i],job))}return result_array};priv.appendJob=function(job,result_array){var i;if(priv.job_array.length!==result_array.length){throw new RangeError("Array out of bound")}for(i=0;i<result_array.length;i+=1){if(result_array[i].action==="dont accept"){return job.notAccepted()}}for(i=0;i<result_array.length;i+=1){switch(result_array[i].action){case"eliminate":result_array[i].job.eliminated();priv.removeJob(result_array[i].job);break;case"update":result_array[i].job.update(job);priv.copyJobArrayToLocal();return;case"wait":job.waitForJob(result_array[i].job);break;default:break}}priv.job_array.push(job);priv.copyJobArrayToLocal()};that.serialized=function(){var a=[],i,job_array=priv.job_array||[];for(i=0;i<job_array.length;i+=1){a.push(job_array[i].serialized())}return a};return that}();var jobRules=function(){var that={},priv={};priv.compare={};priv.action={};Object.defineProperty(that,"eliminate",{configurable:false,enumerable:false,writable:false,value:function(){return"eliminate"}});Object.defineProperty(that,"update",{configurable:false,enumerable:false,writable:false,value:function(){return"update"}});Object.defineProperty(that,"dontAccept",{configurable:false,enumerable:false,writable:false,value:function(){return"dont accept"}});Object.defineProperty(that,"wait",{configurable:false,enumerable:false,writable:false,value:function(){return"wait"}});Object.defineProperty(that,"ok",{configurable:false,enumerable:false,writable:false,value:function(){return"none"}});that.default_action=that.ok;that.default_compare=function(job1,job2){return job1.getId()!==job2.getId()&&job1.getStatus().getLabel()!=="done"&&job1.getStatus().getLabel()!=="fail"&&JSON.stringify(job1.getStorage().serialized())===JSON.stringify(job2.getStorage().serialized())};Object.defineProperty(that,"sameDocumentId",{configurable:false,enumerable:false,writable:false,value:function(job1,job2){return job1.getCommand().getDocId()===job2.getCommand().getDocId()}});Object.defineProperty(that,"sameRevision",{configurable:false,enumerable:false,writable:false,value:function(job1,job2){return job1.getCommand().getDocInfo("_rev")===job2.getCommand().getDocInfo("_rev")}});Object.defineProperty(that,"sameAttachmentId",{configurable:false,enumerable:false,writable:false,value:function(job1,job2){return job1.getCommand().getAttachmentId()===job2.getCommand().getAttachmentId()}});Object.defineProperty(that,"sameDocument",{configurable:false,enumerable:false,writable:false,value:function(job1,job2){return JSON.stringify(job1.getCommand().cloneDoc())===JSON.stringify(job2.getCommand().cloneDoc())}});Object.defineProperty(that,"sameOption",{configurable:false,enumerable:false,writable:false,value:function(job1,job2){return JSON.stringify(job1.getCommand().cloneOption())===JSON.stringify(job2.getCommand().cloneOption())}});priv.getAction=function(job1,job2){var method1,method2,tmp=priv.action,i,j,condition_list=[],res;method1=job1.getCommand().getLabel();method2=job2.getCommand().getLabel();tmp=tmp[method1]=tmp[method1]||{};tmp=tmp[method2]=tmp[method2]||[];for(i=0;i<tmp.length;i+=1){condition_list=tmp[i].condition_list;res=true;for(j=0;j<condition_list.length;j+=1){if(!condition_list[j](job1,job2)){res=false;break}}if(res){return tmp[i].rule()}}return that.default_action()};priv.canCompare=function(job1,job2){var method1,method2;method1=job1.getCommand().getLabel();method2=job2.getCommand().getLabel();if(priv.compare[method1]&&priv.compare[method1][method2]){return priv.compare[method1][method2](job1,job2)}return that.default_compare(job1,job2)};Object.defineProperty(that,"validateJobAccordingToJob",{configurable:false,enumerable:false,writable:false,value:function(job1,job2){if(priv.canCompare(job1,job2)){return{action:priv.getAction(job1,job2),job:job1}}return{action:that.default_action(job1,job2),job:job1}}});Object.defineProperty(that,"addActionRule",{configurable:false,enumerable:false,writable:false,value:function(method1,method2,condition_list,rule){var tmp=priv.action;tmp=tmp[method1]=tmp[method1]||{};tmp=tmp[method2]=tmp[method2]||[];tmp.push({condition_list:condition_list,rule:rule})}});Object.defineProperty(that,"addCompareRule",{configurable:false,enumerable:false,writable:false,value:function(method1,method2,rule){priv.compare[method1]=priv.compare[method1]||{};priv.compare[method1][method2]=rule}});that.addActionRule("post","post",[that.sameDocument],that.update);that.addActionRule("post","post",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("post","put",[that.sameDocument],that.update);that.addActionRule("post","put",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("post","putAttachment",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("post","remove",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("put","post",[that.sameDocument],that.update);that.addActionRule("put","post",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("put","put",[that.sameDocument],that.update);that.addActionRule("put","put",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("put","putAttachment",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("put","remove",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("putAttachment","post",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("putAttachment","put",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("putAttachment","putAttachment",[that.sameDocument],that.update);that.addActionRule("putAttachment","putAttachment",[that.sameDocumentId,that.sameRevision,that.sameAttachmentId],that.wait);that.addActionRule("putAttachment","remove",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("remove","post",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("remove","put",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("remove","putAttachment",[that.sameDocumentId,that.sameRevision],that.wait);that.addActionRule("remove","remove",[that.sameDocumentId,that.sameRevision],that.update);that.addActionRule("get","get",[that.sameDocument,that.sameOption],that.update);that.addActionRule("allDocs","allDocs",[that.sameDocument,that.sameOption],that.update);return that}();var that={},priv={},jio_id_array_name="jio/id_array";spec=spec||{};priv.id=null;priv.storage_spec=spec;priv.environments={};priv.init=function(){if(priv.id===null){var i,jio_id_a=localstorage.getItem(jio_id_array_name)||[];priv.id=1;for(i=0;i<jio_id_a.length;i+=1){if(jio_id_a[i]>=priv.id){priv.id=jio_id_a[i]+1}}jio_id_a.push(priv.id);localstorage.setItem(jio_id_array_name,jio_id_a);activityUpdater.setId(priv.id);jobManager.setId(priv.id)}};Object.defineProperty(that,"storage",{configurable:false,enumerable:false,writable:false,value:function(spec,my,forcetype){var spec_str,type;spec=spec||{};my=my||{};my.basicStorage=storage;spec_str=JSON.stringify(spec);priv.environments[spec_str]=priv.environments[spec_str]||{};my.env=priv.environments[spec_str];my.storage=that.storage;type=forcetype||spec.type||"base";if(type==="base"){return storage(spec,my)}if(!storage_type_object[type]){throw invalidStorageType({type:type,message:"Storage does not exists."})}return storage_type_object[type](spec,my)}});jobManager.storage=that.storage;Object.defineProperty(that,"start",{configurable:false,enumerable:false,writable:false,value:function(){priv.init();activityUpdater.start();jobManager.start()}});Object.defineProperty(that,"stop",{configurable:false,enumerable:false,writable:false,value:function(){jobManager.stop()}});Object.defineProperty(that,"close",{configurable:false,enumerable:false,writable:false,value:function(){activityUpdater.stop();jobManager.stop();priv.id=null}});Object.defineProperty(that,"getId",{configurable:false,enumerable:false,writable:false,value:function(){return priv.id
* Copyright (c) 2012 Nexedi; Licensed */ }});Object.defineProperty(that,"getJobRules",{configurable:false,enumerable:false,writable:false,value:function(){return jobRules}});Object.defineProperty(that,"validateStorageDescription",{configurable:false,enumerable:false,writable:false,value:function(description){return that.storage(description).isValid()}});Object.defineProperty(that,"getJobArray",{configurable:false,enumerable:false,writable:false,value:function(){return jobManager.serialized()}});priv.makeCallbacks=function(param,callback1,callback2){param.callback=function(err,val){if(err){param.error(err)}else{param.success(val)}};param.success=function(val){param.callback(undefined,val)};param.error=function(err){param.callback(err,undefined)};if(typeof callback1==="function"){if(typeof callback2==="function"){param.success=callback1;param.error=callback2}else{param.callback=callback1}}else{param.callback=function(){}}};priv.parametersToObject=function(list,default_options){var k,i=0,callbacks=[],param={options:{}};for(i=0;i<list.length;i+=1){if(typeof list[i]==="object"){param.options=list[i];for(k in default_options){if(typeof default_options[k]!==typeof list[i][k]){param.options[k]=default_options[k]}}}if(typeof list[i]==="function"){callbacks.push(list[i])}}priv.makeCallbacks(param,callbacks[0],callbacks[1]);return param};priv.addJob=function(commandCreator,spec){jobManager.addJob(job({storage:that.storage(priv.storage_spec),command:commandCreator(spec)}))};Object.defineProperty(that,"post",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:0});priv.addJob(postCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"put",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:0});priv.addJob(putCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"get",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:3});priv.addJob(getCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"remove",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,callback){var param=priv.parametersToObject([options,success,callback],{max_retry:0});priv.addJob(removeCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"allDocs",{configurable:false,enumerable:false,writable:false,value:function(options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:3});priv.addJob(allDocsCommand,{options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"getAttachment",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:3});priv.addJob(getAttachmentCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"putAttachment",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:0});priv.addJob(putAttachmentCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"removeAttachment",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,error){var param=priv.parametersToObject([options,success,error],{max_retry:0});priv.addJob(removeAttachmentCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"check",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,callback){var param=priv.parametersToObject([options,success,callback],{max_retry:3});priv.addJob(checkCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});Object.defineProperty(that,"repair",{configurable:false,enumerable:false,writable:false,value:function(doc,options,success,callback){var param=priv.parametersToObject([options,success,callback],{max_retry:3});priv.addJob(repairCommand,{doc:doc,options:param.options,callbacks:{success:param.success,error:param.error}})}});return that};var storage_type_object={base:function(){}};var jioNamespace=function(spec){var that={};spec=spec||{};Object.defineProperty(that,"newJio",{configurable:false,enumerable:false,writable:false,value:function(spec){var storage=spec,instance=null;if(typeof storage==="string"){storage=JSON.parse(storage)}else{storage=JSON.stringify(storage);if(storage!==undefined){storage=JSON.parse(storage)}}storage=storage||{type:"base"};instance=jio(storage);instance.start();return instance}});Object.defineProperty(that,"addStorageType",{configurable:false,enumerable:false,writable:false,value:function(type,constructor){constructor=constructor||function(){return null};if(storage_type_object[type]){throw invalidStorageType({type:type,message:"Already known."})}storage_type_object[type]=constructor}});return that}();Object.defineProperty(scope,"jIO",{configurable:false,enumerable:false,writable:false,value:jioNamespace})})(window,hex_md5);
var jIO=function(){"use strict";var e=function(e,t){var n={};return e=e||{},t=t||{},n.name="jioException",n.message=e.message||"Unknown Reason.",n.toString=function(){return n.name+": "+n.message},n},t=function(t,n){var r=e(t,n);t=t||{};var i=t.command;return r.name="invalidCommandState",r.toString=function(){return r.name+": "+i.getLabel()+", "+r.message},r},n=function(t,n){var r=e(t,n);t=t||{};var i=t.storage.getType();return r.name="invalidStorage",r.toString=function(){return r.name+": "+'Type "'+i+'", '+r.message},r},r=function(t,n){var r=e(t,n),i=t.type;return r.name="invalidStorageType",r.toString=function(){return r.name+": "+i+", "+r.message},r},i=function(t,n){var r=e(t,n);return r.name="jobNotReadyException",r},s=function(t,n){var r=e(t,n);return r.name="tooMuchTriesJobException",r},o=function(t,n){var r=e(t,n);return r.name="invalidJobException",r},u=function(e){var t=function(e,t){var r={};e=e||{},t=t||{};var i={};return i.type=e.type||"",Object.defineProperty(r,"getType",{configurable:!1,enumerable:!1,writable:!1,value:function(){return i.type}}),r.execute=function(e){r.success=e.success,r.error=e.error,r.retry=e.retry,r.end=e.end,r.validate(e)&&e.executeOn(r)},r.isValid=function(){return!0},r.validate=function(){var e=r.validateState();return e?(r.error({status:0,statusText:"Invalid Storage",error:"invalid_storage",message:e,reason:e}),!1):!0},r.serialized=function(){return{type:r.getType()}},r.saveDocument=function(e){r.error({status:0,statusText:"Unknown storage",error:"unknown_storage",message:"Unknown Storage"})},r.loadDocument=function(e){r.saveDocument()},r.removeDocument=function(e){r.saveDocument()},r.getDocumentList=function(e){r.saveDocument()},r.validateState=function(){return""},r.success=function(){},r.retry=function(){},r.error=function(){},r.end=function(){},i.newCommand=function(e,r){var i=r||{};return i.label=e,n(i,t)},r.addJob=function(e,n,r,s,o,u){var a={options:s,callbacks:{success:o,error:u}};r&&(e==="get"?a.docid=r:a.doc=r),T.addJob(b({storage:t.storage(n||{}),command:i.newCommand(e,a)},t))},r},n=function(e,t){var r={};e=e||{},t=t||{};var i={};return i.commandlist={post:h,put:c,get:f,remove:l,allDocs:u},e.label&&i.commandlist[e.label]?(i.label=e.label,delete e.label,i.commandlist[i.label](e,t)):(i.tried=0,i.doc=e.doc||{},i.docid=e.docid||"",i.option=e.options||{},i.callbacks=e.callbacks||{},i.success=i.callbacks.success||function(){},i.error=i.callbacks.error||function(){},i.retry=function(){r.error({status:13,statusText:"Fail Retry",error:"fail_retry",message:"Impossible to retry.",reason:"Impossible to retry."})},i.end=function(){},i.on_going=!1,r.serialized=function(){return{label:r.getLabel(),tried:i.tried,doc:r.cloneDoc(),option:r.cloneOption()}},r.getLabel=function(){return"command"},r.getDocId=function(){return i.docid||i.doc._id},r.getDocContent=function(){return i.doc.content},r.getDocInfo=function(e){return i.doc[e]},r.getOption=function(e){return i.option[e]},r.validate=function(e){return r.validateState()?e.validate():!1},r.validateState=function(){return typeof i.doc!="object"?(r.error({status:20,statusText:"Document_Id Required",error:"document_id_required",message:"No document id.",reason:"no document id"}),!1):!0},r.canBeRetried=function(){return typeof i.option.max_retry=="undefined"||i.option.max_retry===0||i.tried<i.option.max_retry},r.getTried=function(){return i.tried},r.execute=function(e){i.on_going||r.validate(e)&&(i.tried++,i.on_going=!0,e.execute(r))},r.executeOn=function(e){},r.success=function(e){i.on_going=!1,i.success(e),i.end(d())},r.retry=function(e){i.on_going=!1,r.canBeRetried()?i.retry():r.error(e)},r.error=function(e){i.on_going=!1,i.error(e),i.end(v())},r.end=function(){i.end(d())},r.onSuccessDo=function(e){if(!e)return i.success;i.success=e},r.onErrorDo=function(e){if(!e)return i.error;i.error=e},r.onEndDo=function(e){i.end=e},r.onRetryDo=function(e){i.retry=e},r.canBeRestored=function(){return!0},r.clone=function(){return n(r.serialized(),t)},r.cloneOption=function(){var e,t={};for(e in i.option)t[e]=i.option[e];return t},r.cloneDoc=function(){if(i.docid)return i.docid;var e,t={};for(e in i.doc)t[e]=i.doc[e];return t},r)},u=function(e,t){var r=n(e,t);return e=e||{},t=t||{},r.getLabel=function(){return"allDocs"},r.executeOn=function(e){e.allDocs(r)},r.canBeRestored=function(){return!1},r.validateState=function(){return!0},r},f=function(e,t){var r=n(e,t);return e=e||{},t=t||{},r.getLabel=function(){return"get"},r.validateState=function(){return r.getDocId()?!0:(r.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"No document id.",reason:"no document id"}),!1)},r.executeOn=function(e){e.get(r)},r.canBeRestored=function(){return!1},r},l=function(e,t){var r=n(e,t);return e=e||{},t=t||{},r.getLabel=function(){return"remove"},r.executeOn=function(e){e.remove(r)},r},c=function(e,t){var r=n(e,t);e=e||{},t=t||{};var i={};return r.getLabel=function(){return"put"},r.validate=function(){return typeof r.getDocInfo("content")!="string"?(r.error({status:21,statusText:"Content Required",error:"content_required",message:"No data to put.",reason:"no data to put"}),!1):r.validateState()},r.executeOn=function(e){e.put(r)},r},h=function(e,t){var r=n(e,t);e=e||{},t=t||{};var i={};return r.getLabel=function(){return"post"},r.validate=function(){return typeof r.getDocInfo("content")!="string"?(r.error({status:21,statusText:"Content Required",error:"content_required",message:"No data to put.",reason:"no data to put"}),!1):r.validateState()},r.executeOn=function(e){e.put(r)},r},p=function(e,t){var n={};return e=e||{},t=t||{},n.getLabel=function(){return"job status"},n.canStart=function(){},n.canRestart=function(){},n.serialized=function(){return{label:n.getLabel()}},n.isWaitStatus=function(){return!1},n.isDone=function(){return!1},n},d=function(e,t){var n=p(e,t);return e=e||{},t=t||{},n.getLabel=function(){return"done"},n.canStart=function(){return!1},n.canRestart=function(){return!1},n.isDone=function(){return!0},n},v=function(e,t){var n=p(e,t);return e=e||{},t=t||{},n.getLabel=function(){return"fail"},n.canStart=function(){return!1},n.canRestart=function(){return!0},n},m=function(e,t){var n=p(e,t);return e=e||{},t=t||{},n.getLabel=function(){return"initial"},n.canStart=function(){return!0},n.canRestart=function(){return!0},n},g=function(e,t){var n=p(e,t);return e=e||{},t=t||{},n.getLabel=function(){return"on going"},n.canStart=function(){return!1},n.canRestart=function(){return!1},n},y=function(e,t){var n=p(e,t);e=e||{},t=t||{};var r={};return r.job_id_array=e.job_id_array||[],r.threshold=0,n.getLabel=function(){return"wait"},r.refreshJobIdArray=function(){var e=[],t;for(t=0;t<r.job_id_array.length;t+=1)T.jobIdExists(r.job_id_array[t])&&e.push(r.job_id_array[t]);r.job_id_array=e},n.waitForJob=function(e){var t;for(t=0;t<r.job_id_array.length;t+=1)if(r.job_id_array[t]===e.getId())return;r.job_id_array.push(e.getId())},n.dontWaitForJob=function(e){var t,n=[];for(t=0;t<r.job_id_array.length;t+=1)r.job_id_array[t]!==e.getId()&&n.push(r.job_id_array[t]);r.job_id_array=n},n.waitForTime=function(e){r.threshold=Date.now()+e},n.stopWaitForTime=function(){r.threshold=0},n.canStart=function(){return r.refreshJobIdArray(),r.job_id_array.length===0&&Date.now()>=r.threshold},n.canRestart=function(){return n.canStart()},n.serialized=function(){return{label:n.getLabel(),waitfortime:r.threshold,waitforjob:r.job_id_array}},n.isWaitStatus=function(){return!0},n},b=function(e){var t={};e=e||{};var n={};n.id=x.nextId(),n.command=e.command,n.storage=e.storage,n.status=m(),n.date=new Date;if(!n.storage)throw o({job:t,message:"No storage set"});if(!n.command)throw o({job:t,message:"No command set"});return t.getCommand=function(){return n.command},t.getStatus=function(){return n.status},t.getId=function(){return n.id},t.getStorage=function(){return n.storage},t.getDate=function(){return n.date},t.isReady=function(){return n.command.getTried()===0?n.status.canStart():n.status.canRestart()},t.serialized=function(){return{id:n.id,date:n.date.getTime(),status:n.status.serialized(),command:n.command.serialized(),storage:n.storage.serialized()}},t.waitForJob=function(e){n.status.getLabel()!=="wait"&&(n.status=y({})),n.status.waitForJob(e)},t.dontWaitFor=function(e){n.status.getLabel()==="wait"&&n.status.dontWaitForJob(e)},t.waitForTime=function(e){n.status.getLabel()!=="wait"&&(n.status=y({})),n.status.waitForTime(e)},t.stopWaitForTime=function(){n.status.getLabel()==="wait"&&n.status.stopWaitForTime()},t.eliminated=function(){n.command.error({status:10,statusText:"Stopped",error:"stopped",message:"This job has been stopped by another one.",reason:"this job has been stopped by another one"})},t.notAccepted=function(){n.command.onEndDo(function(){n.status=v(),T.terminateJob(t)}),n.command.error({status:11,statusText:"Not Accepted",error:"not_accepted",message:"This job is already running.",reason:"this job is already running"})},t.update=function(e){n.command.error({status:12,statusText:"Replaced",error:"replaced",message:"Job has been replaced by another one.",reason:"job has been replaced by another one"}),n.date=new Date(e.getDate().getTime()),n.command=e.getCommand(),n.status=e.getStatus()},t.execute=function(){if(!t.getCommand().canBeRetried())throw s({job:t,message:"The job was invoked too much time."});if(!t.isReady())throw i({job:t,message:"Can not execute this job."});n.status=g(),n.command.onRetryDo(function(){var e=n.command.getTried();e=e*e*200,e>1e4&&(e=1e4),t.waitForTime(e)}),n.command.onEndDo(function(e){n.status=e,T.terminateJob(t)}),n.command.execute(n.storage)},t},w=function(e,t){var n={};e=e||{},t=t||{};var r=[],i=e.name||"",s=e.announcer||{};return n.add=function(e){r.push(e)},n.remove=function(e){var t,n=[];for(t=0;t<r.length;t+=1)r[t]!==e&&n.push(r[t]);r=n},n.register=function(){s.register(n)},n.unregister=function(){s.unregister(n)},n.trigger=function(e){var t;for(t=0;t<r.length;t++)r[t].apply(null,e)},n},E=function(e,t){var n={};e=e||{},t=t||{};var r={};return r.id=e.id||0,r.interval=400,r.interval_id=null,r.touch=function(){LocalOrCookieStorage.setItem("jio/id/"+r.id,Date.now())},n.setId=function(e){r.id=e},n.setIntervalDelay=function(e){r.interval=e},n.getIntervalDelay=function(){return r.interval},n.start=function(){r.interval_id||(r.touch(),r.interval_id=setInterval(function(){r.touch()},r.interval))},n.stop=function(){r.interval_id!==null&&(clearInterval(r.interval_id),r.interval_id=null)},n}(),S=function(e,t){var n={};e=e||{},t=t||{};var r={};return n.register=function(e){r[e]||(r[e]=w())},n.unregister=function(e){r[e]&&delete r[e]},n.at=function(e){return r[e]},n.on=function(e,t){n.register(e),n.at(e).add(t)},n.trigger=function(e,t){n.at(e).trigger(t)},n}(),x=function(e){var t={};e=e||{};var n=0;return t.nextId=function(){return n+=1,n},t}(),T=function(e){var t={};e=e||{};var r="jio/job_array",i={};return i.id=e.id,i.interval_id=null,i.interval=200,i.job_array=[],i.getJobArrayName=function(){return r+"/"+i.id},i.getJobArray=function(){return LocalOrCookieStorage.getItem(i.getJobArrayName())||[]},i.copyJobArrayToLocal=function(){var e=[],t;for(t=0;t<i.job_array.length;t+=1)e.push(i.job_array[t].serialized());LocalOrCookieStorage.setItem(i.getJobArrayName(),e)},i.removeJob=function(e){var t,n=[];for(t=0;t<i.job_array.length;t+=1)i.job_array[t]!==e&&n.push(i.job_array[t]);i.job_array=n,i.copyJobArrayToLocal()},t.setId=function(e){i.id=e},t.start=function(){var e;i.interval_id===null&&(i.interval_id=setInterval(function(){i.restoreOldJio();for(e=0;e<i.job_array.length;e+=1)t.execute(i.job_array[e])},i.interval))},t.stop=function(){i.interval_id!==null&&(clearInterval(i.interval_id),i.interval_id=null,i.job_array.length===0&&LocalOrCookieStorage.deleteItem(i.getJobArrayName()))},i.restoreOldJio=function(){var e,t;i.lastrestore=i.lastrestore||0;if(i.lastrestore>Date.now()-2e3)return;t=LocalOrCookieStorage.getItem("jio/id_array")||[];for(e=0;e<t.length;e+=1)i.restoreOldJioId(t[e]);i.lastrestore=Date.now()},i.restoreOldJioId=function(e){var t;t=LocalOrCookieStorage.getItem("jio/id/"+e)||0,(new Date(t)).getTime()<Date.now()-1e4&&(i.restoreOldJobFromJioId(e),i.removeOldJioId(e),i.removeJobArrayFromJioId(e))},i.restoreOldJobFromJioId=function(e){var r,i;i=LocalOrCookieStorage.getItem("jio/job_array/"+e)||[];for(r=0;r<i.length;r+=1){var s=n(i[r].command);s.canBeRestored()&&t.addJob(b({storage:t.storage(i[r].storage),command:s}))}},i.removeOldJioId=function(e){var t,n,r=[];n=LocalOrCookieStorage.getItem("jio/id_array")||[];for(t=0;t<n.length;t+=1)n[t]!==e&&r.push(n[t]);LocalOrCookieStorage.setItem("jio/id_array",r),LocalOrCookieStorage.deleteItem("jio/id/"+e)},i.removeJobArrayFromJioId=function(e){LocalOrCookieStorage.deleteItem("jio/job_array/"+e)},t.execute=function(e){try{e.execute()}catch(t){switch(t.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw t}}i.copyJobArrayToLocal()},t.jobIdExists=function(e){var t;for(t=0;t<i.job_array.length;t+=1)if(i.job_array[t].getId()===e)return!0;return!1},t.terminateJob=function(e){i.removeJob(e)},t.addJob=function(e){var n=t.validateJobAccordingToJobList(i.job_array,e);i.appendJob(e,n)},t.validateJobAccordingToJobList=function(e,t){var n,r=[];for(n=0;n<e.length;n+=1)r.push(N.validateJobAccordingToJob(e[n],t));return r},i.appendJob=function(e,t){var n;if(i.job_array.length!==t.length)throw new RangeError("Array out of bound");for(n=0;n<t.length;n+=1)if(t[n].action==="dont accept")return e.notAccepted();for(n=0;n<t.length;n+=1)switch(t[n].action){case"eliminate":t[n].job.eliminated(),i.removeJob(t[n].job);break;case"update":t[n].job.update(e),i.copyJobArrayToLocal();return;case"wait":e.waitForJob(t[n].job);break;default:}i.job_array.push(e),i.copyJobArrayToLocal()},t.serialized=function(){var e=[],t,n=i.job_array||[];for(t=0;t<n.length;t+=1)e.push(n[t].serialized());return e},t}(),N=function(e){var t={},n={};n.compare={},n.action={},Object.defineProperty(t,"eliminate",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"eliminate"}}),Object.defineProperty(t,"update",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"update"}}),Object.defineProperty(t,"dontAccept",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"dont accept"}}),Object.defineProperty(t,"wait",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"wait"}}),Object.defineProperty(t,"none",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"none"}}),t.default_action=t.none,t.default_compare=function(e,t){return e.getCommand().getDocId()===t.getCommand().getDocId()&&e.getCommand().getDocInfo("_rev")===t.getCommand().getDocInfo("_rev")&&e.getCommand().getOption("rev")===t.getCommand().getOption("rev")&&JSON.stringify(e.getStorage().serialized())===JSON.stringify(t.getStorage().serialized())},n.getAction=function(e,r){var i,s,o;return i=e.getCommand().getLabel(),s=r.getCommand().getLabel(),o=e.getStatus().getLabel()==="on going"?"on going":"not on going",n.action[i]&&n.action[i][o]&&n.action[i][o][s]?n.action[i][o][s](e,r):t.default_action(e,r)},n.canCompare=function(e,r){var i=e.getCommand().getLabel(),s=r.getCommand().getLabel();return n.compare[i]&&n.compare[s]?n.compare[i][s](e,r):t.default_compare(e,r)},Object.defineProperty(t,"validateJobAccordingToJob",{configurable:!1,enumerable:!1,writable:!1,value:function(e,r){return n.canCompare(e,r)?{action:n.getAction(e,r),job:e}:{action:t.default_action(e,r),job:e}}}),Object.defineProperty(t,"addActionRule",{configurable:!1,enumerable:!1,writable:!1,value:function(e,t,r,i){var s=t?"on going":"not on going";n.action[e]=n.action[e]||{},n.action[e][s]=n.action[e][s]||{},n.action[e][s][r]=i}}),Object.defineProperty(t,"addCompareRule",{configurable:!1,enumerable:!1,writable:!1,value:function(e,t,r){n.compare[e]=n.compare[e]||{},n.compare[e][t]=r}});var r=function(e,n){return e.getCommand().getDocInfo("content")===n.getCommand().getDocInfo("content")?t.dontAccept():t.wait()};return t.addActionRule("post",!0,"post",r),t.addActionRule("post",!0,"put",r),t.addActionRule("post",!0,"get",t.wait),t.addActionRule("post",!0,"remove",t.wait),t.addActionRule("post",!1,"post",t.update),t.addActionRule("post",!1,"put",t.update),t.addActionRule("post",!1,"get",t.wait),t.addActionRule("post",!1,"remove",t.eliminate),t.addActionRule("put",!0,"post",r),t.addActionRule("put",!0,"put",r),t.addActionRule("put",!0,"get",t.wait),t.addActionRule("put",!0,"remove",t.wait),t.addActionRule("put",!1,"post",t.update),t.addActionRule("put",!1,"put",t.update),t.addActionRule("put",!1,"get",t.wait),t.addActionRule("put",!1,"remove",t.eliminate),t.addActionRule("get",!0,"post",t.wait),t.addActionRule("get",!0,"put",t.wait),t.addActionRule("get",!0,"get",t.dontAccept),t.addActionRule("get",!0,"remove",t.wait),t.addActionRule("get",!1,"post",t.wait),t.addActionRule("get",!1,"put",t.wait),t.addActionRule("get",!1,"get",t.update),t.addActionRule("get",!1,"remove",t.wait),t.addActionRule("remove",!0,"get",t.dontAccept),t.addActionRule("remove",!0,"remove",t.dontAccept),t.addActionRule("remove",!1,"post",t.eliminate),t.addActionRule("remove",!1,"put",t.eliminate),t.addActionRule("remove",!1,"get",t.dontAccept),t.addActionRule("remove",!1,"remove",t.update),t.addActionRule("allDocs",!0,"allDocs",t.dontAccept),t.addActionRule("allDocs",!1,"allDocs",t.update),t}(),C={},k={};e=e||{};var L="jio/id_array";return k.id=null,k.storage_spec=e,k.init=function(){if(k.id===null){var e,t=LocalOrCookieStorage.getItem(L)||[];k.id=1;for(e=0;e<t.length;e+=1)t[e]>=k.id&&(k.id=t[e]+1);t.push(k.id),LocalOrCookieStorage.setItem(L,t),E.setId(k.id),T.setId(k.id)}},Object.defineProperty(C,"storage",{configurable:!1,enumerable:!1,writable:!1,value:function(e,n,i){e=e||{},n=n||{},n.basicStorage=t,n.storage=C.storage;var s=i||e.type||"base";if(s==="base")return t(e,n);if(!a[s])throw r({type:s,message:"Storage does not exists."});return a[s](e,n)}}),T.storage=C.storage,Object.defineProperty(C,"start",{configurable:!1,enumerable:!1,writable:!1,value:function(){k.init(),E.start(),T.start()}}),Object.defineProperty(C,"stop",{configurable:!1,enumerable:!1,writable:!1,value:function(){T.stop()}}),Object.defineProperty(C,"close",{configurable:!1,enumerable:!1,writable:!1,value:function(){E.stop(),T.stop(),k.id=null}}),Object.defineProperty(C,"getId",{configurable:!1,enumerable:!1,writable:!1,value:function(){return k.id}}),Object.defineProperty(C,"getJobRules",{configurable:!1,enumerable:!1,writable:!1,value:function(){return N}}),Object.defineProperty(C,"validateStorageDescription",{configurable:!1,enumerable:!1,writable:!1,value:function(e){return C.storage(e).isValid()}}),Object.defineProperty(C,"getJobArray",{configurable:!1,enumerable:!1,writable:!1,value:function(){return T.serialized()}}),k.getParam=function(e,t){var n={},r=0;return t||(n.doc=e[r],r++),typeof e[r]=="object"?(n.options=e[r],r++):n.options={},n.callback=function(e,t){},n.success=function(e){n.callback(undefined,e)},n.error=function(e){n.callback(e,undefined)},typeof e[r]=="function"&&(typeof e[r+1]=="function"?(n.success=e[r],n.error=e[r+1]):n.callback=e[r]),n},k.addJob=function(e,t){T.addJob(b({storage:C.storage(k.storage_spec),command:e(t)}))},Object.defineProperty(C,"post",{configurable:!1,enumerable:!1,writable:!1,value:function(){var e=k.getParam(arguments);e.options.max_retry=e.options.max_retry||0,k.addJob(h,{doc:e.doc,options:e.options,callbacks:{success:e.success,error:e.error}})}}),Object.defineProperty(C,"put",{configurable:!1,enumerable:!1,writable:!1,value:function(){var e=k.getParam(arguments);e.options.max_retry=e.options.max_retry||0,k.addJob(c,{doc:e.doc,options:e.options,callbacks:{success:e.success,error:e.error}})}}),Object.defineProperty(C,"get",{configurable:!1,enumerable:!1,writable:!1,value:function(){var e=k.getParam(arguments);e.options.max_retry=e.options.max_retry||3,e.options.metadata_only=e.options.metadata_only!==undefined?e.options.metadata_only:!1,k.addJob(f,{docid:e.doc,options:e.options,callbacks:{success:e.success,error:e.error}})}}),Object.defineProperty(C,"remove",{configurable:!1,enumerable:!1,writable:!1,value:function(){var e=k.getParam(arguments);e.options.max_retry=e.options.max_retry||0,k.addJob(l,{doc:e.doc,options:e.options,callbacks:{success:e.success,error:e.error}})}}),Object.defineProperty(C,"allDocs",{configurable:!1,enumerable:!1,writable:!1,value:function(){var e=k.getParam(arguments,"no doc");e.options.max_retry=e.options.max_retry||3,e.options.metadata_only=e.options.metadata_only!==undefined?e.options.metadata_only:!0,k.addJob(u,{options:e.options,callbacks:{success:e.success,error:e.error}})}}),C},a={base:function(){}},f=function(e){var t={};return e=e||{},Object.defineProperty(t,"newJio",{configurable:!1,enumerable:!1,writable:!1,value:function(e){var t=e,n=null;return typeof t=="string"&&(t=JSON.parse(t)),t=t||{type:"base"},n=u(e),n.start(),n}}),Object.defineProperty(t,"addStorageType",{configurable:!1,enumerable:!1,writable:!1,value:function(e,t){t=t||function(){return null};if(a[e])throw r({type:e,message:"Already known."});a[e]=t}}),t}();return f}(); \ No newline at end of file
\ No newline at end of file
/*! JIO Storage - v0.1.0 - 2012-10-12
* Copyright (c) 2012 Nexedi; Licensed */
(function(e,t,n,r,i,s){var o=function(t,n){t=t||{};var r=n.basicStorage(t,n),i={};console.log(t),i.secureDocId=function(e){var t=e.split("/"),n;t[0]===""&&(t=t.slice(1));for(n=0;n<t.length;n+=1)if(t[n]==="")return"";return t.join("%2F")},i.convertSlashes=function(e){return e.split("/").join("%2F")},i.restoreSlashes=function(e){return e.split("%2F").join("/")},i.username=t.username||"",i.secured_username=i.convertSlashes(i.username),i.applicationname=t.applicationname||"untitled",i.secured_applicationname=i.convertSlashes(i.applicationname);var s="jio/local_user_array",o="jio/local_file_name_array/"+i.secured_username+"/"+i.secured_applicationname,u=r.serialized;return r.serialized=function(){var e=u();return e.applicationname=i.applicationname,e.username=i.username,e},r.validateState=function(){return i.secured_username?"":'Need at least one parameter: "username".'},i.getUserArray=function(){return e.getItem(s)||[]},i.addUser=function(t){var n=i.getUserArray();n.push(t),e.setItem(s,n)},i.userExists=function(e){var t=i.getUserArray(),n,r;for(n=0,r=t.length;n<r;n+=1)if(t[n]===e)return!0;return!1},i.getFileNameArray=function(){return e.getItem(o)||[]},i.addFileName=function(t){var n=i.getFileNameArray();n.push(t),e.setItem(o,n)},i.removeFileName=function(t){var n,r,s=i.getFileNameArray(),u=[];for(n=0,r=s.length;n<r;n+=1)s[n]!==t&&u.push(s[n]);e.setItem(o,u)},i.checkSecuredDocId=function(e,t,n){return e?!0:(r.error({status:403,statusText:"Method Not Allowed",error:"method_not_allowed",message:"Cannot "+n+' "'+t+'", file name is incorrect.',reason:"Cannot "+n+' "'+t+'", file name is incorrect'}),!1)},r.post=function(e){r.put(e)},r.put=function(t){setTimeout(function(){var n=i.secureDocId(t.getDocId()),s=null,o="jio/local/"+i.secured_username+"/"+i.secured_applicationname+"/"+n;if(!i.checkSecuredDocId(n,t.getDocId(),"put"))return;s=e.getItem(o),s?(s.content=t.getDocContent(),s._last_modified=Date.now()):(s={_id:t.getDocId(),content:t.getDocContent(),_creation_date:Date.now(),_last_modified:Date.now()},i.userExists(i.secured_username)||i.addUser(i.secured_username),i.addFileName(n)),e.setItem(o,s),r.success({ok:!0,id:t.getDocId()})})},r.get=function(t){setTimeout(function(){var n=i.secureDocId(t.getDocId()),s=null;if(!i.checkSecuredDocId(n,t.getDocId(),"get"))return;s=e.getItem("jio/local/"+i.secured_username+"/"+i.secured_applicationname+"/"+n),s?(t.getOption("metadata_only")&&delete s.content,r.success(s)):r.error({status:404,statusText:"Not Found.",error:"not_found",message:'Document "'+t.getDocId()+'" not found.',reason:"missing"})})},r.allDocs=function(t){setTimeout(function(){var n=[],s=[],o,u,a="key",f="jio/local/"+i.secured_username+"/"+i.secured_applicationname,l={};s=i.getFileNameArray();for(o=0,u=s.length;o<u;o+=1)l=e.getItem(f+"/"+s[o]),l&&(t.getOption("metadata_only")?n.push({id:l._id,key:l._id,value:{_creation_date:l._creation_date,_last_modified:l._last_modified}}):n.push({id:l._id,key:l._id,value:{content:l.content,_creation_date:l._creation_date,_last_modified:l._last_modified}}));r.success({total_rows:n.length,rows:n})})},r.remove=function(t){setTimeout(function(){var n=i.secureDocId(t.getDocId()),s="jio/local/"+i.secured_username+"/"+i.secured_applicationname+"/"+n;if(!i.checkSecuredDocId(n,t.getDocId(),"remove"))return;e.deleteItem(s),i.removeFileName(n),r.success({ok:!0,id:t.getDocId()})})},r};s.addStorageType("local",o);var u=function(e,r){e=e||{};var i=r.basicStorage(e,r),s={};s.secureDocId=function(e){var t=e.split("/"),n;t[0]===""&&(t=t.slice(1));for(n=0;n<t.length;n+=1)if(t[n]==="")return"";return t.join("%2F")},s.convertSlashes=function(e){return e.split("/").join("%2F")},s.restoreSlashes=function(e){return e.split("%2F").join("/")},s.username=e.username||"",s.secured_username=s.convertSlashes(s.username),s.applicationname=e.applicationname||"untitled",s.secured_applicationname=s.convertSlashes(s.applicationname),s.url=e.url||"",s.password=e.password||"";var o=i.serialized;return i.serialized=function(){var e=o();return e.username=s.username,e.applicationname=s.applicationname,e.url=s.url,e.password=s.password,e},i.validateState=function(){return s.secured_username&&s.url?"":'Need at least 2 parameters: "username" and "url".'},s.newAsyncModule=function(){var e={};return e.call=function(e,t,n){return e._wait=e._wait||{},e._wait[t]?(e._wait[t]--,function(){}):(n=n||[],e[t].apply(e[t],n))},e.neverCall=function(e,t){e._wait=e._wait||{},e._wait[t]=-1},e.wait=function(e,t,n){e._wait=e._wait||{},e._wait[t]=n},e.end=function(){e.call=function(){}},e},s.putOrPost=function(e,r){var o=s.secureDocId(e.getDocId());t.ajax({url:s.url+"/"+s.secured_username+"/"+s.secured_applicationname+"/"+o+"?_="+Date.now(),type:r,data:e.getDocContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+n.encode(s.username+":"+s.password)},success:function(){i.success({ok:!0,id:e.getDocId()})},error:function(t){t.error=t.statusText,t.reason='Cannot save "'+e.getDocId()+'"',t.message=t.reason+".",i.retry(t)}})},i.post=function(e){s.putOrPost(e,"POST")},i.put=function(e){s.putOrPost(e,"PUT")},i.get=function(e){var r=s.secureDocId(e.getDocId()),o={},u=function(){t.ajax({url:s.url+"/"+s.secured_username+"/"+s.secured_applicationname+"/"+r+"?_="+Date.now(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+n.encode(s.username+":"+s.password)},success:function(e){o.content=e,i.success(o)},error:function(t){t.error=t.statusText,t.status===404?(t.message='Document "'+e.getDocId()+'" not found.',t.reason="missing",i.error(t)):(t.reason='An error occured when trying to get "'+e.getDocId()+'"',t.message=t.reason+".",i.retry(t))}})};o._id=e.getDocId(),t.ajax({url:s.url+"/"+s.secured_username+"/"+s.secured_applicationname+"/"+r+"?_="+Date.now(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+n.encode(s.username+":"+s.password)},success:function(n){t(n).find("lp1\\:getlastmodified, getlastmodified").each(function(){o._last_modified=(new Date(t(this).text())).getTime()}),t(n).find("lp1\\:creationdate, creationdate").each(function(){o._creation_date=(new Date(t(this).text())).getTime()}),e.getOption("metadata_only")?i.success(o):u()},error:function(t){t.status===404?(t.message='Cannot find "'+e.getDocId()+'" informations.',t.reason="missing",i.error(t)):(t.reason='Cannot get "'+e.getDocId()+'" informations',t.message=t.reason+".",i.retry(t))}})},i.allDocs=function(e){var r=[],o=s.newAsyncModule(),u={};u.getContent=function(e){t.ajax({url:s.url+"/"+s.secured_username+"/"+s.secured_applicationname+"/"+s.secureDocId(e.id)+"?_="+Date.now(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+n.encode(s.username+":"+s.password)},success:function(t){e.value.content=t,r.push(e),o.call(u,"success")},error:function(e){e.error=e.statusText,e.reason="Cannot get a document content from DAVStorage",e.message=e.message+".",o.call(u,"error",[e])}})},u.getDocumentList=function(){t.ajax({url:s.url+"/"+s.secured_username+"/"+s.secured_applicationname+"/"+"?_="+Date.now(),async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+n.encode(s.username+":"+s.password),Depth:"1"},success:function(n){var i=t(n).find("D\\:response, response"),a=i.length;if(a===1)return o.call(u,"success");o.wait(u,"success",a-2),i.each(function(n,i){if(n>0){var a={value:{}};t(i).find("D\\:href, href").each(function(){var e=t(this).text().split("/");a.id=e[e.length-1],a.id=s.restoreSlashes(a.id),a.key=a.id});if(a.id===".htaccess"||a.id===".htpasswd")return;t(i).find("lp1\\:getlastmodified, getlastmodified").each(function(){a.value._last_modified=(new Date(t(this).text())).getTime()}),t(i).find("lp1\\:creationdate, creationdate").each(function(){a.value._creation_date=(new Date(t(this).text())).getTime()}),e.getOption("metadata_only")?(r.push(a),o.call(u,"success")):o.call(u,"getContent",[a])}})},error:function(e){e.status===404?(e.error="not_found",e.reason="missing",o.call(u,"error",[e])):(e.error=e.statusText,e.reason="Cannot get a document list from DAVStorage",e.message=e.reason+".",o.call(u,"retry",[e]))}})},u.retry=function(e){o.neverCall(u,"retry"),o.neverCall(u,"success"),o.neverCall(u,"error"),i.retry(e)},u.error=function(e){o.neverCall(u,"retry"),o.neverCall(u,"success"),o.neverCall(u,"error"),i.error(e)},u.success=function(){o.neverCall(u,"retry"),o.neverCall(u,"success"),o.neverCall(u,"error"),i.success({total_rows:r.length,rows:r})},o.call(u,"getDocumentList")},i.remove=function(e){var r=s.secureDocId(e.getDocId());t.ajax({url:s.url+"/"+s.secured_username+"/"+s.secured_applicationname+"/"+r+"?_="+Date.now(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+n.encode(s.username+":"+s.password)},success:function(t,n,r){i.success({ok:!0,id:e.getDocId()})},error:function(e,t,n){e.status===404?(e.error="not_found",e.reason="missing",e.message="Cannot remove missing file.",i.error(e)):(e.reason='Cannot remove "'+i.getDocId()+'"',e.message=e.reason+".",i.retry(e))}})},i};s.addStorageType("dav",u);var a=function(e,t){e=e||{};var n=t.basicStorage(e,t),r={};r.return_value_array=[],r.storagelist=e.storagelist||[],r.nb_storage=r.storagelist.length;var i=n.serialized;return n.serialized=function(){var e=i();return e.storagelist=r.storagelist,e},n.validateState=function(){return r.storagelist.length===0?'Need at least one parameter: "storagelist" containing at least one storage.':""},r.isTheLast=function(e){return e.length===r.nb_storage},r.doJob=function(e,t,i){var s=!1,o=[],u,a=function(u){s||(o.push(u),r.isTheLast(o)&&n.error({status:207,statusText:"Multi-Status",error:"multi_status",message:"All "+t+(i?" ":' "'+e.getDocId()+'"')+" requests have failed.",reason:"requests fail",array:o}))},f=function(e){s||(s=!0,n.success(e))};for(u=0;u<r.nb_storage;u+=1){var l=e.cloneOption();n.addJob(e.getLabel(),r.storagelist[u],e.cloneDoc(),l,f,a)}},n.post=function(e){r.doJob(e,"post"),n.end()},n.put=function(e){r.doJob(e,"put"),n.end()},n.get=function(e){r.doJob(e,"get"),n.end()},n.allDocs=function(e){r.doJob(e,"allDocs",!0),n.end()},n.remove=function(e){r.doJob(e,"remove"),n.end()},n};s.addStorageType("replicate",a);var f=function(t,n){t=t||{};var r=n.basicStorage(t,n),i={},s=t.storage||!1;i.secondstorage_spec=t.storage||{type:"base"},i.secondstorage_string=JSON.stringify(i.secondstorage_spec);var o="jio/indexed_storage_object",u="jio/indexed_file_object/"+i.secondstorage_string,a=r.serialized;return r.serialized=function(){var e=a();return e.storage=i.secondstorage_spec,e},r.validateState=function(){return s?"":'Need at least one parameter: "storage" containing storage specifications.'},i.secureDocId=function(e){var t=e.split("/"),n;t[0]===""&&(t=t.slice(1));for(n=0;n<t.length;n+=1)if(t[n]==="")return"";return t.join("%2F")},i.indexStorage=function(){var t=e.getItem(o)||{};t[i.secondstorage_spec]=(new Date).getTime(),e.setItem(o,t)},i.formatToFileObject=function(e){var t,n={_id:e.id};for(t in e.value)n[t]=e.value[t];return n},i.allDocs=function(e){var t,n={rows:[]},r=0;for(t in e)n.rows[r]={},n.rows[r].value=e[t],n.rows[r].id=n.rows[r].key=n.rows[r].value._id,delete n.rows[r].value._id,r++;return n.total_rows=n.rows.length,n},i.setFileArray=function(t){var n,r={};for(n=0;n<t.length;n+=1)r[t[n].id]=i.formatToFileObject(t[n]);e.setItem(u,r)},i.getFileObject=function(t){var n=e.getItem(u)||{};return n[t]},i.addFile=function(t){var n=e.getItem(u)||{};n[t._id]=t,e.setItem(u,n)},i.removeFile=function(t){var n=e.getItem(u)||{};delete n[t],e.setItem(u,n)},i.update=function(){var e=function(e){i.setFileArray(e.rows)};r.addJob("allDocs",i.secondstorage_spec,null,{max_retry:3},e,function(){})},r.post=function(e){r.put(e)},r.put=function(e){var t=e.cloneDoc(),n=e.cloneOption(),s=function(e){i.update(),r.success(e)},o=function(e){r.error(e)};i.indexStorage(),r.addJob("put",i.secondstorage_spec,t,n,s,o)},r.get=function(e){var t,n=function(e){r.success(e)},s=function(e){r.error(e)},o=function(){var t=e.cloneOption();r.addJob("get",i.secondstorage_spec,e.cloneDoc(),t,n,s),r.end()};i.indexStorage(),i.update(),e.getOption("metadata_only")?setTimeout(function(){var t=i.getFileObject(e.getDocId());t&&(t._last_modified||t._creation_date)?r.success(t):o()}):o()},r.allDocs=function(t){var n=e.getItem(u);if(n)i.update(),setTimeout(function(){r.success(i.allDocs(n))});else{var s=function(e){i.setFileArray(e.rows),r.success(e)},o=function(e){r.error(e)};r.addJob("allDocs",i.secondstorage_spec,null,t.cloneOption(),s,o)}},r.remove=function(e){var t=function(t){i.removeFile(e.getDocId()),i.update(),r.success(t)},n=function(e){r.error(e)};r.addJob("remove",i.secondstorage_spec,e.cloneDoc(),e.cloneOption(),t,n)},r};s.addStorageType("indexed",f);var l=function(e,n){e=e||{};var i=n.basicStorage(e,n),s={},o=e.storage?!0:!1;s.username=e.username||"",s.password=e.password||"",s.secondstorage_spec=e.storage||{type:"base"},s.secondstorage_string=JSON.stringify(s.secondstorage_string);var u=i.serialized;return i.serialized=function(){var e=u();return e.username=s.username,e.password=s.password,e.storage=s.secondstorage_string,e},i.validateState=function(){return s.username&&o?"":'Need at least two parameters: "username" and "storage".'},s.encrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",v:1,iter:1e3,ks:256,ts:128,mode:"ccm",adata:"",cipher:"aes",salt:"K4bmZG9d704"},s.decrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",ks:256,ts:128,salt:"K4bmZG9d704"},s.encrypt=function(e,t){var n=r.encrypt(s.username+":"+s.password,e,s.encrypt_param_object);t(JSON.parse(n).ct)},s.decrypt=function(e,n){var i,o=t.extend(!0,{},s.decrypt_param_object);o.ct=e||"",o=JSON.stringify(o);try{i=r.decrypt(s.username+":"+s.password,o)}catch(u){n({status:403,statusText:"Forbidden",error:"forbidden",message:"Unable to decrypt.",reason:"unable to decrypt"});return}n(undefined,i)},s.newAsyncModule=function(){var e={};return e.call=function(e,t,n){e._wait=e._wait||{};if(e._wait[t])return e._wait[t]--,function(){};n=n||[],setTimeout(function(){e[t].apply(e[t],n)})},e.neverCall=function(e,t){e._wait=e._wait||{},e._wait[t]=-1},e.wait=function(e,t,n){e._wait=e._wait||{},e._wait[t]=n},e.end=function(){e.call=function(){}},e},i.post=function(e){i.put(e)},i.put=function(e){var t,n,r=s.newAsyncModule(),o={};o.encryptFilePath=function(){s.encrypt(e.getDocId(),function(e){t=e,r.call(o,"save")})},o.encryptFileContent=function(){s.encrypt(e.getDocContent(),function(e){n=e,r.call(o,"save")})},o.save=function(){var r=function(t){t.id=e.getDocId(),i.success(t)},o=function(e){i.error(e)},u=e.cloneDoc();u._id=t,u.content=n,i.addJob("put",s.secondstorage_spec,u,e.cloneOption(),r,o)},r.wait(o,"save",1),r.call(o,"encryptFilePath"),r.call(o,"encryptFileContent")},i.get=function(e){var t,n,r=s.newAsyncModule(),o={};o.encryptFilePath=function(){s.encrypt(e.getDocId(),function(e){t=e,r.call(o,"get")})},o.get=function(){i.addJob("get",s.secondstorage_spec,t,e.cloneOption(),o.success,o.error)},o.success=function(t){t._id=e.getDocId(),e.getOption("metadata_only")?i.success(t):s.decrypt(t.content,function(e,n){e?i.error(e):(t.content=n,i.success(t))})},o.error=function(e){i.error(e)},r.call(o,"encryptFilePath")},i.allDocs=function(e){var t=[],n=s.newAsyncModule(),r={};r.allDocs=function(){i.addJob("allDocs",s.secondstorage_spec,null,e.cloneOption(),r.onSuccess,r.error)},r.onSuccess=function(i){if(i.total_rows===0)return n.call(r,"success");t=i.rows;var o,u=function(i){s.decrypt(t[i].id,function(e,s){e?n.call(r,"error",[e]):(t[i].id=s,t[i].key=s,n.call(r,"success"))}),e.getOption("metadata_only")||s.decrypt(t[i].value.content,function(e,s){e?n.call(r,"error",[e]):(t[i].value.content=s,n.call(r,"success"))})};e.getOption("metadata_only")?n.wait(r,"success",i.total_rows*1-1):n.wait(r,"success",i.total_rows*2-1);for(o=0;o<t.length;o+=1)u(o)},r.error=function(e){n.end(),i.error(e)},r.success=function(){n.end(),i.success({total_rows:t.length,rows:t})},n.call(r,"allDocs")},i.remove=function(e){var t,n={};n.encryptDocId=function(){s.encrypt(e.getDocId(),function(e){t=e,n.removeDocument()})},n.removeDocument=function(){var r=e.cloneDoc();r._id=t,i.addJob("remove",s.secondstorage_spec,r,e.cloneOption(),n.success,i.error)},n.success=function(t){t.id=e.getDocId(),i.success(t)},n.encryptDocId()},i};s.addStorageType("crypt",l);var c=function(e,t){e=e||{};var n=t.basicStorage(e,t),r={},s=e.storage?!0:!1;r.secondstorage_spec=e.storage||{type:"base"},r.secondstorage_string=JSON.stringify(r.secondstorage_spec);var o="jio/conflictmanager/"+r.secondstorage_string+"/",u=function(){},a=n.serialized;return n.serialized=function(){var e=a();return e.storage=r.secondstorage_spec,e},n.validateState=function(){return s?"":'Need at least one parameter: "storage".'},r.getDistantMetadata=function(e,t,i,s){var o=e.cloneOption();o.metadata_only=!1,n.addJob("get",r.secondstorage_spec,t,o,i,s)},r.saveMetadataToDistant=function(e,t,i,s,o){n.addJob("put",r.secondstorage_spec,{_id:t,content:JSON.stringify(i)},e.cloneOption(),s,o)},r.saveNewRevision=function(e,t,i,s,o){n.addJob("post",r.secondstorage_spec,{_id:t,content:i},e.cloneOption(),s,o)},r.loadRevision=function(e,t,i,s){n.addJob("get",r.secondstorage_spec,t,e.cloneOption(),i,s)},r.deleteAFile=function(e,t,i,s){var o=e.cloneOption();n.addJob("remove",r.secondstorage_spec,{_id:t},e.cloneOption(),i,s)},r.chooseARevision=function(e){var t=0,n="",r;for(r in e)t<e[r]._last_modified&&(t=e[r]._last_modified,n=r);return n},r._revs=function(e,t){return!e||!t?null:e[t]?{start:e[t]._revisions.length,ids:e[t]._revisions}:null},r._revs_info=function(e){if(!e)return null;var t,n=[];for(t in e)n.push({rev:t,status:e[t]?e[t]._deleted?"deleted":"available":"missing"});return n},r.solveConflict=function(e,t,n){var s={},o=r.newAsyncModule(),a=n.command,f=n.docid+".metadata",l="",c="",h=null,p=!1,d={total_rows:0,rows:[]},v=n._deleted,m=n.previous_revision,g=null,y=new Date,b;s.getDistantMetadata=function(){r.getDistantMetadata(a,f,function(t){var r=parseInt(m.split("-")[0],10);h=JSON.parse(t.content),l=r+1+"-"+i(""+e.content+m+JSON.stringify(h)),c=n.docid+"."+l,g=h[m]||{},v||(o.wait(s,"saveMetadataOnDistant",1),o.call(s,"saveNewRevision")),o.call(s,"previousUpdateMetadata")},function(e){o.call(s,"error",[e])})},s.saveNewRevision=function(){r.saveNewRevision(a,c,e.content,function(e){o.call(s,"saveMetadataOnDistant")},function(e){o.call(s,"error",[e])})},s.previousUpdateMetadata=function(){var e;for(e=0;e<n.key.length;e+=1)delete h[n.key[e]];o.call(s,"checkForConflicts")},s.checkForConflicts=function(){var e;for(e in h){var t;p=!0,b={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"There is one or more conflicts"};break}o.call(s,"updateMetadata")},s.updateMetadata=function(){var e,t="";t=l.split("-"),t.shift(),t=t.join("-"),e=g._revisions,e.unshift(t),h[l]={_creation_date:g._creation_date||y.getTime(),_last_modified:y.getTime(),_revisions:e,_conflict:p,_deleted:v},p&&(d=r.createConflictObject(a,h,l)),o.call(s,"saveMetadataOnDistant")},s.saveMetadataOnDistant=function(){r.saveMetadataToDistant(a,f,h,function(e){o.call(s,"deleteAllConflictingRevision"),p?o.call(s,"error"):o.call(s,"success")},function(e){o.call(s,"error",[e])})},s.deleteAllConflictingRevision=function(){var e;for(e=0;e<n.key.length;e+=1)r.deleteAFile(a,n.docid+"."+n.key[e],u,u)},s.success=function(){var e={ok:!0,id:n.docid,rev:l};o.neverCall(s,"error"),o.neverCall(s,"success"),t.revs&&(e.revisions=r._revs(h,l)),t.revs_info&&(e.revs_info=r._revs_info(h)),t.conflicts&&(e.conflicts=d),n.success(e)},s.error=function(e){var i=e||b||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};l&&(i.rev=l),t.revs&&(i.revisions=r._revs(h,l)),t.revs_info&&(i.revs_info=r._revs_info(h)),t.conflicts&&(i.conflicts=d),o.neverCall(s,"error"),o.neverCall(s,"success"),n.error(i)},o.call(s,"getDistantMetadata")},r.createConflictObject=function(e,t,n){return{total_rows:1,rows:[r.createConflictRow(e,e.getDocId(),t,n)]}},r.getParam=function(e){var t={},n=0;return typeof e[n]=="string"&&(t.content=e[n],n++),typeof e[n]=="object"?(t.options=e[n],n++):t.options={},t.callback=function(e,t){},t.success=function(e){t.callback(undefined,e)},t.error=function(e){t.callback(e,undefined)},typeof e[n]=="function"&&(typeof e[n+1]=="function"?(t.success=e[n],t.error=e[n+1]):t.callback=e[n]),t},r.createConflictRow=function(e,t,n,i){var s={id:t,key:[],value:{_solveConflict:function(){var n={},o=r.getParam(arguments);return o.content===undefined?n._deleted=!0:n._deleted=!1,n.success=o.success,n.error=o.error,n.previous_revision=i,n.docid=t,n.key=s.key,n.command=e.clone(),r.solveConflict({_id:t,content:o.content,_rev:i},o.options,n)}}},o;for(o in n)s.key.push(o);return s},r.newAsyncModule=function(){var e={};return e.call=function(e,t,n){e._wait=e._wait||{};if(e._wait[t])return e._wait[t]--,u;n=n||[],setTimeout(function(){e[t].apply(e[t],n)})},e.neverCall=function(e,t){e._wait=e._wait||{},e._wait[t]=-1},e.wait=function(e,t,n){e._wait=e._wait||{},e._wait[t]=n},e.end=function(){e.call=u},e},n.post=function(e){n.put(e)},n.put=function(e){var t={},s=r.newAsyncModule(),o=e.getDocId()+".metadata",a="",f="",l=null,c=!1,h={total_rows:0,rows:[]},p=e.getDocInfo("_rev")||"0",d=e.getDocId()+"."+p,v=new Date,m;t.getDistantMetadata=function(){r.getDistantMetadata(e,o,function(n){var r=parseInt(p.split("-")[0],10);l=JSON.parse(n.content),a=r+1+"-"+i(""+e.getDocContent()+p+JSON.stringify(l)),f=e.getDocId()+"."+a,s.wait(t,"saveMetadataOnDistant",1),s.call(t,"saveNewRevision"),s.call(t,"checkForConflicts")},function(n){n.status===404?(a="1-"+i(e.getDocContent()),f=e.getDocId()+"."+a,s.wait(t,"saveMetadataOnDistant",1),s.call(t,"saveNewRevision"),s.call(t,"createMetadata")):s.call(t,"error",[n])})},t.saveNewRevision=function(){r.saveNewRevision(e,f,e.getDocContent(),function(e){s.call(t,"saveMetadataOnDistant")},function(e){s.call(t,"error",[e])})},t.checkForConflicts=function(){var e;for(e in l)if(e!==p){c=!0,m={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"Document update conflict."};break}s.call(t,"updateMetadata")},t.createMetadata=function(){var e=a;e=e.split("-"),e.shift(),e=e.join("-"),l={},l[a]={_creation_date:v.getTime(),_last_modified:v.getTime(),_revisions:[e],_conflict:!1,_deleted:!1},s.call(t,"saveMetadataOnDistant")},t.updateMetadata=function(){var n,i=[],o="";l[p]&&(n=l[p]._creation_date,i=l[p]._revisions,delete l[p]),o=a.split("-"),o.shift(),o=o.join("-"),i.unshift(o),l[a]={_creation_date:n||v.getTime(),_last_modified:v.getTime(),_revisions:i,_conflict:c,_deleted:!1},c&&(h=r.createConflictObject(e,l,a)),s.call(t,"saveMetadataOnDistant")},t.saveMetadataOnDistant=function(){r.saveMetadataToDistant(e,o,l,function(e){s.call(t,"deletePreviousRevision"),c?s.call(t,"error"):s.call(t,"success")},function(e){s.call(t,"error",[e])})},t.deletePreviousRevision=function(){p!=="0"&&r.deleteAFile(e,d,u,u)},t.success=function(){var i={ok:!0,id:e.getDocId(),rev:a};s.neverCall(t,"error"),s.neverCall(t,"success"),e.getOption("revs")&&(i.revisions=r._revs(l,a)),e.getOption("revs_info")&&(i.revs_info=r._revs_info(l)),e.getOption("conflicts")&&(i.conflicts=h),n.success(i)},t.error=function(i){var o=i||m||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};a&&(o.rev=a),e.getOption("revs")&&(o.revisions=r._revs(l,a)),e.getOption("revs_info")&&(o.revs_info=r._revs_info(l)),e.getOption("conflicts")&&(o.conflicts=h),s.neverCall(t,"error"),s.neverCall(t,"success"),n.error(o)},s.call(t,"getDistantMetadata")},n.get=function(e){var t={},i=r.newAsyncModule(),s=e.getDocId()+".metadata",o=e.getOption("rev")||"",u=null,a=e.getOption("metadata_only"),f=!1,l={total_rows:0,rows:[]},c=new Date,h={_id:e.getDocId()},p=function(e){i.call(t,"error",[{status:404,statusText:"Not Found",error:"not_found",message:e,reason:e}])};t.getDistantMetadata=function(){r.getDistantMetadata(e,s,function(e){u=JSON.parse(e.content),a||i.wait(t,"success",1),i.call(t,"affectMetadata"),i.call(t,"checkForConflicts")},function(e){i.call(t,"error",[e])})},t.affectMetadata=function(){if(o){if(!u[o])return p("Document revision does not exists.")}else o=r.chooseARevision(u);h._last_modified=u[o]._last_modified,h._creation_date=u[o]._creation_date,h._rev=o,a?i.call(t,"success"):i.call(t,"loadRevision")},t.loadRevision=function(){if(!o||u[o]._deleted)return p("Document has been removed.");r.loadRevision(e,h._id+"."+o,function(e){h.content=e.content,i.call(t,"success")},function(e){i.call(t,"error",[e])})},t.checkForConflicts=function(){u[o]._conflict&&(f=!0,l=r.createConflictObject(e,u,o)),i.call(t,"success")},t.success=function(){i.neverCall(t,"error"),i.neverCall(t,"success"),e.getOption("revs")&&(h._revisions=r._revs(u,o)),e.getOption("revs_info")&&(h._revs_info=r._revs_info(u)),e.getOption("conflicts")&&(h._conflicts=l),n.success(h)},t.error=function(s){var a=s||{status:0,statusText:"Unknown",message:"Unknown error."};e.getOption("revs")&&(a._revisions=r._revs(u,o)),e.getOption("revs_info")&&(a._revs_info=r._revs_info(u)),e.getOption("conflicts")&&(a._conflicts=l),i.neverCall(t,"error"),i.neverCall(t,"success"),n.error(a)},i.call(t,"getDistantMetadata")},n.allDocs=function(e){var t={},i=r.newAsyncModule(),s=e.getOption("metadata_only"),o=[],u={total_rows:0,rows:[]},a=0,f=0,l=0;t.retreiveList=function(){var s=e.cloneOption(),o=function(e){i.call(t,"filterTheList",[e])},u=function(e){i.call(t,"error",[e])};s.metadata_only=!0,n.addJob("allDocs",r.secondstorage_spec,null,s,o,u)},t.filterTheList=function(e){var n;l++;for(n=0;n<e.total_rows;n+=1){var r=e.rows[n].id.split(".")||[];r.length>0&&r[r.length-1]==="metadata"&&(l++,r.length--,i.call(t,"loadMetadataFile",[r.join(".")]))}i.call(t,"success")},t.loadMetadataFile=function(n){r.getDistantMetadata(e,n+".metadata",function(e){e=JSON.parse(e.content);var s=r.chooseARevision(e);e[s]._deleted?i.call(t,"success"):i.call(t,"loadFile",[n,s,e])},function(e){i.call(t,"error",[e])})},t.loadFile=function(n,a,f){var l={id:n,key:n,value:{_last_modified:f[a]._last_modified,_creation_date:f[a]._creation_date,_rev:a}};e.getOption("revs")&&(l.value._revisions=r._revs(f,a)),e.getOption("revs_info")&&(l.value._revs_info=r._revs_info(f,a)),e.getOption("conflicts")&&f[a]._conflict&&(u.total_rows++,u.rows.push(r.createConflictRow(e,n,f,a))),s?(o.push(l),i.call(t,"success")):r.loadRevision(e,n+"."+a,function(e){l.content=e.content,o.push(l),i.call(t,"success")},function(e){i.call(t,"error",[e])})},t.success=function(){var t;f++,f>=l&&(i.end(),t={total_rows:o.length,rows:o},e.getOption("conflicts")&&(t.conflicts=u),n.success(t))},t.error=function(e){i.end(),n.error(e)},i.call(t,"retreiveList")},n.remove=function(e){var t={},s=r.newAsyncModule(),o=e.getDocId()+".metadata",a="",f="",l=null,c=!1,h={total_rows:0,rows:[]},p=e.getOption("rev")||"0",d=e.getDocId()+"."+p,v=new Date,m;t.getDistantMetadata=function(){r.getDistantMetadata(e,o,function(n){l=JSON.parse(n.content),p==="last"&&(p=r.chooseARevision(l),d=e.getDocId()+"."+p);var o=parseInt(p.split("-")[0],10)||0;a=o+1+"-"+i(""+p+JSON.stringify(l)),f=e.getDocId()+"."+a,s.call(t,"checkForConflicts")},function(e){e.status===404?s.call(t,"error",[{status:404,statusText:"Not Found",error:"not_found",reason:"missing",message:"Document not found."}]):s.call(t,"error",[e])})},t.checkForConflicts=function(){var e;for(e in l)if(e!==p){c=!0,m={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"There is one or more conflicts"};break}s.call(t,"updateMetadata")},t.updateMetadata=function(){var n,i=[],o="";l[p]&&(n=l[p]._creation_date,i=l[p]._revisions,delete l[p]),o=a,o=o.split("-"),o.shift(),o=o.join("-"),i.unshift(o),l[a]={_creation_date:n||v.getTime(),_last_modified:v.getTime(),_revisions:i,_conflict:c,_deleted:!0},c&&(h=r.createConflictObject(e,l,a)),s.call(t,"saveMetadataOnDistant")},t.saveMetadataOnDistant=function(){r.saveMetadataToDistant(e,o,l,function(e){s.call(t,"deletePreviousRevision"),c?s.call(t,"error"):s.call(t,"success")},function(e){s.call(t,"error",[e])})},t.deletePreviousRevision=function(){p!=="0"&&r.deleteAFile(e,d,u,u)},t.success=function(i){var o={ok:!0,id:e.getDocId(),rev:i||a};s.neverCall(t,"error"),s.neverCall(t,"success"),e.getOption("revs")&&(o.revisions=r._revs(l,a)),e.getOption("revs_info")&&(o.revs_info=r._revs_info(l)),e.getOption("conflicts")&&(o.conflicts=h),n.success(o)},t.error=function(i){var o=i||m||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};a&&(o.rev=a),e.getOption("revs")&&(o.revisions=r._revs(l,a)),e.getOption("revs_info")&&(o.revs_info=r._revs_info(l)),e.getOption("conflicts")&&(o.conflicts=h),s.neverCall(t,"error"),s.neverCall(t,"success"),n.error(o)},s.call(t,"getDistantMetadata")},n};s.addStorageType("conflictmanager",c)})(LocalOrCookieStorage,jQuery,Base64,sjcl,hex_sha256,jIO);
\ No newline at end of file
/*! Local Or Cookie Storage - v0.1.0 - 2012-10-12
* Copyright (c) 2012 Nexedi; Licensed */
var LocalOrCookieStorage=function(){var e=function(){var e=function(){};e.prototype={getItem:function(e){return JSON.parse(localStorage.getItem(e))},setItem:function(e,t){if(e)return localStorage.setItem(e,JSON.stringify(t))},getAll:function(){return localStorage},deleteItem:function(e){e&&delete localStorage[e]}};var t=function(){};t.prototype={getItem:function(e){var t=document.cookie.split(";"),n;for(n=0;n<t.length;n+=1){var r=t[n].substr(0,t[n].indexOf("=")),i=t[n].substr(t[n].indexOf("=")+1);r=r.replace(/^\s+|\s+$/g,"");if(r===e)return unescape(i)}return null},setItem:function(e,t){return t!==undefined?(document.cookie=e+"="+JSON.stringify(t)+";domain="+window.location.hostname+";path="+window.location.pathname,!0):!1},getAll:function(){var e={},t,n=document.cookie.split(":");for(t=0;t<n.length;t+=1){var r=n[t].substr(0,n[t].indexOf("=")),i=n[t].substr(n[t].indexOf("=")+1);r=r.replace(/^\s+|\s+$/g,""),e[r]=unescape(i)}return e},deleteItem:function(e){document.cookie=e+"=null;domain="+window.location.hostname+";path="+window.location.pathname+";expires=Thu, 01-Jan-1970 00:00:01 GMT"}};try{return localStorage.getItem?new e:new t}catch(n){return new t}};return window.requirejs?(define("LocalOrCookieStorage",[],e),undefined):e()}();
\ No newline at end of file
(function (scope) { (function (scope) {
"use strict"; "use strict";
var odf = function (obj,name,value) { var OfficeJS, secureKey, secureObject;
Object.defineProperty(obj,name,{ secureKey = function (obj, key, parameters) {
configurable:false,enumerable:false,writable:false,value:value parameters = parameters || {};
Object.defineProperty(obj, key, {
configurable: parameters.configurable || false,
enumerable: parameters.enumerable || false,
writable: parameters.writable || false,
value: obj[key]
}); });
}; };
var OfficeJS = {}; secureObject = function (obj, parameters) {
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
secureKey(obj, key, parameters);
}
}
};
OfficeJS = {};
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
odf(OfficeJS,'env',{}); OfficeJS.env = {};
odf(OfficeJS,'tmp',{}); OfficeJS.tmp = {};
odf(OfficeJS,'system',{}); OfficeJS.system = {};
odf(OfficeJS,'run',{}); OfficeJS.run = {};
odf(OfficeJS,'lib',{}); OfficeJS.lib = {};
odf(OfficeJS,'command',{}); OfficeJS.command = {};
OfficeJS.io = {};
secureObject(OfficeJS);
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
OfficeJS.system.component_folder_path = 'src/component'; OfficeJS.system.component_folder_path = 'src/component';
...@@ -146,6 +160,10 @@ ...@@ -146,6 +160,10 @@
varname: 'OfficeJS_login', varname: 'OfficeJS_login',
api: { api: {
connect: function (spec) { connect: function (spec) {
if (OfficeJS.run.jio) {
OfficeJS.run.jio.close();
delete OfficeJS.run.jio;
}
if (!OfficeJS.run.jio) { if (!OfficeJS.run.jio) {
if (typeof spec === 'string') { if (typeof spec === 'string') {
spec = JSON.parse (spec); spec = JSON.parse (spec);
...@@ -153,7 +171,7 @@ ...@@ -153,7 +171,7 @@
OfficeJS.run.jio = jIO.newJio(spec); OfficeJS.run.jio = jIO.newJio(spec);
OfficeJS.system.applications['left_nav_bar']. OfficeJS.system.applications['left_nav_bar'].
lib.showTools(); lib.showTools();
OfficeJS.lib.allDocs(); OfficeJS.lib.getDocumentList();
} }
} }
} }
...@@ -193,26 +211,23 @@ ...@@ -193,26 +211,23 @@
varname: 'OfficeJS_elrte', varname: 'OfficeJS_elrte',
exts: ['html'], exts: ['html'],
default_ext: 'html', default_ext: 'html',
mime_type: 'text/html',
document_type: "WebPage",
docid_elmnt: '#elrte_docid', docid_elmnt: '#elrte_docid',
editor_elmnt: '#elrte_editor', editor_elmnt: '#elrte_editor',
api: { api: {
save: function () { save: function () {
var id, content; var id, body;
id = OfficeJS.system.applications['elrte']. id = OfficeJS.system.applications['elrte'].
lib.getDocId(); lib.getDocId();
content = OfficeJS.system.applications['elrte']. body = OfficeJS.system.applications['elrte'].
lib.getContent(); lib.getContent();
console.log ('content ' + content);
if (id) { if (id) {
OfficeJS.lib.put({ OfficeJS.io.saveDocument(
_id:id+'.'+OfficeJS.system.applications['elrte']. OfficeJS.system.applications.elrte,
default_ext, id + "." + OfficeJS.system.applications.elrte.default_ext,
content:content||'' body || ""
},function (err,val) { );
setTimeout(function(){
OfficeJS.lib.allDocs();
});
});
} }
} }
}, },
...@@ -237,18 +252,19 @@ ...@@ -237,18 +252,19 @@
} }
}, },
onload: function (doc) { onload: function (doc) {
OfficeJS.tmp.current_file = undefined;
if (doc) { if (doc) {
OfficeJS.tmp.current_file = doc._id;
setTimeout(function(){ setTimeout(function(){
OfficeJS.system.applications['elrte']. OfficeJS.system.applications['elrte'].
lib.setDocId(OfficeJS.lib.basename(doc._id)); lib.setDocId(OfficeJS.lib.basename(doc._id));
OfficeJS.system.applications['elrte']. OfficeJS.system.applications['elrte'].
lib.setContent('loading...'); lib.setContent('loading...');
console.log ('get docid ' + doc._id); OfficeJS.io.loadDocument(doc._id, function (err, val) {
OfficeJS.lib.get(doc._id,null,function (err,val) {
if (val) { if (val) {
console.log ('receive ' + JSON.stringify (val)); OfficeJS.tmp.recent_files[doc._id] = val.metadata;
OfficeJS.system.applications['elrte']. OfficeJS.system.applications['elrte'].
lib.setContent(val.content); lib.setContent(val.body);
} else { } else {
// TODO : // TODO :
} }
...@@ -277,25 +293,23 @@ ...@@ -277,25 +293,23 @@
varname: 'OfficeJS_svgedit', varname: 'OfficeJS_svgedit',
exts: ['svg'], exts: ['svg'],
default_ext: 'svg', default_ext: 'svg',
mime_type: "image/svg+xml",
document_type: "Image",
docid_elmnt: '#svg-edit_docid', docid_elmnt: '#svg-edit_docid',
editor_elmnt: '#svg-edit_frame', editor_elmnt: '#svg-edit_frame',
api: { api: {
save: function () { save: function () {
var id, content; var id, body;
id = OfficeJS.system.applications['svg-edit']. id = OfficeJS.system.applications['svg-edit'].
lib.getDocId(); lib.getDocId();
content = OfficeJS.system.applications['svg-edit']. body = OfficeJS.system.applications['svg-edit'].
lib.getContent(); lib.getContent();
if (id) { if (id) {
OfficeJS.lib.put({ OfficeJS.io.saveDocument(
_id:id+'.'+OfficeJS.system.applications['svg-edit']. OfficeJS.system.applications['svg-edit'],
default_ext, id + '.' + OfficeJS.system.applications['svg-edit'].default_ext,
content:content||'' body || ""
},function (err,val) { );
setTimeout(function(){
OfficeJS.lib.allDocs();
});
});
} }
} }
}, },
...@@ -320,14 +334,17 @@ ...@@ -320,14 +334,17 @@
} }
}, },
onload: function (doc) { onload: function (doc) {
OfficeJS.tmp.current_file = undefined;
if (doc) { if (doc) {
OfficeJS.tmp.current_file = doc._id;
setTimeout(function(){ setTimeout(function(){
OfficeJS.system.applications['svg-edit']. OfficeJS.system.applications['svg-edit'].
lib.setDocId(OfficeJS.lib.basename(doc._id)); lib.setDocId(OfficeJS.lib.basename(doc._id));
OfficeJS.lib.get(doc._id,null,function (err,val) { OfficeJS.io.loadDocument(doc._id,function (err,val) {
if (val) { if (val) {
OfficeJS.tmp.recent_files[doc._id] = val.metadata;
OfficeJS.system.applications['svg-edit']. OfficeJS.system.applications['svg-edit'].
lib.setContent(val.content); lib.setContent(val.body);
} else { } else {
// TODO : // TODO :
} }
...@@ -353,25 +370,23 @@ ...@@ -353,25 +370,23 @@
varname: 'OfficeJS_jquerysheet', varname: 'OfficeJS_jquerysheet',
exts: ['jqs'], exts: ['jqs'],
default_ext: 'jqs', default_ext: 'jqs',
mime_type: "text/html",
document_type: "Spreadsheet",
docid_elmnt: '#jquery-sheet_docid', docid_elmnt: '#jquery-sheet_docid',
sheet_elmnt: '#jQuerySheet', sheet_elmnt: '#jQuerySheet',
api: { api: {
save: function () { save: function () {
var id, content; var id, body;
id = OfficeJS.system.applications['jquery-sheet']. id = OfficeJS.system.applications['jquery-sheet'].
lib.getDocId(); lib.getDocId();
content = OfficeJS.system.applications['jquery-sheet']. body = OfficeJS.system.applications['jquery-sheet'].
lib.getContent(); lib.getContent();
if (id) { if (id) {
OfficeJS.lib.put({ OfficeJS.io.saveDocument(
_id:id+'.'+OfficeJS.system.applications['jquery-sheet']. OfficeJS.system.applications['jquery-sheet'],
default_ext, id + '.' + OfficeJS.system.applications['jquery-sheet'].default_ext,
content:content||'' body || ''
},function (err,val) { );
setTimeout(function(){
OfficeJS.lib.allDocs();
});
});
} }
}, },
firstload: function () { firstload: function () {
...@@ -466,14 +481,17 @@ ...@@ -466,14 +481,17 @@
} }
}, },
onload: function (doc) { onload: function (doc) {
OfficeJS.tmp.current_file = undefined;
if (doc) { if (doc) {
OfficeJS.tmp.current_file = doc._id;
setTimeout(function(){ setTimeout(function(){
OfficeJS.system.applications['jquery-sheet']. OfficeJS.system.applications['jquery-sheet'].
lib.setDocId(OfficeJS.lib.basename(doc._id)); lib.setDocId(OfficeJS.lib.basename(doc._id));
OfficeJS.lib.get(doc._id,null,function (err,val) { OfficeJS.io.loadDocument(doc._id, function (err,val) {
if (val) { if (val) {
OfficeJS.tmp.recent_files[doc._id] = val.metadata;
OfficeJS.system.applications['jquery-sheet']. OfficeJS.system.applications['jquery-sheet'].
lib.setContent(val.content); lib.setContent(val.body);
} else { } else {
// TODO : // TODO :
} }
...@@ -508,7 +526,7 @@ ...@@ -508,7 +526,7 @@
}); });
}, },
refresh: function () { refresh: function () {
OfficeJS.lib.allDocs(function (err,val) { OfficeJS.lib.getDocumentList(function (err,val) {
if (val) { if (val) {
try { try {
OfficeJS.tmp.slick_reload = 0; OfficeJS.tmp.slick_reload = 0;
...@@ -529,7 +547,6 @@ ...@@ -529,7 +547,6 @@
document_list,columns,options, document_list,columns,options,
showConflict = function (arrayi,row) { showConflict = function (arrayi,row) {
return function () { return function () {
console.log ('showConflict');
OfficeJS.lib.openApplication( OfficeJS.lib.openApplication(
OfficeJS.lib.getAppFromPref( OfficeJS.lib.getAppFromPref(
'conflictsolver'), 'conflictsolver'),
...@@ -565,7 +582,7 @@ ...@@ -565,7 +582,7 @@
// make array // make array
array = []; array = [];
for (i = 0; i < document_list.total_rows; i+= 1) { for (i = 0; i < document_list.total_rows; i+= 1) {
var arrayi = {}, lm, cd, j; var arrayi = {}, cd, j;
arrayi.id = document_list.rows[i].id; arrayi.id = document_list.rows[i].id;
arrayi.basename = OfficeJS.lib.basename(arrayi.id); arrayi.basename = OfficeJS.lib.basename(arrayi.id);
arrayi.ext = OfficeJS.lib.extOf(arrayi.id); arrayi.ext = OfficeJS.lib.extOf(arrayi.id);
...@@ -594,12 +611,8 @@ ...@@ -594,12 +611,8 @@
// dates // dates
// FIXME : we can have 2012/1/1 12:5 // FIXME : we can have 2012/1/1 12:5
// we should have 2012/01/01 12:05 // we should have 2012/01/01 12:05
lm = (new Date(document_list.rows[i].value._last_modified)); cd = (new Date(document_list.rows[i].doc.last_modified));
cd = (new Date(document_list.rows[i].value._creation_date)); arrayi.last_modified = cd.getFullYear()+'/'+
arrayi.last_modified = lm.getFullYear()+'/'+
(lm.getMonth()+1)+'/'+lm.getDate()+' '+
lm.getHours()+':'+lm.getMinutes();
arrayi.creation_date = cd.getFullYear()+'/'+
(cd.getMonth()+1)+'/'+cd.getDate()+' '+ (cd.getMonth()+1)+'/'+cd.getDate()+' '+
cd.getHours()+':'+cd.getMinutes(); cd.getHours()+':'+cd.getMinutes();
array.push(arrayi); array.push(arrayi);
...@@ -614,10 +627,8 @@ ...@@ -614,10 +627,8 @@
formatter:showIconFormatter}); formatter:showIconFormatter});
columns.push({id:"file_name",name:"Document", columns.push({id:"file_name",name:"Document",
field:"basename",sortable:true}); field:"basename",sortable:true});
columns.push({id:"last_modified",name:"Modified", columns.push({id:"last_modified",name:"Modification Date",
field:"last_modified",sortable:true}); field:"last_modified",sortable:true});
columns.push({id:"creation_date",name:"Created",
field:"creation_date",sortable:true});
if (document_list.conflicts) { if (document_list.conflicts) {
columns.push({id:'on_conflict',name:'', columns.push({id:'on_conflict',name:'',
field:'conflict',sortable:true, field:'conflict',sortable:true,
...@@ -671,8 +682,8 @@ ...@@ -671,8 +682,8 @@
}; };
selected = grid.getSelectedRows(); selected = grid.getSelectedRows();
for (i = 0, l = selected.length; i < l; i+= 1) { for (i = 0, l = selected.length; i < l; i+= 1) {
OfficeJS.lib.remove( OfficeJS.lib.removeDocument(
{_id:document_list.rows[selected[i]].id},'last', document_list.rows[selected[i]].id,
removeFun); removeFun);
} }
}; };
...@@ -745,6 +756,7 @@ ...@@ -745,6 +756,7 @@
} }
}, },
onload: function () { onload: function () {
OfficeJS.tmp.current_file = undefined;
setTimeout(function(){ setTimeout(function(){
OfficeJS.system.applications['workinprogress'].lib.start(); OfficeJS.system.applications['workinprogress'].lib.start();
},50); },50);
...@@ -787,7 +799,7 @@ ...@@ -787,7 +799,7 @@
OfficeJS.lib.getAppFromPref( OfficeJS.lib.getAppFromPref(
'conflictsolver')); 'conflictsolver'));
} }
OfficeJS.lib.allDocs ( function () { OfficeJS.lib.getDocumentList(function () {
if (OfficeJS.tmp['page-content'].type === if (OfficeJS.tmp['page-content'].type ===
'documentlister') { 'documentlister') {
if (OfficeJS.tmp['page-content'].update) { if (OfficeJS.tmp['page-content'].update) {
...@@ -804,40 +816,6 @@ ...@@ -804,40 +816,6 @@
}); });
OfficeJS.system.applications['basic_conflict_solver']. OfficeJS.system.applications['basic_conflict_solver'].
api.abort(); api.abort();
},
keepRevision: function (revision) {
var content = $('#'+revision).text();
OfficeJS.system.applications['top_nav_bar'].lib.spin('save');
OfficeJS.tmp.basic_conflict_solver_current_conflict.value.
_solveConflict(
content,
{conflicts:true,revs:true,revs_info:true},
function (err,val) {
OfficeJS.system.applications['top_nav_bar'].lib.
endspin('save');
if (err && err.conflicts.total_rows > 0) {
OfficeJS.lib.openApplication(
OfficeJS.lib.getAppFromPref(
'conflictsolver'));
}
OfficeJS.lib.allDocs ( function () {
if (OfficeJS.tmp['page-content'].type ===
'documentlister') {
if (OfficeJS.tmp['page-content'].update) {
OfficeJS.tmp['page-content'].update();
}
}
});
if (OfficeJS.tmp['page-content']['class'] ===
'editor') {
if (OfficeJS.tmp['page-content'].update) {
OfficeJS.tmp['page-content'].update(
content);
}
}
});
OfficeJS.system.applications['basic_conflict_solver'].
api.abort();
} }
}, },
lib:{ lib:{
...@@ -851,21 +829,7 @@ ...@@ -851,21 +829,7 @@
'</textarea></div>'+ '</textarea></div>'+
'<div><button onclick="'+ '<div><button onclick="'+
//'console.log('+"'"+revision+"'"+');'+ //'console.log('+"'"+revision+"'"+');'+
"OfficeJS_basic_conflict_solver.keepRevision('"+doc._rev+"');"+ "OfficeJS_basic_conflict_solver.removeRevision('"+doc._rev+"');"+
'">Save this one</button></div><hr/>'+
'</div></div>';
},50);
},
addRemovedRevision: function (doc) {
setTimeout( function () {
document.querySelector (OfficeJS.system.applications[
'basic_conflict_solver'].main_elmnt+' #revisions').
innerHTML += '<div class="row-fluid"><div class="span12">'+
'<div>'+(new Date(doc._last_modified)).toString()+'</div>'+
'<div>Removed</div>'+
'<div><button onclick="'+
//'console.log('+"'"+revision+"'"+');'+
"OfficeJS_basic_conflict_solver.removeRevision();"+
'">Save this one</button></div><hr/>'+ '">Save this one</button></div><hr/>'+
'</div></div>'; '</div></div>';
},50); },50);
...@@ -880,7 +844,6 @@ ...@@ -880,7 +844,6 @@
'basic_conflict_solver'].docid_elmnt 'basic_conflict_solver'].docid_elmnt
).textContent = doc._id; ).textContent = doc._id;
},50); // FIXME : wait for init end },50); // FIXME : wait for init end
console.log (OfficeJS.tmp.basic_conflict_solver_current_conflict);
var i,getFun = function (err,val) { var i,getFun = function (err,val) {
OfficeJS.system.applications['top_nav_bar'].lib. OfficeJS.system.applications['top_nav_bar'].lib.
endspin('load'); endspin('load');
...@@ -896,7 +859,6 @@ ...@@ -896,7 +859,6 @@
}; };
for (i = 0; i < OfficeJS.tmp.basic_conflict_solver_current_conflict. for (i = 0; i < OfficeJS.tmp.basic_conflict_solver_current_conflict.
key.length; i+= 1) { key.length; i+= 1) {
console.log ('a');
OfficeJS.system.applications['top_nav_bar'].lib.spin('load'); OfficeJS.system.applications['top_nav_bar'].lib.spin('load');
OfficeJS.lib.get( OfficeJS.lib.get(
doc._id, doc._id,
...@@ -916,161 +878,42 @@ ...@@ -916,161 +878,42 @@
}; };
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
odf(OfficeJS.lib,'basename',function (docid) { OfficeJS.lib.basename = function (docid) {
var basename = docid.split('.').slice(0,-1).join('.'); var basename = docid.split('.').slice(0,-1).join('.');
if (basename === '') { if (basename === '') {
return docid; return docid;
} }
return basename; return basename;
}); };
odf(OfficeJS.lib,'extOf',function (docid) { OfficeJS.lib.extOf = function (docid) {
var ext = docid.split('.').splice(-1)[0]; var ext = docid.split('.').splice(-1)[0];
if (ext === docid) { if (ext === docid) {
return ''; return '';
} }
return ext; return ext;
}); };
odf(OfficeJS.lib,'put',function (doc,callback) { OfficeJS.lib.getAppFromPref = function (spec) {
if (OfficeJS.run.jio) {
if (OfficeJS.tmp[doc._id + ' knownrevision']) {
doc._rev = OfficeJS.tmp[doc._id + ' knownrevision'];
}
OfficeJS.system.applications['top_nav_bar'].lib.spin('save');
OfficeJS.run.jio.put(
doc,{conflicts:true,revs:true,revs_info:true},
function (err,val) {
OfficeJS.system.applications['top_nav_bar'].lib.
endspin('save');
OfficeJS.tmp[doc._id + ' knownrevision'] =
(err||val||{rev:undefined}).rev;
if (err) {
OfficeJS.tmp.lastfailure =
OfficeJS.lib.cloneObjectRoot(err);
OfficeJS.tmp.lastfailure.label = 'put';
OfficeJS.tmp.lastfailure.docid = doc._id;
}
if ((err||val).conflicts &&
(err||val).conflicts.total_rows > 0) {
OfficeJS.lib.openApplication(
OfficeJS.lib.getAppFromPref(
'conflictsolver'),
{_id:doc._id,row:(err||val).conflicts.rows[0]}
);
}
if (callback) {
callback(err,val);
}
}
);
}
});
odf(OfficeJS.lib,'get',function (docid,rev,callback) {
if (OfficeJS.run.jio) {
var opts = {conflicts:true,revs:true,revs_info:true,max_retry:3};
if (rev) {
opts.rev = rev;
}
OfficeJS.system.applications['top_nav_bar'].lib.spin('load');
OfficeJS.run.jio.get(
docid,opts,
function (err,val) {
OfficeJS.system.applications['top_nav_bar'].lib.
endspin('load');
if (!rev) {
OfficeJS.tmp[docid + ' knownrevision'] =
(err||val||{_rev:undefined})._rev;
if ((err||val)._conflicts &&
(err||val)._conflicts.total_rows > 0) {
OfficeJS.lib.openApplication(
OfficeJS.lib.getAppFromPref(
'conflictsolver'),
{_id:docid,row:(err||val)._conflicts.rows[0]}
);
}
}
if (err) {
OfficeJS.tmp.lastfailure =
OfficeJS.lib.cloneObjectRoot(err);
OfficeJS.tmp.lastfailure.label = 'get';
OfficeJS.tmp.lastfailure.docid = docid;
}
if (callback) {
callback(err,val);
}
}
);
}
});
odf(OfficeJS.lib,'allDocs',function (callback) {
if (OfficeJS.run.jio) {
OfficeJS.system.applications['top_nav_bar'].lib.spin('getlist');
OfficeJS.run.jio.allDocs(
{conflicts:true,revs:true,revs_info:true,max_retry:3},
function (err,val) {
OfficeJS.system.applications['top_nav_bar'].lib.
endspin('getlist');
if (val) {
OfficeJS.tmp.documentlist = val;
} else if (err) {
OfficeJS.tmp.lastfailure =
OfficeJS.lib.cloneObjectRoot(err);
OfficeJS.tmp.lastfailure.label = 'allDocs';
}
if (callback) {
callback(err,val);
}
}
);
}
});
odf(OfficeJS.lib,'remove',function (doc,rev,callback) {
if (OfficeJS.run.jio) {
var opts = {conflicts:true,revs:true,revs_info:true};
if (rev) {
opts.rev = rev;
} else if (OfficeJS.tmp[doc._id + ' knownrevision']) {
opts.rev = OfficeJS.tmp[doc._id + ' knownrevision'];
}
OfficeJS.system.applications['top_nav_bar'].lib.spin('remove');
OfficeJS.run.jio.remove(
doc,opts,
function (err,val) {
OfficeJS.system.applications['top_nav_bar'].lib.
endspin('remove');
if (err) {
OfficeJS.tmp.lastfailure =
OfficeJS.lib.cloneObjectRoot(err);
OfficeJS.tmp.lastfailure.label = 'remove';
OfficeJS.tmp.lastfailure.docid = doc._id;
}
if (callback) {
callback(err,val);
}
}
);
}
});
odf(OfficeJS.lib,'getAppFromPref',function (spec) {
return OfficeJS.system.preferences[spec]; return OfficeJS.system.preferences[spec];
}); };
odf(OfficeJS.lib,'getAppFromMime',function (ext) { OfficeJS.lib.getAppFromMime = function (ext) {
return OfficeJS.lib.getAppFromPref(OfficeJS.system.mime[ext]); return OfficeJS.lib.getAppFromPref(OfficeJS.system.mime[ext]);
}); };
odf(OfficeJS.lib,'cloneObjectRoot',function (obj) { OfficeJS.lib.cloneObjectRoot = function (obj) {
var cloned_obj = {}, key; var cloned_obj = {}, key;
for (key in obj) { for (key in obj) {
cloned_obj[key] = obj[key]; cloned_obj[key] = obj[key];
} }
return cloned_obj; return cloned_obj;
}); };
odf(OfficeJS.lib,'cloneAndProtectObjectRoot',function (obj) { OfficeJS.lib.cloneAndProtectObjectRoot = function (obj) {
var cloned_obj = {}, key; var cloned_obj = {}, key;
for (key in obj) { for (key in obj) {
odf(cloned_obj,key,obj[key]); cloned_obj[key] = obj[key];
} }
secureObject(cloned_obj);
return cloned_obj; return cloned_obj;
}); };
odf(OfficeJS.lib,'openApplication',function (app,obj) { OfficeJS.lib.openApplication = function (app,obj) {
// unload // unload
if (app.gadgetid && OfficeJS.tmp[app.gadgetid] && if (app.gadgetid && OfficeJS.tmp[app.gadgetid] &&
OfficeJS.tmp[app.gadgetid].onunload) { OfficeJS.tmp[app.gadgetid].onunload) {
...@@ -1090,27 +933,234 @@ ...@@ -1090,27 +933,234 @@
app.onload(obj); app.onload(obj);
} }
return true; return true;
}); };
odf(OfficeJS.lib,'hideApplication',function (app) { OfficeJS.lib.hideApplication = function (app) {
// TODO : // TODO :
};
OfficeJS.lib.setLastFailure = function (err, label, doc_id) {
OfficeJS.tmp.lastfailure = err;
OfficeJS.tmp.lastfailure.label = label;
OfficeJS.tmp.lastfailure.docid = doc_id;
};
OfficeJS.lib.getDocumentList = function (callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.io.allDocs(function (err, response) {
if (response) {
OfficeJS.tmp.documentlist = response;
}
callback(err, response);
}); });
}
};
OfficeJS.lib.removeDocument = function (doc_id, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.io.get({"_id": doc_id}, function (err, response) {
if (err) {
return;
}
OfficeJS.io.remove(response, callback);
});
}
};
secureObject(OfficeJS.lib);
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
odf(OfficeJS.command,'getEnv',function (env) { OfficeJS.command.getEnv = function (env) {
return OfficeJS.env[env]; return OfficeJS.env[env];
}); };
odf(OfficeJS.command,'setEnv',function (env,value) { OfficeJS.command.setEnv = function (env,value) {
OfficeJS.env[env] = value; OfficeJS.env[env] = value;
}); };
odf(OfficeJS.command,'setPreference',function (id,value) { OfficeJS.command.setPreference = function (id,value) {
// TODO : // TODO :
};
secureObject(OfficeJS.command);
//////////////////////////////////////////////////////////////////////
OfficeJS.io.put = function (doc, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("save");
OfficeJS.run.jio.put(doc, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("save");
if (err) {
OfficeJS.lib.setLastFailure(err, "put", "");
}
callback(err, response);
});
}
};
OfficeJS.io.putAttachment = function (attachment, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("save");
OfficeJS.run.jio.putAttachment(attachment, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("save");
if (err) {
OfficeJS.lib.setLastFailure(err, "putAttachment", "");
}
callback(err, response);
});
}
};
OfficeJS.io.get = function (doc, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("load");
OfficeJS.run.jio.get(doc, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("load");
if (err) {
OfficeJS.lib.setLastFailure(err, "get", "");
}
callback(err, response);
});
}
};
OfficeJS.io.getAttachment = function (attachment, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("load");
OfficeJS.run.jio.getAttachment(attachment, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("load");
if (err) {
OfficeJS.lib.setLastFailure(err, "getAttachment", "");
}
callback(err, response);
});
}
};
OfficeJS.io.remove = function (doc, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("remove");
OfficeJS.run.jio.remove(doc, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("remove");
if (err) {
OfficeJS.lib.setLastFailure(err, "remove", "");
}
callback(err, response);
});
}
};
OfficeJS.io.removeAttachment = function (attachment, callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("remove");
OfficeJS.run.jio.removeAttachment(attachment, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("remove");
if (err) {
OfficeJS.lib.setLastFailure(err, "removeAttachment", "");
}
callback(err, response);
});
}
};
OfficeJS.io.allDocs = function (callback) {
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("getlist");
OfficeJS.run.jio.allDocs({
"include_docs": true
}, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("getlist");
if (err) {
OfficeJS.lib.setLastFailure(err, "allDocs", "");
}
callback(err, response);
}); });
}
};
OfficeJS.io.saveDocument = function (application, doc_id, body, callback) {
var recent_metadata;
if (OfficeJS.run.jio) {
if (OfficeJS.tmp.current_file !== doc_id) {
// if the document is treated as a new document
OfficeJS.tmp.current_file = doc_id;
OfficeJS.tmp.recent_files[doc_id] = {};
}
recent_metadata = OfficeJS.tmp.recent_files[doc_id] || {};
recent_metadata._id = doc_id;
recent_metadata.last_modified = Date.now();
recent_metadata.posted_date = recent_metadata.posted_date || Date.now();
// | TODO check if it is the first time or not
// `TODO it is not a W3C date!
recent_metadata.format = [application.mime_type];
recent_metadata.type = application.document_type;
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("save");
OfficeJS.run.jio.put(recent_metadata, function (err, response) {
if (err) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("save");
OfficeJS.lib.setLastFailure(err, "put", doc_id);
return callback(err, response);
}
OfficeJS.tmp.recent_files[doc_id] =
OfficeJS.tmp.recent_files[doc_id] || {};
OfficeJS.tmp.recent_files[doc_id]._id = response.id;
OfficeJS.tmp.recent_files[doc_id]._rev = response.rev;
OfficeJS.run.jio.putAttachment({
"_id": doc_id,
"_attachment": "body",
"_rev": response.rev,
"_data": body,
"_mimetype": application.mime_type
}, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("save");
if (response) {
OfficeJS.tmp.recent_files[doc_id] =
OfficeJS.tmp.recent_files[doc_id] || {};
OfficeJS.tmp.recent_files[doc_id]._id = response.id;
OfficeJS.tmp.recent_files[doc_id]._rev = response.rev;
OfficeJS.lib.getDocumentList();
}
if (err) {
OfficeJS.lib.setLastFailure(err, "putAttachment", doc_id);
}
callback(err, response);
});
});
}
};
OfficeJS.io.loadDocument = function (doc_id, callback) {
var metadata, body;
if (OfficeJS.run.jio) {
callback = callback || function () {};
OfficeJS.system.applications.top_nav_bar.lib.spin("load");
OfficeJS.run.jio.get({"_id": doc_id}, {
"conflicts": true
}, function (err, response) {
if (err) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("load");
OfficeJS.lib.setLastFailure(err, "get", doc_id);
return callback(err, response);
}
if (response._conflicts) {
console.log("There's conflicts! Launch conflict solver for " +
doc_id + "!");
}
metadata = response;
OfficeJS.run.jio.getAttachment({
"_id": doc_id,
"_attachment": "body"
}, function (err, response) {
OfficeJS.system.applications.top_nav_bar.lib.endspin("load");
if (err) {
OfficeJS.lib.setLastFailure(err, "getAttachment", doc_id);
}
callback(err, {"metadata": metadata, "body": response});
});
});
}
};
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
odf(scope,'OfficeJS',OfficeJS.command); scope.OfficeJS = OfficeJS.command;
secureKey(scope,'OfficeJS');
OfficeJS.tmp.recent_files = {};
OfficeJS.lib.openApplication(OfficeJS.system.applications['top_nav_bar']); OfficeJS.lib.openApplication(OfficeJS.system.applications['top_nav_bar']);
OfficeJS.lib.openApplication(OfficeJS.system.applications['left_nav_bar']); OfficeJS.lib.openApplication(OfficeJS.system.applications['left_nav_bar']);
OfficeJS.lib.openApplication(OfficeJS.system.applications['login']); OfficeJS.lib.openApplication(OfficeJS.system.applications['login']);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment