[Checkins] SVN: z3c.widget/sandbox/src/z3c/widget/flashupload/ added flashupload project

Oliver Petznick oliver at mopa.at
Wed Sep 27 09:48:48 EDT 2006


Log message for revision 70398:
  added  flashupload project

Changed:
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/SETUP.cfg
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/__init__.py
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/configure.zcml
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/interfaces.py
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/Upload.as
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/swfobject.js
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.fla
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.html
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.js
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.swf
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/tests.py
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/ticket.py
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/upload.py
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/uploadform.pt
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/vars.pt
  A   z3c.widget/sandbox/src/z3c/widget/flashupload/z3c.widget.flashupload-configure.zcml

-=-
Added: z3c.widget/sandbox/src/z3c/widget/flashupload/SETUP.cfg
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/SETUP.cfg	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/SETUP.cfg	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,3 @@
+<data-files zopeskel/etc/package-includes>
+  z3c.widget.flashupload-*.zcml
+</data-files>


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/SETUP.cfg
___________________________________________________________________
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/__init__.py
===================================================================


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/__init__.py
___________________________________________________________________
Name: svn:keywords
   + Id
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/configure.zcml
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/configure.zcml	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/configure.zcml	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,59 @@
+<configure
+    xmlns="http://namespaces.zope.org/zope"
+    xmlns:browser="http://namespaces.zope.org/browser"
+    xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc"
+    xmlns:zcml="http://namespaces.zope.org/zcml"
+    i18n_domain="zope">
+
+    <!-- target for flash upload client -->
+    <browser:page
+        for="zope.app.container.interfaces.IContainer"
+        name="uploadfile"
+        class=".upload.UploadFile"
+        permission="zope.Public"
+    />
+
+    <configure zcml:condition="have zc.resourcelibrary">
+     <resourceLibrary name="z3c.widget.flashupload"
+                    require="z3c.javascript.prototype">
+      <directory source="resources" include="upload.js swfobject.js"/>
+     </resourceLibrary>
+    </configure>
+
+    <!-- todo not have in zcml
+    <configure zcml:condition="not have zc.resourcelibrary">
+     <browser:resourceDirectory name="z3c.widget.flashupload"
+      directory="resources"/>
+    </configure>
+    -->
+
+    <!-- view for swf upload file -->
+    <!-- example registration of an upload form -->
+    <!--
+    <browser:page
+        for="zope.app.container.interfaces.IContainer"
+        name="uploadform.html"
+        class="z3c.widget.flashupload.upload.UploadForm"
+        permission="zope.ManageContent"
+        menu="zmi_views"
+        title="upload Images"
+        />
+    -->
+
+    <!-- ticket view -->
+
+    <browser:page
+     for=".interfaces.IUploadFileView"
+     name="ticket"
+     class=".ticket.TicketView"
+     permission="zope.ManageContent"
+    />
+
+    <browser:page
+     for=".interfaces.IFlashUploadForm"
+     name="vars.xml"
+     template="vars.pt"
+     permission="zope.Public"
+     />
+    
+</configure>


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/configure.zcml
___________________________________________________________________
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/interfaces.py
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/interfaces.py	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/interfaces.py	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,10 @@
+from zope import interface
+
+class IUploadFileView(interface.Interface):
+
+    """a file upload view"""
+
+class IFlashUploadForm(interface.Interface):
+
+    """Form containing the swf for upload movie"""
+    


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/interfaces.py
___________________________________________________________________
Name: svn:keywords
   + Id
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/Upload.as
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/resources/Upload.as	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/resources/Upload.as	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1 @@
+/**
    Widget for uploading one or more Files to a Zope3 Server. 

    for autentication we need to get a ticket id befor sending the post request.
    
    step1: get the ticket:
    
    ./ticket.html/filename=myfile.jpg
    this returns us a target path:
    targeturl=http://...... 
    this is the target where we post the file
    
    step2: send file to the given url
    
    configuration:
    on _level0 we receive the information about where to get the ticket - inside
    the ticket we receive the url where to upload. 
    
    _level0.target_path -> where to get the ticket
    _level0.allowed_types -> space seperated files of allowed types. 
    
    _level0.allowed_types = "Images (all jpgs and pngs); jpg jpeg png gif|

*/


