diff browser_side/tools.py @ 283:0eba1c4f9c6f

browser_side (plugins radiocol, xep-0054): check for file size or type before uploading
author souliane <souliane@mailoo.org>
date Mon, 25 Nov 2013 20:39:28 +0100
parents 2d6bd975a72d
children 52b1afd7ac3f
line wrap: on
line diff
--- a/browser_side/tools.py	Tue Dec 10 09:07:03 2013 +0100
+++ b/browser_side/tools.py	Mon Nov 25 20:39:28 2013 +0100
@@ -20,6 +20,8 @@
 """
 
 from pyjamas.ui.DragWidget import DragWidget
+from pyjamas.ui.FileUpload import FileUpload
+from pyjamas import Window
 import re
 from nativedom import NativeDOM
 from sat_frontends.tools import xml
@@ -94,3 +96,43 @@
 
     def onDragEnd(self, event):
         LiberviaDragWidget.current = None
+
+
+class FilterFileUpload(FileUpload):
+
+    def __init__(self, name, max_size, types=None):
+        """
+        @param name: the input element name
+        @param max_size: maximum file size in MB
+        @param types: allowed types as a list of couples (x, y, z):
+        - x: MIME content type e.g. "audio/ogg"
+        - y: file extension e.g. "*.ogg"
+        - z: description for the user e.g. "Ogg Vorbis Audio"
+        If types is None, all file format are accepted
+        """
+        FileUpload.__init__(self)
+        self.setName(name)
+        from pyjamas import DOM
+        while DOM.getElementById(name):
+            name = "%s_" % name
+        self.setID(name)
+        self._id = name
+        self.max_size = max_size
+        self.types = types
+
+    def getFileInfo(self):
+        from __pyjamas__ import JS
+        JS("var file = top.document.getElementById(this._id).files[0]; return [file.size, file.type]")
+
+    def check(self):
+        if self.getFilename() == "":
+            return False
+        (size, filetype) = self.getFileInfo()
+        if self.types and filetype not in [x for (x, y, z) in self.types]:
+            types = ["- %s (%s)" % (z, y) for (x, y, z) in self.types]
+            Window.alert('This file type is not accepted.\nAccepted file types are:\n\n%s' % "\n".join(types))
+            return False
+        if size > self.max_size * pow(2, 20):
+            Window.alert('This file is too big!\nMaximum file size: %d MB.' % self.max_size)
+            return False
+        return True