WebBrowser/Bookmarks/BookmarksImporters/FirefoxImporter.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 Firefox bookmarks.
8 """
9
10 from __future__ import unicode_literals
11
12 import os
13 import sqlite3
14
15 from PyQt5.QtCore import QCoreApplication, QDate, Qt, QUrl
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 == "firefox":
35 if Globals.isWindowsPlatform():
36 standardDir = os.path.expandvars(
37 "%APPDATA%\\Mozilla\\Firefox\\Profiles")
38 elif Globals.isMacPlatform():
39 standardDir = os.path.expanduser(
40 "~/Library/Application Support/Firefox/Profiles")
41 else:
42 standardDir = os.path.expanduser("~/.mozilla/firefox")
43 return (
44 UI.PixmapCache.getPixmap("chrome.png"),
45 "Mozilla Firefox",
46 "places.sqlite",
47 QCoreApplication.translate(
48 "FirefoxImporter",
49 """Mozilla Firefox stores its bookmarks in the"""
50 """ <b>places.sqlite</b> SQLite database. This file is"""
51 """ usually located in"""),
52 QCoreApplication.translate(
53 "FirefoxImporter",
54 """Please choose the file to begin importing bookmarks."""),
55 standardDir,
56 )
57 else:
58 raise ValueError("Unsupported browser ID given ({0}).".format(id))
59
60
61 class FirefoxImporter(BookmarksImporter):
62 """
63 Class implementing the Chrome bookmarks importer.
64 """
65 def __init__(self, id="", parent=None):
66 """
67 Constructor
68
69 @param id source ID (string)
70 @param parent reference to the parent object (QObject)
71 """
72 super(FirefoxImporter, self).__init__(id, parent)
73
74 self.__fileName = ""
75 self.__db = None
76
77 def setPath(self, path):
78 """
79 Public method to set the path of the bookmarks file or directory.
80
81 @param path bookmarks file or directory (string)
82 """
83 self.__fileName = path
84
85 def open(self):
86 """
87 Public method to open the bookmarks file.
88
89 @return flag indicating success (boolean)
90 """
91 if not os.path.exists(self.__fileName):
92 self._error = True
93 self._errorString = self.tr("File '{0}' does not exist.")\
94 .format(self.__fileName)
95 return False
96
97 try:
98 self.__db = sqlite3.connect(self.__fileName)
99 except sqlite3.DatabaseError as err:
100 self._error = True
101 self._errorString = self.tr(
102 "Unable to open database.\nReason: {0}").format(str(err))
103 return False
104
105 return True
106
107 def importedBookmarks(self):
108 """
109 Public method to get the imported bookmarks.
110
111 @return imported bookmarks (BookmarkNode)
112 """
113 from ..BookmarkNode import BookmarkNode
114 importRootNode = BookmarkNode(BookmarkNode.Root)
115
116 # step 1: build the hierarchy of bookmark folders
117 folders = {}
118
119 try:
120 cursor = self.__db.cursor()
121 cursor.execute(
122 "SELECT id, parent, title FROM moz_bookmarks "
123 "WHERE type = 2 and title !=''")
124 for row in cursor:
125 id_ = row[0]
126 parent = row[1]
127 title = row[2]
128 if parent in folders:
129 folder = BookmarkNode(BookmarkNode.Folder, folders[parent])
130 else:
131 folder = BookmarkNode(BookmarkNode.Folder, importRootNode)
132 folder.title = title.replace("&", "&&")
133 folders[id_] = folder
134 except sqlite3.DatabaseError as err:
135 self._error = True
136 self._errorString = self.tr(
137 "Unable to open database.\nReason: {0}").format(str(err))
138 return None
139
140 try:
141 cursor = self.__db.cursor()
142 cursor.execute(
143 "SELECT parent, title, fk, position FROM moz_bookmarks"
144 " WHERE type = 1 and title != '' ORDER BY position")
145 for row in cursor:
146 parent = row[0]
147 title = row[1]
148 placesId = row[2]
149
150 cursor2 = self.__db.cursor()
151 cursor2.execute(
152 "SELECT url FROM moz_places WHERE id = {0}"
153 .format(placesId))
154 row2 = cursor2.fetchone()
155 if row2:
156 url = QUrl(row2[0])
157 if not title or url.isEmpty() or \
158 url.scheme() in ["place", "about"]:
159 continue
160
161 if parent in folders:
162 bookmark = BookmarkNode(BookmarkNode.Bookmark,
163 folders[parent])
164 else:
165 bookmark = BookmarkNode(BookmarkNode.Bookmark,
166 importRootNode)
167 bookmark.url = url.toString()
168 bookmark.title = title.replace("&", "&&")
169 except sqlite3.DatabaseError as err:
170 self._error = True
171 self._errorString = self.tr(
172 "Unable to open database.\nReason: {0}").format(str(err))
173 return None
174
175 importRootNode.setType(BookmarkNode.Folder)
176 if self._id == "firefox":
177 importRootNode.title = self.tr("Mozilla Firefox Import")
178 else:
179 importRootNode.title = self.tr("Imported {0}")\
180 .format(QDate.currentDate().toString(Qt.SystemLocaleShortDate))
181 return importRootNode

eric ide

mercurial