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

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

eric ide

mercurial