src/eric7/WebBrowser/Bookmarks/BookmarksImporters/SafariImporter.py

branch
eric7
changeset 9221
bf71ee032bb4
parent 9209
b99e7fd55fd3
child 9413
80c06d472826
equal deleted inserted replaced
9220:e9e7eca7efee 9221:bf71ee032bb4
19 19
20 20
21 def getImporterInfo(sourceId): 21 def getImporterInfo(sourceId):
22 """ 22 """
23 Module function to get information for the given source id. 23 Module function to get information for the given source id.
24 24
25 @param sourceId id of the browser ("chrome" or "chromium") 25 @param sourceId id of the browser ("chrome" or "chromium")
26 @return tuple with an icon (QPixmap), readable name (string), name of 26 @return tuple with an icon (QPixmap), readable name (string), name of
27 the default bookmarks file (string), an info text (string), 27 the default bookmarks file (string), an info text (string),
28 a prompt (string) and the default directory of the bookmarks file 28 a prompt (string) and the default directory of the bookmarks file
29 (string) 29 (string)
30 @exception ValueError raised to indicate an invalid browser ID 30 @exception ValueError raised to indicate an invalid browser ID
31 """ 31 """
32 if sourceId != "safari": 32 if sourceId != "safari":
33 raise ValueError( 33 raise ValueError("Unsupported browser ID given ({0}).".format(sourceId))
34 "Unsupported browser ID given ({0}).".format(sourceId)) 34
35
36 if Globals.isWindowsPlatform(): 35 if Globals.isWindowsPlatform():
37 standardDir = os.path.expandvars( 36 standardDir = os.path.expandvars("%APPDATA%\\Apple Computer\\Safari")
38 "%APPDATA%\\Apple Computer\\Safari")
39 elif Globals.isMacPlatform(): 37 elif Globals.isMacPlatform():
40 standardDir = os.path.expanduser("~/Library/Safari") 38 standardDir = os.path.expanduser("~/Library/Safari")
41 else: 39 else:
42 standardDir = "" 40 standardDir = ""
43 return ( 41 return (
46 "Bookmarks.plist", 44 "Bookmarks.plist",
47 QCoreApplication.translate( 45 QCoreApplication.translate(
48 "SafariImporter", 46 "SafariImporter",
49 """Apple Safari stores its bookmarks in the""" 47 """Apple Safari stores its bookmarks in the"""
50 """ <b>Bookmarks.plist</b> file. This file is usually""" 48 """ <b>Bookmarks.plist</b> file. This file is usually"""
51 """ located in"""), 49 """ located in""",
50 ),
52 QCoreApplication.translate( 51 QCoreApplication.translate(
53 "SafariImporter", 52 "SafariImporter", """Please choose the file to begin importing bookmarks."""
54 """Please choose the file to begin importing bookmarks."""), 53 ),
55 standardDir, 54 standardDir,
56 ) 55 )
57 56
58 57
59 class SafariImporter(BookmarksImporter): 58 class SafariImporter(BookmarksImporter):
60 """ 59 """
61 Class implementing the Apple Safari bookmarks importer. 60 Class implementing the Apple Safari bookmarks importer.
62 """ 61 """
62
63 def __init__(self, sourceId="", parent=None): 63 def __init__(self, sourceId="", parent=None):
64 """ 64 """
65 Constructor 65 Constructor
66 66
67 @param sourceId source ID (string) 67 @param sourceId source ID (string)
68 @param parent reference to the parent object (QObject) 68 @param parent reference to the parent object (QObject)
69 """ 69 """
70 super().__init__(sourceId, parent) 70 super().__init__(sourceId, parent)
71 71
72 self.__fileName = "" 72 self.__fileName = ""
73 73
74 def setPath(self, path): 74 def setPath(self, path):
75 """ 75 """
76 Public method to set the path of the bookmarks file or directory. 76 Public method to set the path of the bookmarks file or directory.
77 77
78 @param path bookmarks file or directory (string) 78 @param path bookmarks file or directory (string)
79 """ 79 """
80 self.__fileName = path 80 self.__fileName = path
81 81
82 def open(self): 82 def open(self):
83 """ 83 """
84 Public method to open the bookmarks file. 84 Public method to open the bookmarks file.
85 85
86 @return flag indicating success (boolean) 86 @return flag indicating success (boolean)
87 """ 87 """
88 if not os.path.exists(self.__fileName): 88 if not os.path.exists(self.__fileName):
89 self._error = True 89 self._error = True
90 self._errorString = self.tr( 90 self._errorString = self.tr("File '{0}' does not exist.").format(
91 "File '{0}' does not exist." 91 self.__fileName
92 ).format(self.__fileName) 92 )
93 return False 93 return False
94 return True 94 return True
95 95
96 def importedBookmarks(self): 96 def importedBookmarks(self):
97 """ 97 """
98 Public method to get the imported bookmarks. 98 Public method to get the imported bookmarks.
99 99
100 @return imported bookmarks (BookmarkNode) 100 @return imported bookmarks (BookmarkNode)
101 """ 101 """
102 try: 102 try:
103 with open(self.__fileName, "rb") as f: 103 with open(self.__fileName, "rb") as f:
104 bookmarksDict = plistlib.load(f) 104 bookmarksDict = plistlib.load(f)
105 except (plistlib.InvalidFileException, OSError) as err: 105 except (plistlib.InvalidFileException, OSError) as err:
106 self._error = True 106 self._error = True
107 self._errorString = self.tr( 107 self._errorString = self.tr(
108 "Bookmarks file cannot be read.\nReason: {0}".format(str(err))) 108 "Bookmarks file cannot be read.\nReason: {0}".format(str(err))
109 )
109 return None 110 return None
110 111
111 from ..BookmarkNode import BookmarkNode 112 from ..BookmarkNode import BookmarkNode
113
112 importRootNode = BookmarkNode(BookmarkNode.Folder) 114 importRootNode = BookmarkNode(BookmarkNode.Folder)
113 if ( 115 if (
114 bookmarksDict["WebBookmarkFileVersion"] == 1 and 116 bookmarksDict["WebBookmarkFileVersion"] == 1
115 bookmarksDict["WebBookmarkType"] == "WebBookmarkTypeList" 117 and bookmarksDict["WebBookmarkType"] == "WebBookmarkTypeList"
116 ): 118 ):
117 self.__processChildren(bookmarksDict["Children"], importRootNode) 119 self.__processChildren(bookmarksDict["Children"], importRootNode)
118 120
119 if self._id == "safari": 121 if self._id == "safari":
120 importRootNode.title = self.tr("Apple Safari Import") 122 importRootNode.title = self.tr("Apple Safari Import")
121 else: 123 else:
122 importRootNode.title = self.tr( 124 importRootNode.title = self.tr("Imported {0}").format(
123 "Imported {0}" 125 QDate.currentDate().toString(Qt.DateFormat.SystemLocaleShortDate)
124 ).format(QDate.currentDate().toString( 126 )
125 Qt.DateFormat.SystemLocaleShortDate))
126 return importRootNode 127 return importRootNode
127 128
128 def __processChildren(self, children, rootNode): 129 def __processChildren(self, children, rootNode):
129 """ 130 """
130 Private method to process the list of children. 131 Private method to process the list of children.
131 132
132 @param children list of child nodes to be processed (list of dict) 133 @param children list of child nodes to be processed (list of dict)
133 @param rootNode node to add the bookmarks to (BookmarkNode) 134 @param rootNode node to add the bookmarks to (BookmarkNode)
134 """ 135 """
135 from ..BookmarkNode import BookmarkNode 136 from ..BookmarkNode import BookmarkNode
137
136 for child in children: 138 for child in children:
137 if child["WebBookmarkType"] == "WebBookmarkTypeList": 139 if child["WebBookmarkType"] == "WebBookmarkTypeList":
138 folder = BookmarkNode(BookmarkNode.Folder, rootNode) 140 folder = BookmarkNode(BookmarkNode.Folder, rootNode)
139 folder.title = child["Title"].replace("&", "&&") 141 folder.title = child["Title"].replace("&", "&&")
140 if "Children" in child: 142 if "Children" in child:
141 self.__processChildren(child["Children"], folder) 143 self.__processChildren(child["Children"], folder)
142 elif child["WebBookmarkType"] == "WebBookmarkTypeLeaf": 144 elif child["WebBookmarkType"] == "WebBookmarkTypeLeaf":
143 url = child["URLString"] 145 url = child["URLString"]
144 if url.startswith(("place:", "about:")): 146 if url.startswith(("place:", "about:")):
145 continue 147 continue
146 148
147 bookmark = BookmarkNode(BookmarkNode.Bookmark, rootNode) 149 bookmark = BookmarkNode(BookmarkNode.Bookmark, rootNode)
148 bookmark.url = url 150 bookmark.url = url
149 bookmark.title = ( 151 bookmark.title = child["URIDictionary"]["title"].replace("&", "&&")
150 child["URIDictionary"]["title"].replace("&", "&&")
151 )

eric ide

mercurial