WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.py

branch
QtWebEngine
changeset 4732
5ac4fc1dfc20
parent 4631
5c1a96925da4
child 5389
9b1c800daff3
equal deleted inserted replaced
4731:67d861d9e492 4732:5ac4fc1dfc20
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2012 - 2016 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing an importer for Chrome bookmarks.
8 """
9
10 from __future__ import unicode_literals
11
12 import os
13 import json
14
15 from PyQt5.QtCore import QCoreApplication, QDate, Qt
16
17 from .BookmarksImporter import BookmarksImporter
18
19 import UI.PixmapCache
20 import Globals
21
22
23 def getImporterInfo(id):
24 """
25 Module function to get information for the given source id.
26
27 @param id id of the browser ("chrome" or "chromium")
28 @return tuple with an icon (QPixmap), readable name (string), name of
29 the default bookmarks file (string), an info text (string),
30 a prompt (string) and the default directory of the bookmarks file
31 (string)
32 @exception ValueError raised to indicate an invalid browser ID
33 """
34 if id == "chrome":
35 if Globals.isWindowsPlatform():
36 standardDir = os.path.expandvars(
37 "%USERPROFILE%\\AppData\\Local\\Google\\Chrome\\"
38 "User Data\\Default")
39 elif Globals.isMacPlatform():
40 standardDir = os.path.expanduser(
41 "~/Library/Application Support/Google/Chrome/Default")
42 else:
43 standardDir = os.path.expanduser("~/.config/google-chrome/Default")
44 return (
45 UI.PixmapCache.getPixmap("chrome.png"),
46 "Google Chrome",
47 "Bookmarks",
48 QCoreApplication.translate(
49 "ChromeImporter",
50 """Google Chrome stores its bookmarks in the"""
51 """ <b>Bookmarks</b> text file. This file is usually"""
52 """ located in"""),
53 QCoreApplication.translate(
54 "ChromeImporter",
55 """Please choose the file to begin importing bookmarks."""),
56 standardDir,
57 )
58 elif id == "chromium":
59 if Globals.isWindowsPlatform():
60 standardDir = os.path.expandvars(
61 "%USERPROFILE%\\AppData\\Local\\Google\\Chrome\\"
62 "User Data\\Default")
63 else:
64 standardDir = os.path.expanduser("~/.config/chromium/Default")
65 return (
66 UI.PixmapCache.getPixmap("chromium.png"),
67 "Chromium",
68 "Bookmarks",
69 QCoreApplication.translate(
70 "ChromeImporter",
71 """Chromium stores its bookmarks in the <b>Bookmarks</b>"""
72 """ text file. This file is usually located in"""),
73 QCoreApplication.translate(
74 "ChromeImporter",
75 """Please choose the file to begin importing bookmarks."""),
76 standardDir,
77 )
78 else:
79 raise ValueError("Unsupported browser ID given ({0}).".format(id))
80
81
82 class ChromeImporter(BookmarksImporter):
83 """
84 Class implementing the Chrome bookmarks importer.
85 """
86 def __init__(self, id="", parent=None):
87 """
88 Constructor
89
90 @param id source ID (string)
91 @param parent reference to the parent object (QObject)
92 """
93 super(ChromeImporter, self).__init__(id, 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 f = open(self.__fileName, "r", encoding="utf-8")
126 contents = json.load(f)
127 f.close()
128 except IOError as err:
129 self._error = True
130 self._errorString = self.tr(
131 "File '{0}' cannot be read.\nReason: {1}")\
132 .format(self.__fileName, str(err))
133 return None
134
135 from ..BookmarkNode import BookmarkNode
136 importRootNode = BookmarkNode(BookmarkNode.Folder)
137 if contents["version"] == 1:
138 self.__processRoots(contents["roots"], importRootNode)
139
140 if self._id == "chrome":
141 importRootNode.title = self.tr("Google Chrome Import")
142 elif self._id == "chromium":
143 importRootNode.title = self.tr("Chromium Import")
144 else:
145 importRootNode.title = self.tr("Imported {0}")\
146 .format(QDate.currentDate().toString(Qt.SystemLocaleShortDate))
147 return importRootNode
148
149 def __processRoots(self, data, rootNode):
150 """
151 Private method to process the bookmark roots.
152
153 @param data dictionary with the bookmarks data (dict)
154 @param rootNode node to add the bookmarks to (BookmarkNode)
155 """
156 for node in data.values():
157 if node["type"] == "folder":
158 self.__generateFolderNode(node, rootNode)
159 elif node["type"] == "url":
160 self.__generateUrlNode(node, rootNode)
161
162 def __generateFolderNode(self, data, rootNode):
163 """
164 Private method to process a bookmarks folder.
165
166 @param data dictionary with the bookmarks data (dict)
167 @param rootNode node to add the bookmarks to (BookmarkNode)
168 """
169 from ..BookmarkNode import BookmarkNode
170 folder = BookmarkNode(BookmarkNode.Folder, rootNode)
171 folder.title = data["name"].replace("&", "&&")
172 for node in data["children"]:
173 if node["type"] == "folder":
174 self.__generateFolderNode(node, folder)
175 elif node["type"] == "url":
176 self.__generateUrlNode(node, folder)
177
178 def __generateUrlNode(self, data, rootNode):
179 """
180 Private method to process a bookmarks node.
181
182 @param data dictionary with the bookmarks data (dict)
183 @param rootNode node to add the bookmarks to (BookmarkNode)
184 """
185 from ..BookmarkNode import BookmarkNode
186 bookmark = BookmarkNode(BookmarkNode.Bookmark, rootNode)
187 bookmark.url = data["url"]
188 bookmark.title = data["name"].replace("&", "&&")

eric ide

mercurial