Helpviewer/Network/FtpReply.py

changeset 3002
6ffc581f00f1
parent 2403
e3d7a861547c
child 3022
57179e4cdadd
child 3057
10516539f238
equal deleted inserted replaced
3001:3674ff5fa8f8 3002:6ffc581f00f1
35 <head> 35 <head>
36 <title>{0}</title> 36 <title>{0}</title>
37 <style type="text/css"> 37 <style type="text/css">
38 body {{ 38 body {{
39 padding: 3em 0em; 39 padding: 3em 0em;
40 background: -webkit-gradient(linear, left top, left bottom, from(#85784A), to(#FDFDFD), color-stop(0.5, #FDFDFD)); 40 background: -webkit-gradient(linear, left top, left bottom, from(#85784A),
41 to(#FDFDFD), color-stop(0.5, #FDFDFD));
41 background-repeat: repeat-x; 42 background-repeat: repeat-x;
42 }} 43 }}
43 #box {{ 44 #box {{
44 background: white; 45 background: white;
45 border: 1px solid #85784A; 46 border: 1px solid #85784A;
122 123
123 self.__ftp = E5Ftp() 124 self.__ftp = E5Ftp()
124 125
125 self.__items = [] 126 self.__items = []
126 self.__content = QByteArray() 127 self.__content = QByteArray()
127 self.__units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] 128 self.__units = ["Bytes", "KB", "MB", "GB", "TB",
129 "PB", "EB", "ZB", "YB"]
128 self.__dirLineParser = FtpDirLineParser() 130 self.__dirLineParser = FtpDirLineParser()
129 self.__fileBytesReceived = 0 131 self.__fileBytesReceived = 0
130 132
131 if url.path() == "": 133 if url.path() == "":
132 url.setPath("/") 134 url.setPath("/")
185 self.__content.remove(0, len_) 187 self.__content.remove(0, len_)
186 return buffer 188 return buffer
187 189
188 def __doFtpCommands(self): 190 def __doFtpCommands(self):
189 """ 191 """
190 Private slot doing the sequence of FTP commands to get the requested result. 192 Private slot doing the sequence of FTP commands to get the requested
193 result.
191 """ 194 """
192 retry = True 195 retry = True
193 try: 196 try:
194 username = self.url().userName() 197 username = self.url().userName()
195 password = self.url().password() 198 password = self.url().password()
212 password = auth.password() 215 password = auth.password()
213 byAuth = True 216 byAuth = True
214 else: 217 else:
215 retry = False 218 retry = False
216 if ok: 219 if ok:
217 self.__ftp.retrlines("LIST " + self.url().path(), self.__dirCallback) 220 self.__ftp.retrlines("LIST " + self.url().path(),
221 self.__dirCallback)
218 if len(self.__items) == 1 and \ 222 if len(self.__items) == 1 and \
219 self.__items[0].isFile(): 223 self.__items[0].isFile():
220 self.__fileBytesReceived = 0 224 self.__fileBytesReceived = 0
221 self.__setContent() 225 self.__setContent()
222 self.__ftp.retrbinary( 226 self.__ftp.retrbinary(
227 self.__setListContent() 231 self.__setListContent()
228 self.__ftp.quit() 232 self.__ftp.quit()
229 except ftplib.all_errors as err: 233 except ftplib.all_errors as err:
230 if isinstance(err, socket.gaierror): 234 if isinstance(err, socket.gaierror):
231 errCode = QNetworkReply.HostNotFoundError 235 errCode = QNetworkReply.HostNotFoundError
232 elif isinstance(err, socket.error) and err.errno == errno.ECONNREFUSED: 236 elif isinstance(err, socket.error) and \
237 err.errno == errno.ECONNREFUSED:
233 errCode = QNetworkReply.ConnectionRefusedError 238 errCode = QNetworkReply.ConnectionRefusedError
234 else: 239 else:
235 errCode = QNetworkReply.ProtocolFailure 240 errCode = QNetworkReply.ProtocolFailure
236 self.setError(errCode, str(err)) 241 self.setError(errCode, str(err))
237 self.error.emit(errCode) 242 self.error.emit(errCode)
238 self.finished.emit() 243 self.finished.emit()
239 244
240 def __doFtpLogin(self, username, password, byAuth=False): 245 def __doFtpLogin(self, username, password, byAuth=False):
241 """ 246 """
242 Private method to do the FTP login with asking for a username and password, 247 Private method to do the FTP login with asking for a username and
243 if the login fails with an error 530. 248 password, if the login fails with an error 530.
244 249
245 @param username user name to use for the login (string) 250 @param username user name to use for the login (string)
246 @param password password to use for the login (string) 251 @param password password to use for the login (string)
247 @param byAuth flag indicating that the login data was provided by an 252 @param byAuth flag indicating that the login data was provided by an
248 authenticator (boolean) 253 authenticator (boolean)
258 # could be a 530, check second line 263 # could be a 530, check second line
259 lines = str(err).splitlines() 264 lines = str(err).splitlines()
260 if lines[1][:3] == "530": 265 if lines[1][:3] == "530":
261 if "usage" in "\n".join(lines[1:].lower()): 266 if "usage" in "\n".join(lines[1:].lower()):
262 # found a not supported proxy 267 # found a not supported proxy
263 self.setError(QNetworkReply.ProxyConnectionRefusedError, 268 self.setError(
269 QNetworkReply.ProxyConnectionRefusedError,
264 self.trUtf8("The proxy type seems to be wrong." 270 self.trUtf8("The proxy type seems to be wrong."
265 " If it is not in the list of supported" 271 " If it is not in the list of"
266 " proxy types please report it with the" 272 " supported proxy types please report"
267 " instructions given by the proxy.\n{0}").format( 273 " it with the instructions given by"
274 " the proxy.\n{0}").format(
268 "\n".join(lines[1:]))) 275 "\n".join(lines[1:])))
269 self.error.emit(QNetworkReply.ProxyConnectionRefusedError) 276 self.error.emit(
277 QNetworkReply.ProxyConnectionRefusedError)
270 return False, False 278 return False, False
271 else: 279 else:
272 from UI.AuthenticationDialog import AuthenticationDialog 280 from UI.AuthenticationDialog import \
273 info = self.trUtf8("<b>Connect to proxy '{0}' using:</b>")\ 281 AuthenticationDialog
282 info = self.trUtf8(
283 "<b>Connect to proxy '{0}' using:</b>")\
274 .format(Utilities.html_encode( 284 .format(Utilities.html_encode(
275 Preferences.getUI("ProxyHost/Ftp"))) 285 Preferences.getUI("ProxyHost/Ftp")))
276 dlg = AuthenticationDialog(info, 286 dlg = AuthenticationDialog(info,
277 Preferences.getUI("ProxyUser/Ftp"), True) 287 Preferences.getUI("ProxyUser/Ftp"), True)
278 dlg.setData(Preferences.getUI("ProxyUser/Ftp"), 288 dlg.setData(Preferences.getUI("ProxyUser/Ftp"),
279 Preferences.getUI("ProxyPassword/Ftp")) 289 Preferences.getUI("ProxyPassword/Ftp"))
280 if dlg.exec_() == QDialog.Accepted: 290 if dlg.exec_() == QDialog.Accepted:
281 username, password = dlg.getData() 291 username, password = dlg.getData()
282 if dlg.shallSave(): 292 if dlg.shallSave():
283 Preferences.setUI("ProxyUser/Ftp", username) 293 Preferences.setUI("ProxyUser/Ftp", username)
284 Preferences.setUI("ProxyPassword/Ftp", password) 294 Preferences.setUI(
285 self.__ftp.setProxyAuthentication(username, password) 295 "ProxyPassword/Ftp", password)
296 self.__ftp.setProxyAuthentication(username,
297 password)
286 return False, True 298 return False, True
287 return False, False 299 return False, False
288 except (ftplib.error_perm, ftplib.error_temp) as err: 300 except (ftplib.error_perm, ftplib.error_temp) as err:
289 code = err.args[0].strip()[:3] 301 code = err.args[0].strip()[:3]
290 if code in ["530", "421"]: 302 if code in ["530", "421"]:
291 # error 530 -> Login incorrect 303 # error 530 -> Login incorrect
292 # error 421 -> Login may be incorrect (reported by some proxies) 304 # error 421 -> Login may be incorrect (reported by some
305 # proxies)
293 if byAuth: 306 if byAuth:
294 self.__handler.setAuthenticator(self.url().host(), None) 307 self.__handler.setAuthenticator(self.url().host(), None)
295 auth = None 308 auth = None
296 else: 309 else:
297 auth = self.__handler.getAuthenticator(self.url().host()) 310 auth = self.__handler.getAuthenticator(self.url().host())
298 if not auth or auth.isNull() or not auth.user(): 311 if not auth or auth.isNull() or not auth.user():
299 auth = QAuthenticator() 312 auth = QAuthenticator()
300 self.__manager.authenticationRequired.emit(self, auth) 313 self.__manager.authenticationRequired.emit(self, auth)
301 if not auth.isNull(): 314 if not auth.isNull():
302 if auth.user(): 315 if auth.user():
303 self.__handler.setAuthenticator(self.url().host(), auth) 316 self.__handler.setAuthenticator(self.url().host(),
317 auth)
304 return False, True 318 return False, True
305 return False, False 319 return False, False
306 return False, True 320 return False, True
307 else: 321 else:
308 raise 322 raise
330 344
331 @param data data received from the FTP server (bytes) 345 @param data data received from the FTP server (bytes)
332 """ 346 """
333 self.__content += QByteArray(data) 347 self.__content += QByteArray(data)
334 self.__fileBytesReceived += len(data) 348 self.__fileBytesReceived += len(data)
335 self.downloadProgress.emit(self.__fileBytesReceived, self.__items[0].size()) 349 self.downloadProgress.emit(
350 self.__fileBytesReceived, self.__items[0].size())
336 self.readyRead.emit() 351 self.readyRead.emit()
337 352
338 QCoreApplication.processEvents() 353 QCoreApplication.processEvents()
339 354
340 def __setContent(self): 355 def __setContent(self):
341 """ 356 """
342 Private method to finish the setup of the data. 357 Private method to finish the setup of the data.
343 """ 358 """
344 mtype, encoding = mimetypes.guess_type(self.url().toString()) 359 mtype, encoding = mimetypes.guess_type(self.url().toString())
345 self.open(QIODevice.ReadOnly | QIODevice.Unbuffered) 360 self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
346 self.setHeader(QNetworkRequest.ContentLengthHeader, self.__items[0].size()) 361 self.setHeader(QNetworkRequest.ContentLengthHeader,
362 self.__items[0].size())
347 if mtype: 363 if mtype:
348 self.setHeader(QNetworkRequest.ContentTypeHeader, mtype) 364 self.setHeader(QNetworkRequest.ContentTypeHeader, mtype)
349 self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200) 365 self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
350 self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok") 366 self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
351 self.metaDataChanged.emit() 367 self.metaDataChanged.emit()
359 @return CSS class string (string) 375 @return CSS class string (string)
360 """ 376 """
361 cssString = \ 377 cssString = \
362 """a.{{0}} {{{{\n"""\ 378 """a.{{0}} {{{{\n"""\
363 """ padding-left: {0}px;\n"""\ 379 """ padding-left: {0}px;\n"""\
364 """ background: transparent url(data:image/png;base64,{1}) no-repeat center left;\n"""\ 380 """ background: transparent url(data:image/png;base64,{1})"""\
381 """ no-repeat center left;\n"""\
365 """ font-weight: bold;\n"""\ 382 """ font-weight: bold;\n"""\
366 """}}}}\n""" 383 """}}}}\n"""
367 pixmap = icon.pixmap(size, size) 384 pixmap = icon.pixmap(size, size)
368 imageBuffer = QBuffer() 385 imageBuffer = QBuffer()
369 imageBuffer.open(QIODevice.ReadWrite) 386 imageBuffer.open(QIODevice.ReadWrite)
386 403
387 baseUrl = self.url().toString() 404 baseUrl = self.url().toString()
388 basePath = u.path() 405 basePath = u.path()
389 406
390 linkClasses = {} 407 linkClasses = {}
391 iconSize = QWebSettings.globalSettings().fontSize(QWebSettings.DefaultFontSize) 408 iconSize = QWebSettings.globalSettings().fontSize(
409 QWebSettings.DefaultFontSize)
392 410
393 parent = u.resolved(QUrl("..")) 411 parent = u.resolved(QUrl(".."))
394 if parent.isParentOf(u): 412 if parent.isParentOf(u):
395 icon = UI.PixmapCache.getIcon("up.png") 413 icon = UI.PixmapCache.getIcon("up.png")
396 linkClasses["link_parent"] = \ 414 linkClasses["link_parent"] = \
467 ) 485 )
468 self.__content = QByteArray(content.encode("utf8")) 486 self.__content = QByteArray(content.encode("utf8"))
469 self.__content.append(512 * b' ') 487 self.__content.append(512 * b' ')
470 488
471 self.open(QIODevice.ReadOnly | QIODevice.Unbuffered) 489 self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
472 self.setHeader(QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8") 490 self.setHeader(
473 self.setHeader(QNetworkRequest.ContentLengthHeader, self.__content.size()) 491 QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8")
492 self.setHeader(
493 QNetworkRequest.ContentLengthHeader, self.__content.size())
474 self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200) 494 self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
475 self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok") 495 self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
476 self.metaDataChanged.emit() 496 self.metaDataChanged.emit()
477 self.downloadProgress.emit(self.__content.size(), self.__content.size()) 497 self.downloadProgress.emit(
498 self.__content.size(), self.__content.size())
478 self.readyRead.emit() 499 self.readyRead.emit()

eric ide

mercurial