import flash.net.FileReferenceList;
import flash.net.FileReference;

class Upload extends MovieClip{
   
    
    private var info_mc:MovieClip;
        
    private var file_array:Array;
    private var fileref:FileReferenceList;
    private var file:FileReference; // currently active file for upload
    
    private var allowed_types:Array;
    private var debug_txt:TextField;
    
    private var load_vars:LoadVars;
    
    private var overall_total:Number;
    private var overall_loaded:Number;
    
    private var file_counter:Number;
    private var file_amount:Number;
	
	private var data_xml:XML;
    
	private var error_msg:String;
	
	private var js_command_queue:Array; // only one getURL can be called inside one frame. so lets make a queue to avoid troubles. 
	
    public function Upload(){
        
        Stage.scaleMode = "noScale";
        Stage.align = "LT";
        
		js_command_queue = new Array();
        overall_total = 0;
        overall_loaded = 0;
        file_counter = 0;
        log("initialize. target: "+_level0.target_path);
    
        // allow upload from the local host
        System.security.allowDomain("http://localhost/");
        
        fileref = new FileReferenceList();
        fileref.addListener(this);
                
        info_mc.progress_file_mc.bar_mc.gotoAndStop(1);
        info_mc.progress_overall_mc.bar_mc.gotoAndStop(1);
        // get allowed file types
        
        info_mc._visible = false;

        var margin:Number = 5;
        var width:Number = Stage.width - 2*margin;
        
        info_mc.progress_file_mc._width = width;
        info_mc.progress_overall_mc._width = width;
        
		info_mc.filenum_txt._x = width - info_mc.filenum_txt._width;
		info_mc.filename_txt._width = info_mc.filenum_txt._x - info_mc.filename_txt._x 
        info_mc.progress_file_txt._x = width - info_mc.progress_file_txt._width;
		info_mc.label_file_progress_txt._width = info_mc.progress_file_txt._x - info_mc.label_file_progress_txt._x;
        info_mc.progress_overall_txt._x = width - info_mc.progress_overall_txt._width;
		info_mc.label_total_progress_txt._width = info_mc.progress_overall_txt._x - info_mc.label_total_progress_txt._x
		
		var xml_url:String = _level0.base_path+"/@@vars.xml";
		
		data_xml = new XML();
		data_xml["ptr"] = this;
		data_xml.ignoreWhite = true;
		data_xml.onLoad = function(){ this.ptr.parseDataXML(this); }
		data_xml.load(xml_url);
		log("vars url: "+xml_url);
    }
	
	/**
		parses the language dependend strings. 
	*/
	private function parseDataXML(obj_xml:XML):Void{
		log("xml loaded: "+obj_xml.firstChild);
		var nodes = obj_xml.firstChild.childNodes;
		for (var i=0; i<nodes.length; i++){
			var nodeval:String = nodes[i].firstChild.nodeValue; 
			switch(nodes[i].attributes.name){
				case "file_progress" :
					info_mc.label_file_progress_txt.text = nodeval;
					break;
				case "overall_progress" :
					info_mc.label_total_progress_txt.text = nodeval;
					break;
				case "error" :
					error_msg = nodeval;
					break;
				default:
					log("error: unexpected attribute: "+nodes[i].attributes.name);
					break;
			}
		}
	}
	
	
    /**
        creates an array with all allowed types
        the data gets parsed from the variable of _level0.allowed_types
        
        var file:FileReference;

        var allTypes:Array = new Array();
        var imageTypes:Object = new Object();
        imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
        imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
        allTypes.push(imageTypes);

        var textTypes:Object = new Object();
        textTypes.description = "Text Files (*.txt, *.rtf)";
        textTypes.extension = "*.txt;*.rtf";
        allTypes.push(textTypes);
        
        arr = [{description:'a description', extension:'*.jpg'}, .....]
    */
    public function saveAllowedTypes(arr:Array):Void{
        allowed_types = arr;
    }
    
