WebBrowser/Sync/DirectorySyncHandler.py

branch
QtWebEngine
changeset 4774
2c6ffa778c3b
parent 4631
5c1a96925da4
child 4776
7f4c8e5f3385
equal deleted inserted replaced
4773:cad470dfd807 4774:2c6ffa778c3b
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2012 - 2016 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing a synchronization handler using a shared directory.
8 """
9
10 from __future__ import unicode_literals
11
12 import os
13
14 from PyQt5.QtCore import pyqtSignal, QByteArray, QFileInfo, QCoreApplication
15
16 from .SyncHandler import SyncHandler
17
18 from WebBrowser.WebBrowserWindow import WebBrowserWindow
19
20 import Preferences
21
22
23 class DirectorySyncHandler(SyncHandler):
24 """
25 Class implementing a synchronization handler using a shared directory.
26
27 @signal syncStatus(type_, message) emitted to indicate the synchronization
28 status (string one of "bookmarks", "history", "passwords",
29 "useragents" or "speeddial", string)
30 @signal syncError(message) emitted for a general error with the error
31 message (string)
32 @signal syncMessage(message) emitted to send a message about
33 synchronization (string)
34 @signal syncFinished(type_, done, download) emitted after a
35 synchronization has finished (string one of "bookmarks", "history",
36 "passwords", "useragents" or "speeddial", boolean, boolean)
37 """
38 syncStatus = pyqtSignal(str, str)
39 syncError = pyqtSignal(str)
40 syncMessage = pyqtSignal(str)
41 syncFinished = pyqtSignal(str, bool, bool)
42
43 def __init__(self, parent=None):
44 """
45 Constructor
46
47 @param parent reference to the parent object (QObject)
48 """
49 super(DirectorySyncHandler, self).__init__(parent)
50 self.__forceUpload = False
51
52 self.__remoteFilesFound = []
53
54 def initialLoadAndCheck(self, forceUpload):
55 """
56 Public method to do the initial check.
57
58 @keyparam forceUpload flag indicating a forced upload of the files
59 (boolean)
60 """
61 if not Preferences.getWebBrowser("SyncEnabled"):
62 return
63
64 self.__forceUpload = forceUpload
65
66 self.__remoteFilesFound = []
67
68 # check the existence of the shared directory; create it, if it is
69 # not there
70 if not os.path.exists(Preferences.getWebBrowser("SyncDirectoryPath")):
71 try:
72 os.makedirs(Preferences.getWebBrowser("SyncDirectoryPath"))
73 except OSError as err:
74 self.syncError.emit(
75 self.tr("Error creating the shared directory.\n{0}")
76 .format(str(err)))
77 return
78
79 self.__initialSync()
80
81 def __downloadFile(self, type_, fileName, timestamp):
82 """
83 Private method to downlaod the given file.
84
85 @param type_ type of the synchronization event (string one
86 of "bookmarks", "history", "passwords", "useragents" or
87 "speeddial")
88 @param fileName name of the file to be downloaded (string)
89 @param timestamp time stamp in seconds of the file to be downloaded
90 (integer)
91 """
92 self.syncStatus.emit(type_, self._messages[type_]["RemoteExists"])
93 try:
94 f = open(os.path.join(
95 Preferences.getWebBrowser("SyncDirectoryPath"),
96 self._remoteFiles[type_]), "rb")
97 data = f.read()
98 f.close()
99 except IOError as err:
100 self.syncStatus.emit(
101 type_,
102 self.tr("Cannot read remote file.\n{0}").format(str(err)))
103 self.syncFinished.emit(type_, False, True)
104 return
105
106 QCoreApplication.processEvents()
107 ok, error = self.writeFile(QByteArray(data), fileName, type_,
108 timestamp)
109 if not ok:
110 self.syncStatus.emit(type_, error)
111 self.syncFinished.emit(type_, ok, True)
112
113 def __uploadFile(self, type_, fileName):
114 """
115 Private method to upload the given file.
116
117 @param type_ type of the synchronization event (string one
118 of "bookmarks", "history", "passwords", "useragents" or
119 "speeddial")
120 @param fileName name of the file to be uploaded (string)
121 """
122 QCoreApplication.processEvents()
123 data = self.readFile(fileName, type_)
124 if data.isEmpty():
125 self.syncStatus.emit(type_, self._messages[type_]["LocalMissing"])
126 self.syncFinished.emit(type_, False, False)
127 return
128 else:
129 try:
130 f = open(os.path.join(
131 Preferences.getWebBrowser("SyncDirectoryPath"),
132 self._remoteFiles[type_]), "wb")
133 f.write(bytes(data))
134 f.close()
135 except IOError as err:
136 self.syncStatus.emit(
137 type_,
138 self.tr("Cannot write remote file.\n{0}").format(
139 str(err)))
140 self.syncFinished.emit(type_, False, False)
141 return
142
143 self.syncFinished.emit(type_, True, False)
144
145 def __initialSyncFile(self, type_, fileName):
146 """
147 Private method to do the initial synchronization of the given file.
148
149 @param type_ type of the synchronization event (string one
150 of "bookmarks", "history", "passwords", "useragents" or
151 "speeddial")
152 @param fileName name of the file to be synchronized (string)
153 """
154 if not self.__forceUpload and \
155 os.path.exists(os.path.join(
156 Preferences.getWebBrowser("SyncDirectoryPath"),
157 self._remoteFiles[type_])) and \
158 QFileInfo(fileName).lastModified() <= QFileInfo(
159 os.path.join(
160 Preferences.getWebBrowser("SyncDirectoryPath"),
161 self._remoteFiles[type_])).lastModified():
162 self.__downloadFile(
163 type_, fileName,
164 QFileInfo(os.path.join(
165 Preferences.getWebBrowser("SyncDirectoryPath"),
166 self._remoteFiles[type_])).lastModified().toTime_t())
167 else:
168 if os.path.exists(os.path.join(
169 Preferences.getWebBrowser("SyncDirectoryPath"),
170 self._remoteFiles[type_])):
171 self.syncStatus.emit(
172 type_, self._messages[type_]["RemoteMissing"])
173 else:
174 self.syncStatus.emit(
175 type_, self._messages[type_]["LocalNewer"])
176 self.__uploadFile(type_, fileName)
177
178 def __initialSync(self):
179 """
180 Private slot to do the initial synchronization.
181 """
182 QCoreApplication.processEvents()
183 # Bookmarks
184 if Preferences.getWebBrowser("SyncBookmarks"):
185 self.__initialSyncFile(
186 "bookmarks",
187 WebBrowserWindow.bookmarksManager().getFileName())
188
189 QCoreApplication.processEvents()
190 # History
191 if Preferences.getWebBrowser("SyncHistory"):
192 self.__initialSyncFile(
193 "history",
194 WebBrowserWindow.historyManager().getFileName())
195
196 QCoreApplication.processEvents()
197 # Passwords
198 if Preferences.getWebBrowser("SyncPasswords"):
199 self.__initialSyncFile(
200 "passwords",
201 WebBrowserWindow.passwordManager().getFileName())
202
203 # TODO: UserAgents
204 ## QCoreApplication.processEvents()
205 ## # User Agent Settings
206 ## if Preferences.getWebBrowser("SyncUserAgents"):
207 ## self.__initialSyncFile(
208 ## "useragents",
209 ## WebBrowserWindow.userAgentsManager().getFileName())
210
211 # TODO: SpeedDial
212 ## QCoreApplication.processEvents()
213 ## # Speed Dial Settings
214 ## if Preferences.getWebBrowser("SyncSpeedDial"):
215 ## self.__initialSyncFile(
216 ## "speeddial",
217 ## WebBrowserWindow.speedDial().getFileName())
218
219 self.__forceUpload = False
220 self.syncMessage.emit(self.tr("Synchronization finished"))
221
222 def __syncFile(self, type_, fileName):
223 """
224 Private method to synchronize the given file.
225
226 @param type_ type of the synchronization event (string one
227 of "bookmarks", "history", "passwords", "useragents" or
228 "speeddial")
229 @param fileName name of the file to be synchronized (string)
230 """
231 self.syncStatus.emit(type_, self._messages[type_]["Uploading"])
232 self.__uploadFile(type_, fileName)
233
234 def syncBookmarks(self):
235 """
236 Public method to synchronize the bookmarks.
237 """
238 self.__syncFile(
239 "bookmarks",
240 WebBrowserWindow.bookmarksManager().getFileName())
241
242 def syncHistory(self):
243 """
244 Public method to synchronize the history.
245 """
246 self.__syncFile(
247 "history",
248 WebBrowserWindow.historyManager().getFileName())
249
250 def syncPasswords(self):
251 """
252 Public method to synchronize the passwords.
253 """
254 self.__syncFile(
255 "passwords",
256 WebBrowserWindow.passwordManager().getFileName())
257
258 # TODO: UserAgents
259 def syncUserAgents(self):
260 """
261 Public method to synchronize the user agents.
262 """
263 ## self.__syncFile(
264 ## "useragents",
265 ## WebBrowserWindow.userAgentsManager().getFileName())
266
267 # TODO: SpeedDial
268 def syncSpeedDial(self):
269 """
270 Public method to synchronize the speed dial data.
271 """
272 ## self.__syncFile(
273 ## "speeddial",
274 ## WebBrowserWindow.speedDial().getFileName())
275
276 def shutdown(self):
277 """
278 Public method to shut down the handler.
279 """
280 # nothing to do
281 return

eric ide

mercurial