Code

Ticket #4165: 5126_oldforms_admin_update.diff

File 5126_oldforms_admin_update.diff, 7.3 KB (added by Michael Axiak <axiak@…>, 7 years ago)

Reworked a lot of JS, this is for oldforms-admin.

Line 
1Index: django/contrib/admin/media/js/UploadProgress.js
2===================================================================
3--- django/contrib/admin/media/js/UploadProgress.js     (revision 0)
4+++ django/contrib/admin/media/js/UploadProgress.js     (revision 0)
5@@ -0,0 +1,172 @@
6+
7+var upload_progress_failures = 0;
8+var TOTAL_UPLOAD_PROGRESS_FAILURES = 10;
9+
10+function getxy(){
11+    var x,y;
12+    if (self.innerHeight) // all except Explorer
13+        {
14+        x = self.innerWidth;
15+        y = self.innerHeight;
16+        }
17+    else if (document.documentElement && document.documentElement.clientHeight)
18+        // Explorer 6 Strict Mode
19+        {
20+        x = document.documentElement.clientWidth;
21+        y = document.documentElement.clientHeight;
22+        }
23+    else if (document.body) // other Explorers
24+        {
25+        x = document.body.clientWidth;
26+        y = document.body.clientHeight;
27+        }
28+    return {'x':x,'y':y}
29+    }
30+
31+
32+function upload_ajax_problem() {
33+    /* If there's a problem, will cancel after
34+       TOTAL_UPLOAD_PROGRESS_FAILURES tries.   */
35+
36+    progress_wrap = document.getElementById('progress_wrap');
37+    upload_progress_failures++;
38+    if (upload_progress_failures >= TOTAL_UPLOAD_PROGRESS_FAILURES){
39+      window.clearTimeout(interval);
40+    }
41+    progress_wrap.style.visibility = 'hidden';
42+}
43+
44+var humanvalue = ['B','KB','MB','GB']
45+function humanize(bytes) {
46+  curbytes = bytes;
47+  iterations = 0;
48+  while (curbytes>1024) {
49+    iterations++;
50+    curbytes=curbytes/1024;
51+  }
52+  return curbytes.toFixed(1) + ' ' + humanvalue[iterations];
53+}
54+
55+interval = null;
56+function fetch(uuid) {
57+  /* no ajax here */
58+  if (!xmlhttp) {
59+    upload_ajax_problem();
60+    return;
61+  }
62+
63+  req = xmlhttp;
64+  req.open("GET", "/admin/upload_progress/", true);
65+  req.onreadystatechange = function () {
66+    if (req.readyState == 4) {
67+      try {
68+        request_status = req.status;
69+      } catch (e) {
70+        /* Really bad. */
71+        request_status = -1;
72+      }
73+      if (request_status == 200) {
74+        var upload = new Function(" return "+req.responseText)();
75+        if (upload) {
76+          progress_wrap = document.getElementById('progress_wrap');
77+
78+          if (!upload.state) {
79+            progress_wrap.style.visibility = 'hidden';
80+            return
81+          } else if (upload.state == 'done') {
82+             window.clearTimeout(interval);
83+             progress_wrap.style.visibility = 'hidden';
84+             return;   
85+          } else {
86+             progress_bar = document.getElementById('progress_bar');
87+             bar_txt = document.getElementById('progress_text');
88+
89+             progress_wrap.style.visibility = 'visible';
90+             bar_txt.innerHTML = ((upload.received / upload.size) * 100).toFixed(1)
91+                     + '% - ' + humanize(upload.received) + ' of '
92+                     + humanize(upload.size);
93+             bar_width__px = 400 * upload.received / upload.size;
94+             progress_bar.style.width = bar_width__px + 'px';
95+          }
96+        } else {
97+          upload_ajax_problem();
98+        }
99+      } else {
100+        upload_ajax_problem();
101+      }
102+    }
103+  };
104+  try {
105+    req.setRequestHeader("X-Progress-Id", uuid);
106+  } catch (e) {
107+    /* couldn't set the header, the request is broken. */
108+    req.abort();
109+  }
110+  req.send(null);
111+
112+}
113+
114+
115+function openprogress(e) {
116+    upload_progress_failures = 0;
117+    uuid = "";
118+    for (i = 0; i < 32; i++) {
119+        uuid += Math.floor(Math.random() * 16).toString(16);
120+        }
121+    frm = e.target||e.srcElement;
122+
123+    if (frm.action.indexOf('?') == -1) {
124+       frm.action=frm.action+"?progress_id=" + uuid;
125+    } else {
126+       frm.action=frm.action+"&progress_id=" + uuid;
127+    }
128+
129+    if (document.getElementById('progress_wrap')) {
130+        document.getElementById('progress_wrap').style.visibility = 'hidden';
131+        document.getElementById('progress_bar').style.width = '0';
132+        document.getElementById('progress_text').innerHTML = '0%';
133+
134+        interval = window.setInterval(
135+        function () {
136+            fetch(uuid);
137+            },
138+        1000
139+        );
140+        return;
141+    }
142+
143+    pos = getxy()
144+    posx = parseInt((pos.x/2)-(420/2), 10)
145+    posy = parseInt((pos.y/2)-(50/2), 10)
146+
147+    progress_wrap = quickElement('div', document.body, '', 'style',
148+        'position: absolute; top: '+posy+'px; left: '+posx+'px; height: 50px; ' +
149+        'padding: 10px; width: 420px; background: #ffffff; ' +
150+        'border: solid 1px #dddddd;' +
151+        'visibility: hidden;', 'id', 'progress_wrap')
152+
153+    progress_label = quickElement('h1', progress_wrap, 'Upload progress')
154+
155+    progress = quickElement('div', progress_wrap, '', 'style',
156+        'top: 0; left: 0; width: 0px; ', 'id', 'progress_bar', 'class', 'submit-row')
157+
158+    progress_text = quickElement('div', progress_wrap, '0%', 'style',
159+        'color: #000000; ', 'id', 'progress_text')
160+    progress_wrap.style.visibility = 'hidden';
161+    interval = window.setInterval(
162+        function () {
163+            fetch(uuid);
164+            },
165+        1000
166+        );
167+    }
168+
169+addEvent(window, 'load', function() {
170+        frms = document.getElementsByTagName('form');
171+        for (var i=0; i<frms.length; i++) {
172+           if (frms[i].encoding.toLowerCase() == 'multipart/form-data') {
173+              addEvent(frms[i], 'submit',  openprogress);
174+              return;
175+           }
176+        }
177+    });
178Index: django/contrib/admin/urls.py
179===================================================================
180--- django/contrib/admin/urls.py        (revision 5126)
181+++ django/contrib/admin/urls.py        (working copy)
182@@ -10,6 +10,7 @@
183     ('^$', 'django.contrib.admin.views.main.index'),
184     ('^r/(\d+)/(.*)/$', 'django.views.defaults.shortcut'),
185     ('^jsi18n/$', i18n_view, {'packages': 'django.conf'}),
186+    ('^upload_progress/$', 'django.contrib.admin.views.main.upload_progress'),
187     ('^logout/$', 'django.contrib.auth.views.logout'),
188     ('^password_change/$', 'django.contrib.auth.views.password_change'),
189     ('^password_change/done/$', 'django.contrib.auth.views.password_change_done'),
190Index: django/contrib/admin/views/main.py
191===================================================================
192--- django/contrib/admin/views/main.py  (revision 5126)
193+++ django/contrib/admin/views/main.py  (working copy)
194@@ -81,6 +81,8 @@
195 def get_javascript_imports(opts, auto_populated_fields, field_sets):
196 # Put in any necessary JavaScript imports.
197     js = ['js/core.js', 'js/admin/RelatedObjectLookups.js']
198+    if opts.has_field_type(models.FileField):
199+        js.append('js/UploadProgress.js')
200     if auto_populated_fields:
201         js.append('js/urlify.js')
202     if opts.has_field_type(models.DateTimeField) or opts.has_field_type(models.TimeField) or opts.has_field_type(models.DateField):
203@@ -777,3 +779,16 @@
204                                'admin/%s/change_list.html' % app_label,
205                                'admin/change_list.html'], context_instance=c)
206 change_list = staff_member_required(never_cache(change_list))
207+
208+def upload_progress(request):
209+    """
210+    Given this request, returns a JSON
211+    object that has information on a file upload progress.
212+    If there is no file upload in progress, returns an
213+    empty dictionary, '{}'.
214+    """
215+    from django.utils import simplejson
216+
217+    content = simplejson.dumps(request.file_progress)
218+
219+    return HttpResponse(content=content, mimetype='text/plain')