Debian Codegraph @

src/pyj/ajax.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import hash_literals
4
5 from gettext import gettext as _
6
7
8 default_timeout = 300
9
10
11 def set_default_timeout(val):
12 nonlocal default_timeout
13 default_timeout = val
14
15
16 def encode_query_component(x):
17 ans = encodeURIComponent(x)
18 # The following exceptions are to make epubcfi() look better
19 ans = ans.replace(/%2[fF]/g, '/')
20 ans = ans.replace(/%40/g, '@')
21 ans = ans.replace(/%5[bB]/g, '[')
22 ans = ans.replace(/%5[dD]/g, ']')
23 ans = ans.replace(/%5[eE]/g, '^')
24 ans = ans.replace(/%3[aA]/g, ':')
25 return ans
26
27
28 def encode_query(query, qchar):
29 if not query:
30 return ''
31 qchar = qchar or '?'
32 keys = Object.keys(query).sort()
33 ans = ''
34 if keys.length:
35 for k in keys:
36 val = query[k]
37 if val is undefined or val is None or val is '':
38 continue
39 ans += qchar + encodeURIComponent(k) + '=' + encode_query_component(val.toString())
40 qchar = '&'
41 return ans
42
43
44 def absolute_path(path):
45 if path[0] is not '/':
46 slash = '' if window.location.pathname[-1] is '/' else '/'
47 path = window.location.pathname + slash + path
48 return path
49
50
51 def workaround_qt_bug(xhr, end_type, ok_code=200):
52 if end_type is 'error' and xhr.status is ok_code and window.navigator.userAgent.indexOf('calibre-viewer') is 0:
53 end_type = 'load'
54 return end_type
55
56
57 def ajax(path, on_complete, on_progress=None, bypass_cache=True, method='GET', query=None, timeout=None, ok_code=200, progress_totals_needed=True):
58 # Run an AJAX request. on_complete must be a function that accepts three
59 # arguments: end_type, xhr, ev where end_type is one of 'abort', 'error',
60 # 'load', 'timeout'. In case end_type is anything other than 'load' you can
61 # get a descriptive error message via `xhr.error_html`. on_progress, if
62 # provided must be a function accepting three arguments: loaded, total, xhr
63 # where loaded is the number of bytes received, total is the total size.
64 #
65 # Returns the xhr object, call xhr.send() to start the request.
66 if timeout is None:
67 timeout = default_timeout
68 query = query or {}
69 xhr = XMLHttpRequest()
70 eq = encode_query(query)
71 has_query = eq.length > 0
72 path = absolute_path(path) + eq
73 if bypass_cache:
74 path += ('&' if has_query else '?') + Date().getTime()
75
76 xhr.request_path = path
77 xhr.error_html = ''
78
79 def set_error(event, is_network_error):
80 if is_network_error:
81 xhr.error_html = str.format(_('Failed to communicate with "{}", network error. Is the server running and accessible?'), xhr.request_path)
82 elif event is 'timeout':
83 xhr.error_html = str.format(_('Failed to communicate with "{}", timed out after: {} seconds'), xhr.request_path, timeout)
84 elif event is 'abort':
85 xhr.error_html = str.format(_('Failed to communicate with "{}", aborted'), xhr.request_path)
86 else:
87 try:
88 rtext = xhr.responseText or ''
89 except:
90 rtext = ''
91 xhr.error_html = str.format(
92 _('Failed to communicate with "{}", with status: [{} ({})] {}<br><br>{}'),
93 xhr.request_path,
94 xhr.status,
95 event,
96 xhr.statusText,
97 rtext[:200]
98 )
99
100 def progress_callback(ev):
101 if ev.lengthComputable:
102 on_progress(ev.loaded, ev.total, xhr)
103 elif ev.loaded:
104 if not progress_totals_needed:
105 on_progress(ev.loaded, undefined, xhr)
106 return
107 ul = xhr.getResponseHeader('Calibre-Uncompressed-Length')
108 if ul:
109 try:
110 ul = int(ul)
111 except Exception:
112 return
113 on_progress(ev.loaded, ul, xhr)
114
115 def complete_callback(end_type, ev):
116 is_network_error = ev if end_type is 'error' else False
117 if xhr.status is not ok_code and end_type is 'load':
118 end_type = 'error'
119 end_type = workaround_qt_bug(xhr, end_type, ok_code)
120 if end_type is not 'load':
121 set_error(end_type, is_network_error)
122 on_complete(end_type, xhr, ev)
123
124 if on_progress:
125 xhr.addEventListener('progress', progress_callback)
126 xhr.addEventListener('abort', def (ev): complete_callback('abort', ev);)
127 xhr.addEventListener('error', def (ev): complete_callback('error', ev);)
128 xhr.addEventListener('load', def (ev): complete_callback('load', ev);)
129 xhr.addEventListener('timeout', def (ev): complete_callback('timeout', ev);)
130 xhr.open(method, path)
131 xhr.timeout = timeout * 1000 # IE requires timeout to be set after open
132 return xhr
133
134
135 def ajax_send(path, data, on_complete, on_progress=None, query=None, timeout=None, ok_code=200):
136 # Unfortunately, browsers do not allow sending of data with HTTP GET, except
137 # as query parameters, so we have to use POST
138 xhr = ajax(path, on_complete, on_progress, False, 'POST', query, timeout, ok_code)
139 xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
140 xhr.send(JSON.stringify(data))
141 return xhr
142
143
144 def ajax_send_file(path, file, on_complete, on_progress, timeout=None, ok_code=200):
145 xhr = ajax(path, on_complete, on_progress, False, 'POST', timeout, ok_code)
146 if file.type:
147 xhr.overrideMimeType(file.type)
148 xhr.send(file)
149 return xhr
150
151
152 def console_print():
153 ρσ_print.apply(this, arguments) # noqa: undef
154 data = ' '.join(map(str, Array.from (arguments))) + '\n'
155 xhr = ajax('console-print', def (): pass;, method='POST', progress_totals_needed=False)
156 xhr.send(data)
157
158 # TODO: Implement AJAX based switch user by:
159 # 1) POST to a logout URL with an incorrect username and password
160 # 2) Have the server accept that incorrect username/password
161 # 3) Navigate to / which should cause the browser to re-prompt for username and password
162 # (only problem is login dialog will likely pre-show the wrong username) To workaround that,
163 # You can consider using a dedicated ajax based login form, see http://www.peej.co.uk/articles/http-auth-with-html-forms.html)