src/eric7/WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.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 Chrome bookmarks.
8 """
9
10 import os
11 import json
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 not in ("chrome", "chromium"):
33 raise ValueError(
34 "Unsupported browser ID given ({0}).".format(sourceId))
35
36 if sourceId == "chrome":
37 if Globals.isWindowsPlatform():
38 standardDir = os.path.expandvars(
39 "%USERPROFILE%\\AppData\\Local\\Google\\Chrome\\"
40 "User Data\\Default")
41 elif Globals.isMacPlatform():
42 standardDir = os.path.expanduser(
43 "~/Library/Application Support/Google/Chrome/Default")
44 else:
45 standardDir = os.path.expanduser("~/.config/google-chrome/Default")
46 return (
47 UI.PixmapCache.getPixmap("chrome"),
48 "Google Chrome",
49 "Bookmarks",
50 QCoreApplication.translate(
51 "ChromeImporter",
52 """Google Chrome stores its bookmarks in the"""
53 """ <b>Bookmarks</b> text file. This file is usually"""
54 """ located in"""),
55 QCoreApplication.translate(
56 "ChromeImporter",
57 """Please choose the file to begin importing bookmarks."""),
58 standardDir,
59 )
60 else:
61 if Globals.isWindowsPlatform():
62 standardDir = os.path.expandvars(
63 "%USERPROFILE%\\AppData\\Local\\Google\\Chrome\\"
64 "User Data\\Default")
65 else:
66 standardDir = os.path.expanduser("~/.config/chromium/Default")
67 return (
68 UI.PixmapCache.getPixmap("chromium"),
69 "Chromium",
70 "Bookmarks",
71 QCoreApplication.translate(
72 "ChromeImporter",
73 """Chromium stores its bookmarks in the <b>Bookmarks</b>"""
74 """ text file. This file is usually located in"""),
75 QCoreApplication.translate(
76 "ChromeImporter",
77 """Please choose the file to begin importing bookmarks."""),
78 standardDir,
79 )
80
81
82 class ChromeImporter(BookmarksImporter):
83 """
84 Class implementing the Chrome bookmarks importer.
85 """
86 def __init__(self, sourceId="", parent=None):
87 """
88 Constructor
89
90 @param sourceId source ID (string)
91 @param parent reference to the parent object (QObject)
92 """
93 super().__init__(sourceId, parent)
94
95 self.__fileName = ""
96
97 def setPath(self, path):
98 """
99 Public method to set the path of the bookmarks file or directory.
100
101 @param path bookmarks file or directory (string)
102 """
103 self.__fileName = path
104
105 def open(self):
106 """
107 Public method to open the bookmarks file.
108
109 @return flag indicating success (boolean)
110 """
111 if not os.path.exists(self.__fileName):
112 self._error = True
113 self._errorString = self.tr(
114 "File '{0}' does not exist.").format(self.__fileName)
115 return False
116 return True
117
118 def importedBookmarks(self):
119 """
120 Public method to get the imported bookmarks.
121
122 @return imported bookmarks (BookmarkNode)
123 """
124 try:
125 with open(self.__fileName, "r", encoding="utf-8") as f:
126 contents = json.load(f)
127 except OSError as err:
128 self._error = True
129 self._errorString = self.tr(
130 "File '{0}' cannot be read.\nReason: {1}"
131 ).format(self.__fileName, str(err))
132 return None
133
134 from ..BookmarkNode import BookmarkNode
135 importRootNode = BookmarkNode(BookmarkNode.Folder)
136 if contents["version"] == 1:
137 self.__processRoots(contents["roots"], importRootNode)
138
139 if self._id == "chrome":
140 importRootNode.title = self.tr("Google Chrome Import")
141 elif self._id == "chromium":
142 importRootNode.title = self.tr("Chromium Import")
143 else:
144 importRootNode.title = self.tr(
145 "Imported {0}"
146 ).format(QDate.currentDate().toString(
147 Qt.DateFormat.SystemLocaleShortDate))
148 return importRootNode
149
150 def __processRoots(self, data, rootNode):
151 """
152 Private method to process the bookmark roots.
153
154 @param data dictionary with the bookmarks data (dict)
155 @param rootNode node to add the bookmarks to (BookmarkNode)
156 """
157 for node in data.values():
158 if node["type"] == "folder":
159 self.__generateFolderNode(node, rootNode)
160 elif node["type"] == "url":
161 self.__generateUrlNode(node, rootNode)
162
163 def __generateFolderNode(self, data, rootNode):
164 """
165 Private method to process a bookmarks folder.
166
167 @param data dictionary with the bookmarks data (dict)
168 @param rootNode node to add the bookmarks to (BookmarkNode)
169 """
170 from ..BookmarkNode import BookmarkNode
171 folder = BookmarkNode(BookmarkNode.Folder, rootNode)
172 folder.title = data["name"].replace("&", "&&")
173 for node in data["children"]:
174 if node["type"] == "folder":
175 self.__generateFolderNode(node, folder)
176 elif node["type"] == "url":
177 self.__generateUrlNode(node, folder)
178
179 def __generateUrlNode(self, data, rootNode):
180 """
181 Private method to process a bookmarks node.
182
183 @param data dictionary with the bookmarks data (dict)
184 @param rootNode node to add the bookmarks to (BookmarkNode)
185 """
186 from ..BookmarkNode import BookmarkNode
187 bookmark = BookmarkNode(BookmarkNode.Bookmark, rootNode)
188 bookmark.url = data["url"]
189 bookmark.title = data["name"].replace("&", "&&")

eric ide

mercurial