eric6/Helpviewer/HelpUtilities.py

branch
maintenance
changeset 7286
7eb04391adf7
parent 7226
babe80d84a3e
parent 7285
1ff497f33f31
child 7287
1c17f2191bdd
equal deleted inserted replaced
7226:babe80d84a3e 7286:7eb04391adf7
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2012 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing some global helper functions.
8 """
9
10 from __future__ import unicode_literals
11
12 import os
13
14 from PyQt5.QtCore import QUrl
15
16
17 def getFileNameFromUrl(url):
18 """
19 Module function to generate a file name based on the given URL.
20
21 @param url URL (QUrl)
22 @return file name (string)
23 """
24 fileName = url.toString(QUrl.RemoveFragment | QUrl.RemoveQuery |
25 QUrl.RemoveScheme | QUrl.RemovePort)
26 if fileName.find("/") != -1:
27 pos = fileName.rfind("/")
28 fileName = fileName[pos:]
29 fileName = fileName.replace("/", "")
30
31 fileName = filterCharsFromFilename(fileName)
32
33 if not fileName:
34 fileName = filterCharsFromFilename(url.host().replace(".", "_"))
35
36 return fileName
37
38
39 def filterCharsFromFilename(name):
40 """
41 Module function to filter illegal characters.
42
43 @param name name to be sanitized (string)
44 @return sanitized name (string)
45 """
46 return name\
47 .replace("/", "_")\
48 .replace("\\", "")\
49 .replace(":", "")\
50 .replace("*", "")\
51 .replace("?", "")\
52 .replace('"', "")\
53 .replace("<", "")\
54 .replace(">", "")\
55 .replace("|", "")
56
57
58 def ensureUniqueFilename(name, appendFormat="({0})"):
59 """
60 Module function to generate an unique file name based on a pattern.
61
62 @param name desired file name (string)
63 @param appendFormat format pattern to be used to make the unique name
64 (string)
65 @return unique file name
66 """
67 if not os.path.exists(name):
68 return name
69
70 tmpFileName = name
71 i = 1
72 while os.path.exists(tmpFileName):
73 tmpFileName = name
74 index = tmpFileName.rfind(".")
75
76 appendString = appendFormat.format(i)
77 if index == -1:
78 tmpFileName += appendString
79 else:
80 tmpFileName = tmpFileName[:index] + appendString + \
81 tmpFileName[index:]
82 i += 1
83
84 return tmpFileName
85
86
87 def parseContentDisposition(reply):
88 """
89 Function to parse a content disposition header.
90
91 @param reply network reply to be parsed
92 @type QNetworkReply
93 @return file name parsed from a content disposition header
94 @rtype str
95 """
96 path = ""
97 # step 1: check the content disposition header for a file name
98 if reply.hasRawHeader(b"Content-Disposition"):
99 from E5Network.E5RFC6266 import parse_headers
100 contentDisposition = parse_headers(
101 bytes(reply.rawHeader(b"Content-Disposition")))
102 path = contentDisposition.filename()
103 # step 2: get file name from URL
104 if not path:
105 path = reply.url().path()
106 # step 3: give a generic file name
107 if not path:
108 path = "unnamed_download"
109
110 return os.path.basename(path)

eric ide

mercurial