    /**
        starts the browsing process for uploading files
    */
    public function browse():Void{
		js_command_queue.push("javascript:z3cFlashUploadDisableBrowseButton()");
		//getURL("javascript:z3cFlashUploadDisableBrowseButton()");		
        if (allowed_types.length>0){
            fileref.browse(allowed_types);
        }
        else{
            fileref.browse();
        }
    }

    /**
        starts the upload queue
    */
    public function onSelect(fileRefList:FileReferenceList):Void{
        file_array = fileRefList.fileList;
        log("uploadFiles: "+file_array.length);        
        
        for (var i=0; i<file_array.length; i++){
            overall_total+=file_array[i].size;
        }
        
        if (file_array.length>0){
            info_mc._visible = true;
            file_counter = 0;
            file_amount = file_array.length;
            loadNextTicket();
        }
    }
    
    /**
        loads the next upload ticket via loadvars
        the ticket holds some security information which 
        are required for the upload
    */
    public function loadNextTicket():Void{
        if (file_array.length == 0){
            log("all files uploaded.");
			// all files uploaded. Fire JavaScript Event
			js_command_queue.push("javascript:z3cFlashUploadOnUploadCompleteFEvent()");
			//getURL("javascript:z3cFlashUploadOnUploadCompleteFEvent()");
			
            return;
        }
        
        load_vars = new LoadVars();
        load_vars["ptr"] = this;
        load_vars.onData = function(d:String){
            this["ptr"].log("load data: "+d);
            this["ptr"].loadNextFile(d);
        }
        load_vars.load(_level0.target_path+"/@@ticket");
    
    }
    
    /**
        loads the next file inside the file_array
    */
    public function loadNextFile(ticket:String):Void{        
        file = FileReference(file_array.pop());
        
        var url:String = _level0.target_path+"?ticket="+ticket;
        
        log("uploadNextFile: "+url);
        
        file.addListener(this);
        file.upload(url);
    }
    
    public function log(msg:String):Void{
        trace(msg);
        _level0.debug_mc.debug_txt.text+=msg+"\n";
		_level0.debug_mc.debug_txt.scroll = _level0.debug_mc.debug_txt.maxscroll;
    }
    
    /**
        FileReference Listeners....
    */
    
    public function onProgress(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void{
        log("###############################");
        var percent:Number = Math.round(bytesLoaded/bytesTotal * 100);
		if (percent>100) percent=100; // for any strange reason, the totalbytes can be smaller then the loade bytes :)
        log("onProgress with bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal+" = "+percent+"%");
        
        info_mc.progress_file_mc.bar_mc.gotoAndStop(percent);
        info_mc.progress_file_txt.text = percent+"%";
        
        var percent_complete:Number = Math.round((overall_loaded+bytesLoaded) / overall_total * 100);
        info_mc.progress_overall_mc.bar_mc.gotoAndStop(percent_complete);
        info_mc.progress_overall_txt.text = percent_complete+"%";
    }
    
    public function onComplete(file:FileReference):Void{
        log("file upload complete");
        
        overall_loaded+=file.size;
        this.loadNextTicket();
		
		// tell javascript that the file is uploaded. 
		//getURL("javascript:z3cFlashUploadOnFileCompleteFEvent('"+file.name+"')");
		js_command_queue.push("javascript:z3cFlashUploadOnFileCompleteFEvent('"+file.name+"')");
    }

    public function onCancel(file:FileReference):Void{
        log("onCancel");
		js_command_queue.push("javascript:z3cFlashUploadOnCancelFEvent()");
    }
    
    public function onOpen(file:FileReference):Void{
        log("onOpen: "+file.name+" : "+file.size);
        file_counter++;
        
        info_mc.filename_txt.text = file.name +" ("+Math.round(file.size/1024)+"kb)";
        info_mc.filenum_txt.text = file_counter+"/"+file_amount;
    }

    public function onHTTPError(file:FileReference):Void {
        log("onHTTPError: " + file.name);
		js_command_queue.push("javascript:z3cFlashUploadOnErrorFEvent('"+this.error_msg+"')");
    }

    public function onIOError(file:FileReference):Void {
        log("onIOError: " + file.name);
		js_command_queue.push("javascript:z3cFlashUploadOnErrorFEvent('"+this.error_msg+"')");		
    }
    
    public function onSecurityError(file:FileReference, errorString:String):Void {
        log("onSecurityError: " + file.name + " errorString: " + errorString);
		js_command_queue.push("javascript:z3cFlashUploadOnErrorFEvent('"+this.error_msg+"')");		
    }

    public function onEnterFrame():Void{
        if (_level0.startBrowse=="go"){
			log("go event was fired");
            _level0.startBrowse = "";
            this.browse();
        }
		
		if (js_command_queue.length>0){
			var command = js_command_queue.shift();
			getURL(command);
		}
		
    }
	
}
\ No newline at end of file

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/swfobject.js
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/resources/swfobject.js	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/resources/swfobject.js	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,135 @@
+/**
+ * SWFObject v1.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
+ *
+ * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
+ * http://www.opensource.org/licenses/mit-license.php
+ *
+ * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
+ *   legal reasons.
+ */
+if(typeof deconcept=="undefined"){var deconcept=new Object();}
+if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
+if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
+deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
+if(!document.createElement||!document.getElementById){return;}
+this.DETECT_KEY=_b?_b:"detectflash";
+this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
+this.params=new Object();
+this.variables=new Object();
+this.attributes=new Array();
+if(_1){this.setAttribute("swf",_1);}
+if(id){this.setAttribute("id",id);}
+if(w){this.setAttribute("width",w);}
+if(h){this.setAttribute("height",h);}
+if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
+this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
+if(c){this.addParam("bgcolor",c);}
+var q=_8?_8:"high";
+this.addParam("quality",q);
+this.setAttribute("useExpressInstall",_7);
+this.setAttribute("doExpressInstall",false);
+var _d=(_9)?_9:window.location;
+this.setAttribute("xiRedirectUrl",_d);
+this.setAttribute("redirectUrl","");
+if(_a){this.setAttribute("redirectUrl",_a);}};
+deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
+this.attributes[_e]=_f;
+},getAttribute:function(_10){
+return this.attributes[_10];
+},addParam:function(_11,_12){
+this.params[_11]=_12;
+},getParams:function(){
+return this.params;
+},addVariable:function(_13,_14){
+this.variables[_13]=_14;
+},getVariable:function(_15){
+return this.variables[_15];
+},getVariables:function(){
+return this.variables;
+},getVariablePairs:function(){
+var _16=new Array();
+var key;
+var _18=this.getVariables();
+for(key in _18){
+_16.push(key+"="+_18[key]);}
+return _16;
+},getSWFHTML:function(){
+var _19="";
+if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
+if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
+_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
+_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
+var _1a=this.getParams();
+for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
+var _1c=this.getVariablePairs().join("&");
+if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
+_19+="/>";
+}else{
+if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
+_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
+_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
+var _1d=this.getParams();
+for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
+var _1f=this.getVariablePairs().join("&");
+if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}
+_19+="</object>";}
+return _19;
+},write:function(_20){
+if(this.getAttribute("useExpressInstall")){
+var _21=new deconcept.PlayerVersion([6,0,65]);
+if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
+this.setAttribute("doExpressInstall",true);
+this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
+document.title=document.title.slice(0,47)+" - Flash Player Installation";
+this.addVariable("MMdoctitle",document.title);}}
+if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
+var n=(typeof _20=="string")?document.getElementById(_20):_20;
+n.innerHTML=this.getSWFHTML();
+return true;
+}else{
+if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
+return false;}};
+deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){
+var _25=new deconcept.PlayerVersion([0,0,0]);
+if(navigator.plugins&&navigator.mimeTypes.length){
+var x=navigator.plugins["Shockwave Flash"];
+if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
+}else{try{
+var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
+for(var i=15;i>6;i--){
+try{
+axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
+_25=new deconcept.PlayerVersion([i,0,0]);
+break;}
+catch(e){}}}
+catch(e){}
+if(_23&&_25.major>_23.major){return _25;}
+if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){
+try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}
+catch(e){}}}
+return _25;};
+deconcept.PlayerVersion=function(_29){
+this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0;
+this.minor=parseInt(_29[1])||0;
+this.rev=parseInt(_29[2])||0;};
+deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
+if(this.major<fv.major){return false;}
+if(this.major>fv.major){return true;}
+if(this.minor<fv.minor){return false;}
+if(this.minor>fv.minor){return true;}
+if(this.rev<fv.rev){return false;}return true;};
+deconcept.util={getRequestParameter:function(_2b){
+var q=document.location.search||document.location.hash;
+if(q){
+var _2d=q.indexOf(_2b+"=");
+var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length;
+if(q.length>1&&_2d>-1){
+return q.substring(q.indexOf("=",_2d)+1,_2e);
+}}return "";}};
+if(Array.prototype.push==null){
+Array.prototype.push=function(_2f){
+this[this.length]=_2f;
+return this.length;};}
+var getQueryParamValue=deconcept.util.getRequestParameter;
+var FlashObject=deconcept.SWFObject; // for backwards compatibility
+var SWFObject=deconcept.SWFObject;

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.fla
===================================================================
(Binary files differ)


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.fla
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.html
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.html	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.html	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,15 @@
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
+<title>upload</title>
+</head>
+<body bgcolor="#f8f8f8">
+<!--url's used in the movie-->
+<!--text used in the movie-->
+<!-- saved from url=(0013)about:internet -->
+<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="220" height="300" id="upload" align="middle">
+<param name="allowScriptAccess" value="sameDomain" />
+<param name="movie" value="upload.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#f8f8f8" /><embed src="upload.swf" quality="high" wmode="transparent" bgcolor="#f8f8f8" width="220" height="300" name="upload" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
+</object>
+</body>
+</html>


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.html
___________________________________________________________________
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.js
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.js	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.js	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,65 @@
+function z3cFlashUploadStartBrowsing(){
+    // tells flash to start with browsing
+    if(window.fuploader){
+        window.document["fuploader"].SetVariable("startBrowse", "go");
+    }else if(document.fuploader){
+        document.fuploader.SetVariable("startBrowse", "go");
+    }         
+}
+
+function z3cFlashUploadDisableBrowseButton(){
+    $("flash.start.browsing").style.visibility = "hidden";
+    $("flash.start.browsing").disabled = "disabled";
+}
+
+function z3cFlashUploadOnUploadCompleteFEvent(status){
+    // always fired from flash
+    if (typeof(z3cFlashUploadOnUploadComplete) == "function"){
+        z3cFlashUploadOnUploadComplete(status);
+    }
+}
+
+function z3cFlashUploadOnFileCompleteFEvent(filename){
+    // always fired from flash
+    if (typeof(z3cFlashUploadOnFileComplete) =="function"){
+        z3cFlashUploadOnFileComplete(filename);
+    }
+}
+
+/**
+    called when the user presses the cancel button while browsing
+*/  
+function z3cFlashUploadOnCancelFEvent(){
+    if (typeof(z3cFlashUploadOnCancelEvent) =="function"){
+        z3cFlashUploadOnCancelEvent(filename);
+    }    
+}
+
+/**
+    called if an error occured during the upload progress 
+*/
+function z3cFlashUploadOnErrorFEvent(error_str){
+    if (typeof(z3cFlashUploadOnErrorEvent) =="function"){
+        z3cFlashUploadOnErrorEvent(error_str);
+    }    
+}
+/**
+    creates a instance of the multifile upload widget
+    insidde the target div. 
+    Required global variable: swf_upload_target_path
+*/
+function createFlashUpload(){
+    var so = new SWFObject(swf_upload_url, "fuploader", "300", "100", "#f8f8f8");
+    so.addParam("allowScriptAccess", "sameDomain");
+    so.addParam("wmode", "transparent");
+    
+    // we need to manually quote the "+" signs to make shure they do not
+    // result in a " " sign inside flash    
+    var quoted_location_url =   escape(window.location.href).split("+").join("%2B");
+    so.addVariable("target_path", swf_upload_target_path);
+    so.addVariable("base_path", quoted_location_url);
+    
+    so.write("flashuploadtarget");
+}
+
+Event.observe(window, "load", createFlashUpload, false);     

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.swf
===================================================================
(Binary files differ)


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/resources/upload.swf
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/tests.py
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/tests.py	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/tests.py	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,24 @@
+import doctest
+import unittest
+from zope.testing.doctestunit import DocTestSuite
+from zope.app.testing import setup
+
+def setUp(test):
+    setup.placefulSetUp()
+
+def tearDown(test):
+    setup.placefulTearDown()
+
+def test_suite():
+
+    return unittest.TestSuite(
+        (
+        DocTestSuite('z3c.widget.flashupload.ticket',
+                     setUp=setUp,tearDown=tearDown,
+                     optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
+                     ),
+        ))
+
+if __name__ == '__main__':
+    unittest.main(defaultTest='test_suite')
+


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/tests.py
___________________________________________________________________
Name: svn:keywords
   + Id
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/ticket.py
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/ticket.py	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/ticket.py	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,55 @@
+from zope.traversing.browser.absoluteurl import absoluteURL
+import md5
+import base64
+import random
+from zope.app.cache.ram import RAMCache
+
+ticketCache = RAMCache()
+
+def issueTicket(ident):
+    """ issues a timelimit ticket 
+    >>> type(issueTicket(object()))== type('')
+    True
+    """
+    ticket = str(random.random())
+    ticketCache.set(True, ident, key=dict(ticket=ticket))
+    return ticket
+
+def validateTicket(ident,ticket):
+    """validates a ticket
+
+    >>> validateTicket(object(),'abc')
+    False
+    >>> obj = object()
+    >>> ticket = issueTicket(obj)
+    >>> validateTicket(obj,ticket)
+    True
+    >>> validateTicket(object(),ticket)
+    False
+    >>> validateTicket(obj,'another')
+    False
+    """
+    ticket =  ticketCache.query(ident,dict(ticket=ticket))
+    return ticket is not None
+
+def invalidateTicket(ident,ticket):
+
+    """invalidates a ticket
+    >>> ticket = issueTicket(1)
+    >>> validateTicket(1,ticket)
+    True
+    >>> invalidateTicket(1,ticket)
+    >>> validateTicket(1,ticket)
+    False
+    """
+    ticketCache.invalidate(ident,dict(ticket=ticket))
+
+
+class TicketView(object):
+
+    """A view which returns a ticket for its context"""
+    def __call__(self):
+        return issueTicket(absoluteURL(self.context,self.request))
+    
+        
+        


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/ticket.py
___________________________________________________________________
Name: svn:keywords
   + Id
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/upload.py
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/upload.py	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/upload.py	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,82 @@
+from zope.app.container.interfaces import INameChooser
+from zope.app.container.contained import setitem
+from ticket import validateTicket, invalidateTicket
+from zope.security.interfaces import Unauthorized
+from zope.publisher.browser import BrowserView
+from interfaces import IFlashUploadForm, IUploadFileView
+from zope import interface
+from zope.traversing.browser.absoluteurl import absoluteURL
+from zope.security.proxy import removeSecurityProxy
+from zope.filerepresentation.interfaces import IFileFactory
+from zope.app.pagetemplate import ViewPageTemplateFile
+from zope.app.container.constraints import checkObject
+
+try:
+    from zc import resourcelibrary
+    haveResourceLibrary = True
+except ImportError:
+    haveResourceLibrary = False
+
+
+class UploadFile(object):
+    """handles file upload for the flash client.
+    flash client sends the data via post as u'Filedata'
+    the filename gets sent as: u'Filename'
+    """
+    interface.implements(IUploadFileView)
+    
+    def __call__(self):
+        ticket = self.request.form.get('ticket',None)
+       
+        url = None
+        if ticket is None:
+            # we cannot set post headers in flash, so get the
+            # querystring manually
+            qs = self.request.get('QUERY_STRING','ticket=')
+            ticket = qs.split('=')[-1] or None
+            if ticket is None:
+                raise Unauthorized
+        else:
+            url = absoluteURL(self,self.request)
+            if not validateTicket(url,ticket):
+                raise Unauthorized
+        invalidateTicket(url,ticket)
+        if self.request.form.get('Filedata', None) is None:
+            # flash sends a emtpy form in a pre request in flash version 8.0
+            return ""
+        fileUpload = self.request.form['Filedata']
+        fileName = self.request.form['Filename']
+        contentType = self.request.form.get('Content-Type',None)
+        factory = IFileFactory(self.context)
+        f = factory(fileName, contentType, fileUpload)
+
+        # get the namechooser for the container by adapting the
+        # container to INameChooser
+        nameChooser = INameChooser(self.context)
+        
+        # namechooser selects a name for us
+        name = nameChooser.chooseName(fileName, f)
+
+        # check precondition
+        checkObject(self.context, name, f)
+        
+        # store the file inside the container
+        removeSecurityProxy(self.context)[name]=f
+
+        return "filename=%s" %name
+        
+        
+class UploadForm(BrowserView):
+    """displays the swf for uploading files
+    """
+    
+    template = ViewPageTemplateFile('uploadform.pt')
+    interface.implements(IFlashUploadForm)
+    
+    def __call__(self, *args, **kw):
+        if haveResourceLibrary:
+            resourcelibrary.need('z3c.widget.flashupload')
+        return self.template(*args, **kw)
+
+
+


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/upload.py
___________________________________________________________________
Name: svn:keywords
   + Id
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/uploadform.pt
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/uploadform.pt	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/uploadform.pt	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,20 @@
+<html metal:use-macro="context/@@standard_macros/page">    
+
+ <metal:block fill-slot="body">
+  <metal:block define-macro="swf">
+   <input type="button" id="flash.start.browsing" value="Browse"
+          onClick="JavaScript:z3cFlashUploadStartBrowsing()" />
+
+   <script type="text/javascript" tal:content="string:
+        var swf_upload_url='${context/++resource++z3c.widget.flashupload/upload.swf}';
+        var swf_upload_target_path='${context/@@absolute_url/url:quote}/uploadfile';
+        ">   
+   </script>
+   
+   <div id="flashuploadtarget">
+        <!-- inside this div, the flash upload swf will be injected -->
+   </div>
+   
+  </metal:block>
+ </metal:block>
+</html>
\ No newline at end of file


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/uploadform.pt
___________________________________________________________________
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/vars.pt
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/vars.pt	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/vars.pt	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1,6 @@
+<?xml version="1.0" ?>
+<vars>
+    <var name="file_progress">File Progress</var>
+    <var name="overall_progress">Overall Progress</var>
+    <var name="error">Es ist ein Fehler Aufgetreten</var>
+</vars>
\ No newline at end of file


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/vars.pt
___________________________________________________________________
Name: svn:eol-style
   + native

Added: z3c.widget/sandbox/src/z3c/widget/flashupload/z3c.widget.flashupload-configure.zcml
===================================================================
--- z3c.widget/sandbox/src/z3c/widget/flashupload/z3c.widget.flashupload-configure.zcml	2006-09-27 13:32:51 UTC (rev 70397)
+++ z3c.widget/sandbox/src/z3c/widget/flashupload/z3c.widget.flashupload-configure.zcml	2006-09-27 13:48:47 UTC (rev 70398)
@@ -0,0 +1 @@
+<include package="z3c.widget.flashupload" />
\ No newline at end of file


Property changes on: z3c.widget/sandbox/src/z3c/widget/flashupload/z3c.widget.flashupload-configure.zcml
___________________________________________________________________
Name: svn:eol-style
   + native



More information about the Checkins mailing list