OSDN Git Service

4709e6d015b2662f49df7aeea97fdac49d1b00fe
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / threads / SyncRunner.java
1 /*\r
2  * This file is part of NixNote \r
3  * Copyright 2009 Randy Baumgarte\r
4  * \r
5  * This file may be licensed under the terms of of the\r
6  * GNU General Public License Version 2 (the ``GPL'').\r
7  *\r
8  * Software distributed under the License is distributed\r
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\r
10  * express or implied. See the GPL for the specific language\r
11  * governing rights and limitations.\r
12  *\r
13  * You should have received a copy of the GPL along with this\r
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html\r
15  * or write to the Free Software Foundation, Inc.,\r
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
17  *\r
18 */\r
19 package cx.fbn.nevernote.threads;\r
20 \r
21 import java.io.BufferedOutputStream;\r
22 import java.io.File;\r
23 import java.io.FileOutputStream;\r
24 import java.io.IOException;\r
25 import java.io.InputStream;\r
26 import java.io.UnsupportedEncodingException;\r
27 import java.net.UnknownHostException;\r
28 import java.util.ArrayList;\r
29 import java.util.Calendar;\r
30 import java.util.Date;\r
31 import java.util.GregorianCalendar;\r
32 import java.util.HashMap;\r
33 import java.util.List;\r
34 import java.util.TreeSet;\r
35 import java.util.Vector;\r
36 import java.util.concurrent.LinkedBlockingQueue;\r
37 \r
38 import org.apache.http.HttpEntity;\r
39 import org.apache.http.HttpResponse;\r
40 import org.apache.http.NameValuePair;\r
41 import org.apache.http.client.ClientProtocolException;\r
42 import org.apache.http.client.HttpClient;\r
43 import org.apache.http.client.entity.UrlEncodedFormEntity;\r
44 import org.apache.http.client.methods.HttpPost;\r
45 import org.apache.http.impl.client.DefaultHttpClient;\r
46 import org.apache.http.message.BasicNameValuePair;\r
47 import org.apache.http.protocol.HTTP;\r
48 import org.apache.thrift.TException;\r
49 import org.apache.thrift.protocol.TBinaryProtocol;\r
50 import org.apache.thrift.transport.THttpClient;\r
51 import org.apache.thrift.transport.TTransportException;\r
52 \r
53 import com.evernote.edam.error.EDAMNotFoundException;\r
54 import com.evernote.edam.error.EDAMSystemException;\r
55 import com.evernote.edam.error.EDAMUserException;\r
56 import com.evernote.edam.notestore.NoteStore;\r
57 import com.evernote.edam.notestore.NoteStore.Client;\r
58 import com.evernote.edam.notestore.SyncChunk;\r
59 import com.evernote.edam.notestore.SyncState;\r
60 import com.evernote.edam.type.Data;\r
61 import com.evernote.edam.type.LinkedNotebook;\r
62 import com.evernote.edam.type.Note;\r
63 import com.evernote.edam.type.Notebook;\r
64 import com.evernote.edam.type.Resource;\r
65 import com.evernote.edam.type.SavedSearch;\r
66 import com.evernote.edam.type.SharedNotebook;\r
67 import com.evernote.edam.type.Tag;\r
68 import com.evernote.edam.type.User;\r
69 import com.evernote.edam.userstore.AuthenticationResult;\r
70 import com.evernote.edam.userstore.UserStore;\r
71 import com.trolltech.qt.core.QByteArray;\r
72 import com.trolltech.qt.core.QFile;\r
73 import com.trolltech.qt.core.QIODevice.OpenModeFlag;\r
74 import com.trolltech.qt.core.QObject;\r
75 import com.trolltech.qt.core.QTextCodec;\r
76 import com.trolltech.qt.gui.QMessageBox;\r
77 \r
78 import cx.fbn.nevernote.signals.NoteIndexSignal;\r
79 import cx.fbn.nevernote.signals.NoteResourceSignal;\r
80 import cx.fbn.nevernote.signals.NoteSignal;\r
81 import cx.fbn.nevernote.signals.NotebookSignal;\r
82 import cx.fbn.nevernote.signals.SavedSearchSignal;\r
83 import cx.fbn.nevernote.signals.StatusSignal;\r
84 import cx.fbn.nevernote.signals.SyncSignal;\r
85 import cx.fbn.nevernote.signals.TagSignal;\r
86 import cx.fbn.nevernote.sql.DatabaseConnection;\r
87 import cx.fbn.nevernote.sql.DeletedItemRecord;\r
88 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
89 \r
90 public class SyncRunner extends QObject implements Runnable {\r
91         \r
92         private final ApplicationLogger logger;\r
93                 private DatabaseConnection              conn;\r
94                 private boolean                                 idle;\r
95                 public boolean                                  error;\r
96                 public volatile Vector<String>  errorSharedNotebooks;\r
97                 public volatile HashMap<String,String>  errorSharedNotebooksIgnored;\r
98                 public volatile boolean                 isConnected;\r
99                 public volatile boolean                 keepRunning;\r
100                 public volatile String                  authToken;\r
101                 private long                                    evernoteUpdateCount;\r
102                 private final String userAgent = "NixNote/" + System.getProperty("os.name")\r
103                                                                 +"/"+System.getProperty("java.vendor") + "/"\r
104                                                                 + System.getProperty("java.version") +";";\r
105                 \r
106                 public volatile NoteStore.Client                localNoteStore;\r
107                 private UserStore.Client                                userStore;\r
108                 \r
109                 public volatile StatusSignal                    status;\r
110                 public volatile TagSignal                               tagSignal;\r
111                 public volatile NotebookSignal                  notebookSignal;\r
112                 public volatile NoteIndexSignal                 noteIndexSignal;\r
113                 public volatile NoteSignal                              noteSignal;\r
114                 public volatile SavedSearchSignal               searchSignal;\r
115                 public volatile NoteResourceSignal              resourceSignal;\r
116                 public volatile SyncSignal                              syncSignal;\r
117                 public volatile boolean                                 authRefreshNeeded;\r
118                 public volatile boolean                                 syncNeeded;\r
119                 public volatile boolean                                 disableUploads;\r
120                 public volatile boolean                                 syncDeletedContent;\r
121                 private volatile Vector<String>                 dirtyNoteGuids;\r
122                 \r
123             public volatile String username = ""; \r
124             public volatile String password = ""; \r
125                 public volatile String userStoreUrl;\r
126 //          private final static String consumerKey = "baumgarte"; \r
127 //          private final static String consumerSecret = "eb8b5740e17cb55f";\r
128             public String noteStoreUrlBase;\r
129             private THttpClient userStoreTrans;\r
130             private TBinaryProtocol userStoreProt;\r
131             //private AuthenticationResult authResult;\r
132             private AuthenticationResult linkedAuthResult;\r
133             private User user; \r
134 //          private long authTimeRemaining;\r
135             public long authRefreshTime;\r
136             public long failedRefreshes = 0;\r
137             public  THttpClient noteStoreTrans;\r
138             public TBinaryProtocol noteStoreProt;\r
139             public String noteStoreUrl;\r
140             public long sequenceDate;\r
141             public int updateSequenceNumber;\r
142             private boolean refreshNeeded;\r
143             private volatile LinkedBlockingQueue<String> workQueue;\r
144                 private static int MAX_QUEUED_WAITING = 1000;\r
145                 String dbuid;\r
146                 String dburl;\r
147                 String indexUrl;\r
148                 String resourceUrl;\r
149                 String dbpswd;\r
150                 String dbcpswd;\r
151                 private final TreeSet<String> ignoreTags;\r
152                 private final TreeSet<String> ignoreNotebooks;\r
153                 private final TreeSet<String> ignoreLinkedNotebooks;\r
154                 private HashMap<String,String> badTagSync;\r
155         \r
156                 \r
157                 \r
158         public SyncRunner(String logname, String u, String i, String r, String uid, String pswd, String cpswd) {\r
159                 logger = new ApplicationLogger(logname);\r
160                 \r
161                 noteSignal = new NoteSignal();\r
162                 status = new StatusSignal();\r
163                 tagSignal = new TagSignal();\r
164                 notebookSignal = new NotebookSignal();\r
165                 noteIndexSignal = new NoteIndexSignal();\r
166                 noteSignal = new NoteSignal();\r
167                 searchSignal = new SavedSearchSignal();\r
168                 syncSignal = new SyncSignal();\r
169                 resourceSignal = new NoteResourceSignal();\r
170                 resourceUrl = r;\r
171                 indexUrl = i;\r
172                 dbuid = uid;\r
173                 dburl = u;\r
174                 dbpswd = pswd;\r
175                 dbcpswd = cpswd;\r
176 //              this.setAutoDelete(false);\r
177                 \r
178                 isConnected = false;\r
179                 syncNeeded = false;\r
180                 authRefreshNeeded = false;\r
181                 keepRunning = true;\r
182                 idle = true;\r
183                 disableUploads = false;\r
184                 ignoreTags = new TreeSet<String>();\r
185                 ignoreNotebooks = new TreeSet<String>();\r
186                 ignoreLinkedNotebooks = new TreeSet<String>();\r
187                 \r
188 //              setAutoDelete(false);\r
189                 workQueue=new LinkedBlockingQueue<String>(MAX_QUEUED_WAITING);\r
190         }\r
191         @Override\r
192         public void run() {\r
193                 errorSharedNotebooks = new Vector<String>();\r
194                 errorSharedNotebooksIgnored = new HashMap<String,String>();\r
195                 try {\r
196                         logger.log(logger.EXTREME, "Starting thread");\r
197                         conn = new DatabaseConnection(logger, dburl, indexUrl, resourceUrl, dbuid, dbpswd, dbcpswd, 200);\r
198                         while(keepRunning) {\r
199                                 logger.log(logger.EXTREME, "Blocking until work is found");\r
200                                 String work = workQueue.take();\r
201                                 logger.log(logger.EXTREME, "Work found: " +work);\r
202                                 if (work.equalsIgnoreCase("stop")) {\r
203                                         idle=false;\r
204                                         return;\r
205                                 }\r
206                                 idle=false;\r
207                                 error=false;\r
208                                 if (syncNeeded) {\r
209                                         logger.log(logger.EXTREME, "SyncNeeded is true");\r
210                                         refreshNeeded=false;\r
211                                         sequenceDate = conn.getSyncTable().getLastSequenceDate();\r
212                                         updateSequenceNumber = conn.getSyncTable().getUpdateSequenceNumber();\r
213                                         try {\r
214                                                 logger.log(logger.EXTREME, "Beginning sync");\r
215                                                 evernoteSync(localNoteStore);\r
216                                                 logger.log(logger.EXTREME, "Sync finished");\r
217                                         } catch (UnknownHostException e) {\r
218                                                 status.message.emit(e.getMessage());\r
219                                         }\r
220                                 }\r
221                                 idle=true;\r
222                                 logger.log(logger.EXTREME, "Signaling refresh finished.  refreshNeeded=" +refreshNeeded);\r
223                                 syncSignal.finished.emit(refreshNeeded);\r
224                                 if (error) {\r
225                                         syncSignal.errorDisconnect.emit();\r
226                                         status.message.emit(tr("Error synchronizing - see log for details."));\r
227                                 }\r
228                         }\r
229                 }       \r
230                 catch (InterruptedException e1) {\r
231                         e1.printStackTrace();\r
232                 }\r
233                 conn.dbShutdown();\r
234         }\r
235 \r
236         \r
237         public DatabaseConnection getConnection() {\r
238                 return conn;\r
239         }\r
240 \r
241         public boolean isIdle() {\r
242                 return idle;\r
243         }\r
244 \r
245 \r
246         public void setConnected(boolean c) {\r
247                 isConnected = c;\r
248         }\r
249         public void setKeepRunning(boolean r) {\r
250                 logger.log(logger.EXTREME, "Setting keepRunning=" +r);\r
251                 keepRunning = r;\r
252         }\r
253         public void setNoteStore(NoteStore.Client c) {\r
254                 logger.log(logger.EXTREME, "Setting NoteStore in sync thread");\r
255                 localNoteStore = c;\r
256         }\r
257         public void setUserStore(UserStore.Client c) {\r
258                 logger.log(logger.EXTREME, "Setting UserStore in sync thread");\r
259                 userStore = c;\r
260         }\r
261 \r
262         public void setEvernoteUpdateCount(long s) {\r
263                 logger.log(logger.EXTREME, "Setting Update Count in sync thread");\r
264                 evernoteUpdateCount = s;\r
265         }\r
266         \r
267         //***************************************************************\r
268     //***************************************************************\r
269     //** These functions deal with Evernote communications\r
270     //***************************************************************\r
271     //***************************************************************\r
272         // Synchronize changes with Evernote\r
273         @SuppressWarnings("unused")\r
274         private void evernoteSync(Client noteStore) throws java.net.UnknownHostException {\r
275                 logger.log(logger.HIGH, "Entering SyncRunner.evernoteSync");\r
276                 \r
277                 // Rebuild list of tags & notebooks to ignore\r
278                 ignoreNotebooks.clear();\r
279                 List<String> ignore = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");\r
280                 for (int i=0; i<ignore.size(); i++) \r
281                         ignoreNotebooks.add(ignore.get(i));\r
282                 \r
283                 ignore.clear();\r
284                 ignore = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");\r
285                 for (int i=0; i<ignore.size(); i++) \r
286                         ignoreLinkedNotebooks.add(ignore.get(i));\r
287                 \r
288                 ignoreTags.clear();\r
289                 ignore = conn.getSyncTable().getIgnoreRecords("TAG");\r
290                 for (int i=0; i<ignore.size(); i++) \r
291                         ignoreTags.add(ignore.get(i));\r
292 \r
293                 // Make sure we are connected & should keep running\r
294                 if (isConnected && keepRunning) {\r
295                         error = false;\r
296                         logger.log(logger.EXTREME, "Synchronizing with Evernote");\r
297                         status.message.emit(tr("Synchronizing with Evernote"));\r
298                         \r
299                         // Get user information\r
300                         try {\r
301                                 logger.log(logger.EXTREME, "getting user from userstore");\r
302                                 User user = userStore.getUser(authToken);\r
303                                 logger.log(logger.EXTREME, "Saving user information");\r
304                                 syncSignal.saveUserInformation.emit(user);\r
305                         } catch (EDAMUserException e1) {\r
306                                 e1.printStackTrace();\r
307                                 status.message.emit(tr("User exception getting user account information.  Aborting sync and disconnecting"));\r
308                                 syncSignal.errorDisconnect.emit();\r
309                                 error = true;\r
310                                 enDisconnect();\r
311                                 return;\r
312                         } catch (EDAMSystemException e1) {\r
313                                 e1.printStackTrace();\r
314                                 status.message.emit(tr("System error user account information.  Aborting sync and disconnecting!"));\r
315                                 syncSignal.errorDisconnect.emit();\r
316                                 error = true;\r
317                                 enDisconnect();\r
318                                 return;\r
319                         } catch (TException e1) {\r
320                                 e1.printStackTrace();\r
321                                 syncSignal.errorDisconnect.emit();\r
322                                 error = true;\r
323                                 status.message.emit(tr("Transaction error getting user account information.  Aborting sync and disconnecting!"));\r
324                                 enDisconnect();\r
325                                 return;\r
326                         }\r
327                         \r
328                         // Get sync state\r
329                         SyncState syncState = null;\r
330                         try {   \r
331                                 logger.log(logger.EXTREME, "Getting sync state");\r
332                                 syncState = noteStore.getSyncState(authToken);  \r
333                                 syncSignal.saveUploadAmount.emit(syncState.getUploaded());\r
334                                 syncSignal.saveEvernoteUpdateCount.emit(syncState.getUpdateCount());\r
335                                 evernoteUpdateCount = syncState.getUpdateCount();\r
336                         } catch (EDAMUserException e) {\r
337                                 e.printStackTrace();\r
338                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
339                                 syncSignal.errorDisconnect.emit();\r
340                                 enDisconnect();\r
341                                 return;\r
342                         } catch (EDAMSystemException e) {\r
343                                 e.printStackTrace();\r
344                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
345                                 syncSignal.errorDisconnect.emit();\r
346                                 enDisconnect();\r
347                                 return;\r
348                         } catch (TException e) {\r
349                                 e.printStackTrace();\r
350                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
351                                 syncSignal.errorDisconnect.emit();\r
352                                 enDisconnect();\r
353                                 return;\r
354                         }\r
355                         \r
356                         if (syncState == null) {\r
357                                 logger.log(logger.EXTREME, "Sync State is null");\r
358                                 status.message.emit(tr("Syncronization Error!"));\r
359                                 return;\r
360                         }\r
361 \r
362                         // Determine what to do. \r
363                         // If we need to do a full sync.\r
364                         logger.log(logger.LOW, "Full Sequence Before: " +syncState.getFullSyncBefore());\r
365                         logger.log(logger.LOW, "Last Sequence Date: " +sequenceDate);\r
366                         logger.log(logger.LOW, "Var Last Sequence Number: " +updateSequenceNumber);\r
367                         logger.log(logger.LOW, "DB Last Sequence Number: " + conn.getSyncTable().getUpdateSequenceNumber());\r
368                         if (syncState.getFullSyncBefore() > sequenceDate) {\r
369                                 logger.log(logger.EXTREME, "Full sequence date has expired");\r
370                                 sequenceDate = 0;\r
371                                 conn.getSyncTable().setLastSequenceDate(0);\r
372                                 updateSequenceNumber = 0;\r
373                                 conn.getSyncTable().setUpdateSequenceNumber(0);\r
374                         }\r
375                         // Check for "special" sync instructions\r
376                         String syncLinked = conn.getSyncTable().getRecord("FullLinkedNotebookSync");\r
377                         String syncShared = conn.getSyncTable().getRecord("FullSharedNotebookSync");\r
378                         String syncNotebooks = conn.getSyncTable().getRecord("FullNotebookSync");\r
379                         String syncInkNoteImages = conn.getSyncTable().getRecord("FullInkNoteImageSync");\r
380                         if (syncLinked != null) {\r
381                                 downloadAllLinkedNotebooks(localNoteStore);\r
382                         }\r
383                         if (syncShared != null) {\r
384                                 downloadAllSharedNotebooks(localNoteStore);\r
385                         }\r
386                         if (syncNotebooks != null) {\r
387                                 downloadAllNotebooks(localNoteStore);\r
388                         }\r
389                         \r
390                         if (syncInkNoteImages != null) {\r
391                                 List<String> guids = conn.getNoteTable().noteResourceTable.findInkNotes();\r
392                                 for (int i=0; i<guids.size(); i++) {\r
393                                         downloadInkNoteImage(guids.get(i), authToken);\r
394                                 }\r
395                                 conn.getSyncTable().deleteRecord("FullInkNoteImageSync");\r
396                         }\r
397                         \r
398                         // If there are remote changes\r
399                         logger.log(logger.LOW, "Update Count: " +syncState.getUpdateCount());\r
400                         logger.log(logger.LOW, "Last Update Count: " +updateSequenceNumber);\r
401                         \r
402                         if (syncState.getUpdateCount() > updateSequenceNumber) {\r
403                                 logger.log(logger.EXTREME, "Refresh needed is true");\r
404                                 refreshNeeded = true;\r
405                                 logger.log(logger.EXTREME, "Downloading changes");\r
406                                 syncRemoteToLocal(localNoteStore);\r
407                         }\r
408                         \r
409                         //*****************************************\r
410                         //* Sync linked/shared notebooks \r
411                         //*****************************************\r
412                         syncLinkedNotebooks();\r
413                         \r
414                         if (!disableUploads) {\r
415                                 logger.log(logger.EXTREME, "Uploading changes");\r
416                                 // Synchronize remote changes\r
417                                 if (!error)\r
418                                         syncExpunged(localNoteStore);\r
419                                 if (!error)\r
420                                         syncLocalTags(localNoteStore);\r
421                                 if (!error)\r
422                                         syncLocalNotebooks(localNoteStore);\r
423                                 if (!error)\r
424                                         syncLocalLinkedNotebooks(localNoteStore);\r
425                                 if (!error) \r
426                                         syncDeletedNotes(localNoteStore);\r
427                                 if (!error)\r
428                                         syncLocalNotes();\r
429                                 if (!error)\r
430                                         syncLocalSavedSearches(localNoteStore);\r
431                         }\r
432                         \r
433                         status.message.emit(tr("Cleaning up"));\r
434                         List<String> notes = conn.getNoteTable().expungeIgnoreSynchronizedNotes(conn.getSyncTable().getIgnoreRecords("NOTEBOOK"), \r
435                                         conn.getSyncTable().getIgnoreRecords("TAG"), conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK"));\r
436                         if (notes.size() > 0)\r
437                                 syncSignal.refreshLists.emit();\r
438                         \r
439                         //*****************************************\r
440                         //* End of synchronization\r
441                         //*****************************************\r
442                         if (refreshNeeded)\r
443                                 syncSignal.refreshLists.emit();\r
444                         \r
445                         if (!error) {\r
446                                 logger.log(logger.LOW, "Sync completed.  Errors=" +error);\r
447                                 if (!disableUploads) \r
448                                         status.message.emit(tr("Synchronizing complete"));\r
449                                 else\r
450                                         status.message.emit(tr("Download syncronization complete.  Uploads have been disabled."));\r
451                                 \r
452                                 logger.log(logger.EXTREME, "Saving sync time");\r
453                                 if (syncState.getCurrentTime() > sequenceDate)\r
454                                         sequenceDate = syncState.getCurrentTime();\r
455                                 if (syncState.getUpdateCount() > updateSequenceNumber)\r
456                                         updateSequenceNumber = syncState.getUpdateCount();\r
457                                 conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
458                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
459                         }\r
460                 }\r
461                 logger.log(logger.HIGH, "Leaving SyncRunner.evernoteSync");\r
462         }\r
463         \r
464         // Sync deleted items with Evernote\r
465         private void syncExpunged(Client noteStore) {\r
466                 logger.log(logger.HIGH, "Entering SyncRunner.syncExpunged");\r
467                 \r
468                 List<DeletedItemRecord> expunged = conn.getDeletedTable().getAllDeleted();\r
469                 boolean error = false;\r
470                 for (int i=0; i<expunged.size() && keepRunning; i++) {\r
471 \r
472 //                      if (authRefreshNeeded)\r
473 //                              if (!refreshConnection())\r
474 //                                      return;\r
475 \r
476                         try {\r
477                                 if (expunged.get(i).type.equalsIgnoreCase("TAG")) {\r
478                                         logger.log(logger.EXTREME, "Tag expunged");\r
479                                         updateSequenceNumber = noteStore.expungeTag(authToken, expunged.get(i).guid);\r
480                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
481                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
482                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
483                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "TAG");                                 \r
484                                 }\r
485                                 if      (expunged.get(i).type.equalsIgnoreCase("NOTEBOOK")) {\r
486                                         logger.log(logger.EXTREME, "Notebook expunged");\r
487                                         updateSequenceNumber = noteStore.expungeNotebook(authToken, expunged.get(i).guid);\r
488                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
489                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
490                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "NOTEBOOK");\r
491                                 }\r
492                                 if (expunged.get(i).type.equalsIgnoreCase("NOTE")) {\r
493                                         logger.log(logger.EXTREME, "Note expunged");\r
494                                         updateSequenceNumber = noteStore.deleteNote(authToken, expunged.get(i).guid);\r
495                                         refreshNeeded = true;\r
496                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
497                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
498                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "NOTE");\r
499                                 }\r
500                                 if (expunged.get(i).type.equalsIgnoreCase("SAVEDSEARCH")) {\r
501                                         logger.log(logger.EXTREME, "saved search expunged");\r
502                                         updateSequenceNumber = noteStore.expungeSearch(authToken, expunged.get(i).guid);\r
503                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
504                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
505                                         conn.getDeletedTable().expungeDeletedItem(expunged.get(i).guid, "SAVEDSEARCH");\r
506                                 }\r
507                         } catch (EDAMUserException e) {\r
508                                 logger.log(logger.LOW, "EDAM User Excepton in syncExpunged: " +expunged.get(i).guid);   // This can happen if we try to delete a deleted note\r
509                         } catch (EDAMSystemException e) {\r
510                                 logger.log(logger.LOW, "EDAM System Excepton in syncExpunged: "+expunged.get(i).guid);\r
511                                 logger.log(logger.LOW, e.getStackTrace());\r
512                                 error=true;\r
513                         } catch (EDAMNotFoundException e) {\r
514                                 logger.log(logger.LOW, "EDAM Not Found Excepton in syncExpunged: "+expunged.get(i).guid);\r
515                         } catch (TException e) {\r
516                                 logger.log(logger.LOW, "EDAM TExcepton in syncExpunged: "+expunged.get(i).guid);\r
517                                 logger.log(logger.LOW, e.getStackTrace());\r
518                                 error=true;\r
519                         }\r
520                 }\r
521                 if (!error)\r
522                         conn.getDeletedTable().expungeAllDeletedRecords();\r
523                 \r
524                 logger.log(logger.HIGH, "Leaving SyncRunner.syncExpunged");\r
525 \r
526         }\r
527         private void syncDeletedNotes(Client noteStore) {\r
528                 if (syncDeletedContent)\r
529                         return;\r
530                 logger.log(logger.HIGH, "Entering SyncRunner.syncDeletedNotes");\r
531                 status.message.emit(tr("Synchronizing deleted notes."));\r
532 \r
533                 List<Note> notes = conn.getNoteTable().getDirty();\r
534                 // Sync the local notebooks with Evernote's\r
535                 for (int i=0; i<notes.size() && keepRunning; i++) {\r
536                         \r
537 //                      if (authRefreshNeeded)\r
538 //                              if (!refreshConnection())\r
539 //                                      return;\r
540                         \r
541                         Note enNote = notes.get(i);\r
542                         try {\r
543                                 if (enNote.getUpdateSequenceNum() > 0 && (enNote.isActive() == false || enNote.getDeleted() > 0)) {\r
544                                         if (syncDeletedContent) {\r
545                                                 logger.log(logger.EXTREME, "Deleted note found & synch content selected");\r
546                                                 Note delNote = conn.getNoteTable().getNote(enNote.getGuid(), true, true, true, true, true);\r
547                                                 delNote = getNoteContent(delNote);\r
548                                                 delNote = noteStore.updateNote(authToken, delNote);\r
549                                                 enNote.setUpdateSequenceNum(delNote.getUpdateSequenceNum());\r
550                                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());\r
551                                         } else {\r
552                                                 logger.log(logger.EXTREME, "Deleted note found & sync content not selected");\r
553                                                 int usn = noteStore.deleteNote(authToken, enNote.getGuid());\r
554                                                 enNote.setUpdateSequenceNum(usn);\r
555                                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());                                                \r
556                                         }\r
557                                         logger.log(logger.EXTREME, "Resetting deleted dirty flag");\r
558                                         conn.getNoteTable().resetDirtyFlag(enNote.getGuid());\r
559                                         updateSequenceNumber = enNote.getUpdateSequenceNum();\r
560                                         logger.log(logger.EXTREME, "Saving sequence number");\r
561                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
562                                 }                               \r
563                         } catch (EDAMUserException e) {\r
564                                 //logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotes "+e);\r
565                                 //status.message.emit("Error sending local note: " +e.getParameter());\r
566                                 //logger.log(logger.LOW, e.toString()); \r
567                                 //error = true;\r
568                         } catch (EDAMSystemException e) {\r
569                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotes "+e);\r
570                                 status.message.emit(tr("Error: ") +e);\r
571                                 logger.log(logger.LOW, e.toString());           \r
572                                 error = true;\r
573                         } catch (EDAMNotFoundException e) {\r
574                                 //logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotes " +e);\r
575                                 //status.message.emit("Error deleting local note: " +e +" - Continuing");\r
576                                 //logger.log(logger.LOW, e.toString());         \r
577                                 //error = true;\r
578                         } catch (TException e) {\r
579                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotes "+e);\r
580                                 status.message.emit(tr("Error sending local note: ") +e);\r
581                                 logger.log(logger.LOW, e.toString());   \r
582                                 error = true;\r
583                         }               \r
584                 }\r
585         }\r
586         // Sync notes with Evernote\r
587         private void syncLocalNotes() {\r
588                 logger.log(logger.HIGH, "Entering SyncRunner.syncNotes");\r
589                 status.message.emit(tr("Sending local notes."));\r
590 \r
591                 List<Note> notes = conn.getNoteTable().getDirty();\r
592                 // Sync the local notebooks with Evernote's\r
593                 for (int i=0; i<notes.size() && keepRunning; i++) {\r
594                         syncLocalNote(localNoteStore, notes.get(i), authToken);\r
595                 }\r
596                 logger.log(logger.HIGH, "Leaving SyncRunner.syncNotes");\r
597 \r
598         }\r
599         // Sync notes with Evernote\r
600         private void syncLocalNote(Client noteStore, Note enNote, String token) {\r
601                 logger.log(logger.HIGH, "Entering SyncRunner.syncNotes");\r
602                 status.message.emit(tr("Sending local notes."));\r
603                         \r
604                 if (enNote.isActive()) {\r
605                         try {\r
606                                 if (enNote.getUpdateSequenceNum() > 0) {\r
607                                         logger.log(logger.EXTREME, "Active dirty note found - non new - " +enNote.getGuid());\r
608                                         logger.log(logger.EXTREME, "Fetching note content");\r
609                                         enNote = getNoteContent(enNote);\r
610                                         logger.log(logger.MEDIUM, "Updating note : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
611                                         enNote = noteStore.updateNote(token, enNote);\r
612                                 } else { \r
613                                         logger.log(logger.EXTREME, "Active dirty found - new note " +enNote.getGuid());\r
614                                         String oldGuid = enNote.getGuid();\r
615                                         logger.log(logger.MEDIUM, "Fetching note content");\r
616                                         enNote = getNoteContent(enNote);\r
617                                         logger.log(logger.MEDIUM, "Creating note : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
618                                         enNote = noteStore.createNote(token, enNote);\r
619                                         logger.log(logger.MEDIUM, "New note Guid : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
620                                         noteSignal.guidChanged.emit(oldGuid, enNote.getGuid());\r
621                                         conn.getNoteTable().updateNoteGuid(oldGuid, enNote.getGuid());\r
622                                 }\r
623                                 updateSequenceNumber = enNote.getUpdateSequenceNum();\r
624                                 logger.log(logger.EXTREME, "Saving note");\r
625                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());\r
626                                 List<Resource> rl = enNote.getResources();\r
627                                 logger.log(logger.EXTREME, "Getting note resources");\r
628                                 for (int j=0; j<enNote.getResourcesSize() && keepRunning; j++) {\r
629                                         Resource newRes = rl.get(j);\r
630                                         Data d = newRes.getData();\r
631                                         if (d!=null) {  \r
632                                                 logger.log(logger.EXTREME, "Calculating resource hash");\r
633                                                 String hash = byteArrayToHexString(d.getBodyHash());\r
634                                                 logger.log(logger.EXTREME, "updating resources by hash");\r
635                                                 String oldGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(enNote.getGuid(), hash);\r
636                                                 conn.getNoteTable().updateNoteResourceGuidbyHash(enNote.getGuid(), newRes.getGuid(), hash);\r
637                                                 resourceSignal.resourceGuidChanged.emit(enNote.getGuid(), oldGuid, newRes.getGuid());\r
638                                         }\r
639                                 }\r
640                                 logger.log(logger.EXTREME, "Resetting note dirty flag");\r
641                                 conn.getNoteTable().resetDirtyFlag(enNote.getGuid());\r
642                                 updateSequenceNumber = enNote.getUpdateSequenceNum();\r
643                                 logger.log(logger.EXTREME, "Emitting note sequence number change");\r
644                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
645 \r
646                         } catch (EDAMUserException e) {\r
647                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotes "+e);\r
648                                 status.message.emit(tr("Error sending local note: ")     +e.getParameter());\r
649                                 logger.log(logger.LOW, e.toString());   \r
650                                 error = true;\r
651                         } catch (EDAMSystemException e) {\r
652                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotes "+e);\r
653                                 status.message.emit(tr("Error: ") +e);\r
654                                 logger.log(logger.LOW, e.toString());           \r
655                                 error = true;\r
656                         } catch (EDAMNotFoundException e) {\r
657                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotes " +e);\r
658                                 status.message.emit(tr("Error sending local note: ") +e);\r
659                                 logger.log(logger.LOW, e.toString());   \r
660                                 error = true;\r
661                         } catch (TException e) {\r
662                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotes "+e);\r
663                                 status.message.emit(tr("Error sending local note: ") +e);\r
664                                 logger.log(logger.LOW, e.toString());   \r
665                                 error = true;\r
666                         }\r
667                 }\r
668                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalNote");\r
669 \r
670         }\r
671 \r
672         // Sync Notebooks with Evernote\r
673         private void syncLocalNotebooks(Client noteStore) {\r
674                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalNotebooks");\r
675                 \r
676                 status.message.emit(tr("Sending local notebooks."));\r
677                 List<Notebook> remoteList = new ArrayList<Notebook>();\r
678                 try {\r
679                         logger.log(logger.EXTREME, "Getting remote notebooks to compare with local");\r
680                         remoteList = noteStore.listNotebooks(authToken);\r
681                 } catch (EDAMUserException e1) {\r
682                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotebooks getting remote Notebook List");\r
683                         status.message.emit(tr("Error: ") +e1);\r
684                         logger.log(logger.LOW, e1.toString());          \r
685                         error = true;\r
686                 } catch (EDAMSystemException e1) {\r
687                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotebooks getting remote Notebook List");\r
688                         status.message.emit(tr("Error: ") +e1);\r
689                         logger.log(logger.LOW, e1.toString());  \r
690                         error = true;\r
691                 } catch (TException e1) {\r
692                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalNotebooks getting remote Notebook List");\r
693                         status.message.emit(tr("Error: ") +e1);\r
694                         logger.log(logger.LOW, e1.toString());  \r
695                         error = true;\r
696                 }\r
697                 logger.log(logger.EXTREME, "Getting local dirty notebooks");\r
698                 List<Notebook> notebooks = conn.getNotebookTable().getDirty();\r
699                 int sequence;\r
700                 // Sync the local notebooks with Evernote's\r
701                 for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
702                         \r
703 //                      if (authRefreshNeeded)\r
704 //                              if (!refreshConnection())\r
705 //                                      return;\r
706                         \r
707                         Notebook enNotebook = notebooks.get(i);\r
708                         try {\r
709                                 if (enNotebook.getUpdateSequenceNum() > 0) {\r
710                                         logger.log(logger.EXTREME, "Existing notebook is dirty");\r
711                                         sequence = noteStore.updateNotebook(authToken, enNotebook);\r
712                                 } else {\r
713                                         logger.log(logger.EXTREME, "New dirty notebook found");\r
714                                         String oldGuid = enNotebook.getGuid();\r
715                                         boolean found = false;\r
716                                         \r
717                                         // Look for a notebook with the same name.  If one is found, we don't need \r
718                                         // to create another one\r
719                                         logger.log(logger.EXTREME, "Looking for matching notebook name");\r
720                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
721                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enNotebook.getName())) {\r
722                                                         enNotebook = remoteList.get(k);\r
723                                                         logger.log(logger.EXTREME, "Matching notebook found");\r
724                                                         found = true;\r
725                                                 }\r
726                                         }\r
727                                         if (!found)\r
728                                                 enNotebook = noteStore.createNotebook(authToken, enNotebook);\r
729                                         \r
730                                         logger.log(logger.EXTREME, "Updating notebook in database");\r
731                                         conn.getNotebookTable().updateNotebookGuid(oldGuid, enNotebook.getGuid());\r
732                                         sequence = enNotebook.getUpdateSequenceNum();\r
733                                 }\r
734                                 logger.log(logger.EXTREME, "Updating notebook sequence in database");\r
735                                 conn.getNotebookTable().updateNotebookSequence(enNotebook.getGuid(), sequence);\r
736                                 logger.log(logger.EXTREME, "Resetting dirty flag in notebook");\r
737                                 conn.getNotebookTable().resetDirtyFlag(enNotebook.getGuid());\r
738                                 updateSequenceNumber = sequence;\r
739                                 logger.log(logger.EXTREME, "Emitting sequence number to main thread");\r
740                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
741                         } catch (EDAMUserException e) {\r
742                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotebooks");\r
743                                 logger.log(logger.LOW, e.toString());   \r
744                                 error = true;\r
745                         } catch (EDAMSystemException e) {\r
746                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotebooks");\r
747                                 logger.log(logger.LOW, e.toString());           \r
748                                 error = true;\r
749                         } catch (EDAMNotFoundException e) {\r
750                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotebooks");\r
751                                 logger.log(logger.LOW, e.toString());           \r
752                                 error = true;\r
753                         } catch (TException e) {\r
754                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotebooks");\r
755                                 logger.log(logger.LOW, e.toString());   \r
756                                 error = true;\r
757                         }               \r
758                 }\r
759                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalNotebooks");\r
760 \r
761         }\r
762         // Sync Tags with Evernote\r
763         private void syncLocalTags(Client noteStore) {\r
764                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalTags");\r
765                 List<Tag> remoteList = new ArrayList<Tag>();\r
766                 status.message.emit(tr("Sending local tags."));\r
767                 \r
768                 try {\r
769                         logger.log(logger.EXTREME, "Getting remote tags to compare names with the local tags");\r
770                         remoteList = noteStore.listTags(authToken);\r
771                 } catch (EDAMUserException e1) {\r
772                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags getting remote Tag List");\r
773                         status.message.emit(tr("Error: ") +e1);\r
774                         logger.log(logger.LOW, e1.toString());  \r
775                         error = true;\r
776                 } catch (EDAMSystemException e1) {\r
777                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalTags getting remote Tag List");\r
778                         status.message.emit(tr("Error: ") +e1);\r
779                         logger.log(logger.LOW, e1.toString());          \r
780                         error = true;\r
781                 } catch (TException e1) {\r
782                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalTags getting remote Tag List");\r
783                         status.message.emit(tr("Error: ") +e1);\r
784                         logger.log(logger.LOW, e1.toString());  \r
785                         error = true;\r
786                 }               \r
787                 \r
788                 int sequence;\r
789                 \r
790                 if (badTagSync == null)\r
791                         badTagSync = new HashMap<String,String>();\r
792                 else\r
793                         badTagSync.clear();\r
794                 \r
795                 Tag enTag = findNextTag();\r
796                 \r
797                 // This is a hack.  Sometimes this function goes flookey and goes into a \r
798                 // perpetual loop.  This causes  NeverNote to flood Evernote's servers.\r
799                 // This is a safety valve to prevent unlimited loops.\r
800                 int maxCount = conn.getTagTable().getDirty().size()+10;\r
801                 int loopCount = 0;\r
802                 \r
803                 while(enTag!=null && loopCount < maxCount) {\r
804                         loopCount++;\r
805 //                      if (authRefreshNeeded)\r
806 //                              if (!refreshConnection())\r
807 //                                      return;\r
808 \r
809                         try {\r
810                                 if (enTag.getUpdateSequenceNum() > 0) {\r
811                                         logger.log(logger.EXTREME, "Updating tag");\r
812                                         sequence = noteStore.updateTag(authToken, enTag);\r
813                                 } else {\r
814                                         \r
815                                         // Look for a tag with the same name.  If one is found, we don't need \r
816                                         // to create another one\r
817                                         logger.log(logger.EXTREME, "New tag.  Comparing with remote names");\r
818                                         boolean found = false;\r
819                                         String oldGuid = enTag.getGuid();\r
820                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
821                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enTag.getName())) {\r
822                                                         conn.getTagTable().updateTagGuid(enTag.getGuid(), remoteList.get(k).getGuid());\r
823                                                         enTag = remoteList.get(k);\r
824                                                         logger.log(logger.EXTREME, "Matching tag name found");\r
825                                                         found = true;\r
826                                                 }\r
827                                         }\r
828                                         if (!found)\r
829                                                 enTag = noteStore.createTag(authToken, enTag);\r
830                                         else\r
831                                                 enTag.setUpdateSequenceNum(noteStore.updateTag(authToken,enTag));\r
832                                         sequence = enTag.getUpdateSequenceNum();\r
833                                         if (!oldGuid.equals(enTag.getGuid())) {\r
834                                                 logger.log(logger.EXTREME, "Updating tag guid");\r
835                                                 conn.getTagTable().updateTagGuid(oldGuid, enTag.getGuid());\r
836                                         }\r
837                                 }\r
838                                 logger.log(logger.EXTREME, "Updating tag sequence number");\r
839                                 conn.getTagTable().updateTagSequence(enTag.getGuid(), sequence);\r
840                                 logger.log(logger.EXTREME, "Resetting tag dirty flag");\r
841                                 conn.getTagTable().resetDirtyFlag(enTag.getGuid());\r
842                                 logger.log(logger.EXTREME, "Emitting sequence number to the main thread.");\r
843                                 updateSequenceNumber = sequence;\r
844                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
845                         } catch (EDAMUserException e) {\r
846                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags: " +enTag.getName());\r
847                                 logger.log(logger.LOW, e.toString());\r
848                                 badTagSync.put(enTag.getGuid(),null);\r
849                                 error = true;\r
850                         } catch (EDAMSystemException e) {\r
851                                 logger.log(logger.LOW, "** EDAM System Excepton syncLocalTags: " +enTag.getName());\r
852                                 logger.log(logger.LOW, e.toString());   \r
853                                 badTagSync.put(enTag.getGuid(),null);\r
854                                 error = true;\r
855                         } catch (EDAMNotFoundException e) {\r
856                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalTags: " +enTag.getName());\r
857                                 logger.log(logger.LOW, e.toString());\r
858                                 badTagSync.put(enTag.getGuid(),null);\r
859                                 error = true;\r
860                         } catch (TException e) {\r
861                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalTags: " +enTag.getName());\r
862                                 logger.log(logger.LOW, e.toString());\r
863                                 badTagSync.put(enTag.getGuid(),null);\r
864                                 error = true;\r
865                         }       \r
866                         \r
867                         // Find the next tag\r
868                         logger.log(logger.EXTREME, "Finding next tag");\r
869                         enTag = findNextTag();\r
870                 }\r
871                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalTags");\r
872         }\r
873         private void syncLocalLinkedNotebooks(Client noteStore) {\r
874                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalLinkedNotebooks");\r
875                 \r
876                 List<String> list = conn.getLinkedNotebookTable().getDirtyGuids();\r
877                 for (int i=0; i<list.size(); i++) {\r
878                         LinkedNotebook book = conn.getLinkedNotebookTable().getNotebook(list.get(i));\r
879                         try {\r
880                                 noteStore.updateLinkedNotebook(authToken, book);\r
881                         } catch (EDAMUserException e) {\r
882                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalLinkedNotebooks");\r
883                                 status.message.emit(tr("Error: ") +e);\r
884                                 logger.log(logger.LOW, e.toString());           \r
885                                 error = true;\r
886                                 e.printStackTrace();\r
887                         } catch (EDAMNotFoundException e) {\r
888                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalLinkedNotebooks");\r
889                                 status.message.emit(tr("Error: ") +e);\r
890                                 logger.log(logger.LOW, e.toString());           \r
891                                 error = true;\r
892                                 e.printStackTrace();\r
893                         } catch (EDAMSystemException e) {\r
894                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalLinkedNotebooks");\r
895                                 status.message.emit(tr("Error: ") +e);\r
896                                 logger.log(logger.LOW, e.toString());           \r
897                                 error = true;\r
898                                 e.printStackTrace();\r
899                         } catch (TException e) {\r
900                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalLinkedNotebooks");\r
901                                 status.message.emit(tr("Error: ") +e);\r
902                                 logger.log(logger.LOW, e.toString());           \r
903                                 error = true;\r
904                                 e.printStackTrace();\r
905                         }\r
906                 }\r
907                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalLinkedNotebooks");\r
908         }\r
909         // Sync Saved Searches with Evernote\r
910         private void syncLocalSavedSearches(Client noteStore) {\r
911                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalSavedSearches");\r
912                 List<SavedSearch> remoteList = new ArrayList<SavedSearch>();\r
913                 status.message.emit(tr("Sending saved searches."));\r
914         \r
915                 logger.log(logger.EXTREME, "Getting saved searches to compare with local");\r
916                 try {\r
917                         remoteList = noteStore.listSearches(authToken);\r
918                 } catch (EDAMUserException e1) {\r
919                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags getting remote saved search List");\r
920                         status.message.emit(tr("Error: ") +e1);\r
921                         logger.log(logger.LOW, e1.toString());  \r
922                         error = true;\r
923                 } catch (EDAMSystemException e1) {\r
924                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalTags getting remote saved search List");\r
925                         status.message.emit(tr("Error: ") +e1);\r
926                         logger.log(logger.LOW, e1.toString());          \r
927                         error = true;\r
928                 } catch (TException e1) {\r
929                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalTags getting remote saved search List");\r
930                         status.message.emit(tr("Error: ") +e1);\r
931                         logger.log(logger.LOW, e1.toString());  \r
932                         error = true;\r
933                 }               \r
934                 \r
935                 List<SavedSearch> searches = conn.getSavedSearchTable().getDirty();\r
936                 int sequence;\r
937                 // Sync the local notebooks with Evernote's\r
938                 logger.log(logger.EXTREME, "Beginning to send saved searches");\r
939                 for (int i=0; i<searches.size() &&  keepRunning; i++) {\r
940                         \r
941 //                      if (authRefreshNeeded)\r
942 //                              if (!refreshConnection())\r
943 //                                      return;\r
944                         \r
945                         SavedSearch enSearch = searches.get(i);\r
946                         try {\r
947                                 if (enSearch.getUpdateSequenceNum() > 0) \r
948                                         sequence = noteStore.updateSearch(authToken, enSearch);\r
949                                 else {\r
950                                         logger.log(logger.EXTREME, "New saved search found.");\r
951                                         // Look for a tag with the same name.  If one is found, we don't need \r
952                                         // to create another one\r
953                                         boolean found = false;\r
954                                         logger.log(logger.EXTREME, "Matching remote saved search names with local");\r
955                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
956                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enSearch.getName())) {\r
957                                                         enSearch = remoteList.get(k);\r
958                                                         found = true;\r
959                                                         logger.log(logger.EXTREME, "Matching saved search found");\r
960                                                         sequence = enSearch.getUpdateSequenceNum();\r
961                                                 }\r
962                                         }\r
963 \r
964                                         String oldGuid = enSearch.getGuid();\r
965                                         if (!found)\r
966                                                 enSearch = noteStore.createSearch(authToken, enSearch);\r
967                                         sequence = enSearch.getUpdateSequenceNum();\r
968                                         logger.log(logger.EXTREME, "Updating tag guid in local database");\r
969                                         conn.getSavedSearchTable().updateSavedSearchGuid(oldGuid, enSearch.getGuid());\r
970                                 }\r
971                                 logger.log(logger.EXTREME, "Updating tag sequence in local database");\r
972                                 conn.getSavedSearchTable().updateSavedSearchSequence(enSearch.getGuid(), sequence);\r
973                                 logger.log(logger.EXTREME, "Resetting tag dirty flag");\r
974                                 conn.getSavedSearchTable().resetDirtyFlag(enSearch.getGuid());\r
975                                 logger.log(logger.EXTREME, "Emitting sequence number to the main thread.");\r
976                                 updateSequenceNumber = sequence;\r
977                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
978                         } catch (EDAMUserException e) {\r
979                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags");\r
980                                 logger.log(logger.LOW, e.toString());   \r
981                                 error = true;\r
982                         } catch (EDAMSystemException e) {\r
983                                 logger.log(logger.LOW, "** EDAM System Excepton syncLocalTags");\r
984                                 logger.log(logger.LOW, e.toString());   \r
985                                 error = true;\r
986                         } catch (EDAMNotFoundException e) {\r
987                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalTags");\r
988                                 logger.log(logger.LOW, e.toString());   \r
989                                 error = true;\r
990                         } catch (TException e) {\r
991                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalTags");\r
992                                 logger.log(logger.LOW, e.toString());   \r
993                                 error = true;\r
994                         }               \r
995                 }\r
996 \r
997                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalSavedSearches");\r
998         }       \r
999 \r
1000         // Sync evernote changes with local database\r
1001         private void syncRemoteToLocal(Client noteStore) {\r
1002                 logger.log(logger.HIGH, "Entering SyncRunner.syncRemoteToLocal");\r
1003 \r
1004                 List<Note> dirtyNotes = conn.getNoteTable().getDirty();\r
1005                 dirtyNoteGuids = new Vector<String>();\r
1006                 for (int i=0; i<dirtyNotes.size() && keepRunning; i++) {\r
1007                         dirtyNoteGuids.add(dirtyNotes.get(i).getGuid());\r
1008                 }\r
1009                 \r
1010                 int chunkSize = 10;\r
1011                 SyncChunk chunk = null;\r
1012                 boolean fullSync = false;\r
1013                 boolean more = true;\r
1014                 \r
1015                 if (updateSequenceNumber == 0)\r
1016                         fullSync = true;\r
1017                 \r
1018                 status.message.emit(tr("Downloading 0% complete."));\r
1019                 \r
1020                 while(more &&  keepRunning) {\r
1021                         \r
1022 //                      if (authRefreshNeeded)\r
1023 //                              if (!refreshConnection())\r
1024 //                                      return;\r
1025                         \r
1026                         int sequence = updateSequenceNumber;\r
1027                         try {\r
1028 //                              conn.beginTransaction();\r
1029                                 logger.log(logger.EXTREME, "Getting chunk from Evernote");\r
1030                                 chunk = noteStore.getSyncChunk(authToken, sequence, chunkSize, fullSync);\r
1031                                 logger.log(logger.LOW, "Chunk High Sequence: " +chunk.getChunkHighUSN());\r
1032                         } catch (EDAMUserException e) {\r
1033                                 error = true;\r
1034                                 e.printStackTrace();\r
1035                                 status.message.emit(e.getMessage());\r
1036                         } catch (EDAMSystemException e) {\r
1037                                 error = true;\r
1038                                 e.printStackTrace();\r
1039                                 status.message.emit(e.getMessage());\r
1040                         } catch (TException e) {\r
1041                                 error = true;\r
1042                                 e.printStackTrace();\r
1043                                 status.message.emit(e.getMessage());\r
1044                         } \r
1045                         if (error || chunk == null) \r
1046                                 return;\r
1047                                 \r
1048                 \r
1049                         \r
1050                         syncRemoteTags(chunk.getTags());\r
1051                         syncRemoteSavedSearches(chunk.getSearches());\r
1052                         syncRemoteNotebooks(chunk.getNotebooks());\r
1053                         syncRemoteNotes(noteStore, chunk.getNotes(), fullSync, authToken);\r
1054                         syncRemoteResources(noteStore, chunk.getResources());\r
1055                         syncRemoteLinkedNotebooks(chunk.getLinkedNotebooks());\r
1056                         \r
1057                         // Signal about any updated notes to invalidate the cache\r
1058                         for (int i=0; i<chunk.getNotesSize(); i++) \r
1059                                 noteSignal.noteChanged.emit(chunk.getNotes().get(i).getGuid(), null); \r
1060                         syncExpungedNotes(chunk);\r
1061                         \r
1062                         \r
1063                         // Check for more notes\r
1064                         if (chunk.getChunkHighUSN() <= updateSequenceNumber) \r
1065                                 more = false;\r
1066                         if (error)\r
1067                                 more = false;\r
1068                         logger.log(logger.EXTREME, "More notes? " +more);\r
1069 \r
1070                         \r
1071                         // Save the chunk sequence number\r
1072                         if (!error && chunk.getChunkHighUSN() > 0 && keepRunning) {\r
1073                                 logger.log(logger.EXTREME, "emitting sequence number to main thread");\r
1074                                 updateSequenceNumber = chunk.getChunkHighUSN();\r
1075                                 conn.getSyncTable().setLastSequenceDate(chunk.getCurrentTime());\r
1076                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
1077 //                              conn.commitTransaction();\r
1078                         }\r
1079                         \r
1080                         \r
1081                         if (more) {\r
1082                                 long pct = chunk.getChunkHighUSN() * 100;\r
1083                                 conn.getSyncTable().setLastSequenceDate(chunk.getCurrentTime());\r
1084                                 pct = pct/evernoteUpdateCount;\r
1085                                 status.message.emit(tr("Downloading ") +new Long(pct).toString()+tr("% complete."));\r
1086                         }\r
1087 //                      conn.commitTransaction();\r
1088                 }\r
1089                 logger.log(logger.HIGH, "Leaving SyncRunner.syncRemoteToLocal");\r
1090         }\r
1091         // Sync expunged notes\r
1092         private void syncExpungedNotes(SyncChunk chunk) {\r
1093                 // Do the local deletes\r
1094                 logger.log(logger.EXTREME, "Doing local deletes");\r
1095                 List<String> guid = chunk.getExpungedNotes();\r
1096                 if (guid != null) {\r
1097                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1098                                 String notebookGuid = "";\r
1099                                 Note localNote = conn.getNoteTable().getNote(guid.get(i), false, false, false, false, false);\r
1100                                 if (localNote != null) {\r
1101                                         conn.getNoteTable().updateNoteSequence(guid.get(i), 0);\r
1102                                         notebookGuid = localNote.getNotebookGuid();\r
1103                                 }\r
1104                                 if (!conn.getNotebookTable().isNotebookLocal(notebookGuid)) {\r
1105                                         logger.log(logger.EXTREME, "Expunging local note from database");\r
1106                                         conn.getNoteTable().expungeNote(guid.get(i), true, false);\r
1107                                 }\r
1108                         }\r
1109                 }\r
1110                 guid = chunk.getExpungedNotebooks();\r
1111                 if (guid != null)\r
1112                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1113                                 logger.log(logger.EXTREME, "Expunging local notebook from database");\r
1114                                 conn.getNotebookTable().expungeNotebook(guid.get(i), false);\r
1115                         }\r
1116                 guid = chunk.getExpungedTags();\r
1117                 if (guid != null)\r
1118                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1119                                 logger.log(logger.EXTREME, "Expunging tags from local database");\r
1120                                 conn.getTagTable().expungeTag(guid.get(i), false);\r
1121                         }\r
1122                 guid = chunk.getExpungedSearches();\r
1123                 if (guid != null) \r
1124                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1125                                 logger.log(logger.EXTREME, "Expunging saved search from local database");\r
1126                                 conn.getSavedSearchTable().expungeSavedSearch(guid.get(i), false);\r
1127                         }\r
1128                 guid = chunk.getExpungedLinkedNotebooks();\r
1129                 if (guid != null) \r
1130                         for (int i=0; i<guid.size() && keepRunning; i++) {\r
1131                                 logger.log(logger.EXTREME, "Expunging linked notebook from local database");\r
1132                                 conn.getLinkedNotebookTable().expungeNotebook(guid.get(i), false);\r
1133                         }\r
1134 \r
1135         }\r
1136         // Sync remote tags\r
1137         private void syncRemoteTags(List<Tag> tags) {\r
1138                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteTags");\r
1139                 if (tags != null) {\r
1140                         for (int i=0; i<tags.size() && keepRunning; i++) {\r
1141                                 String oldGuid;\r
1142                                 oldGuid = conn.getTagTable().findTagByName(tags.get(i).getName());\r
1143                                 if (oldGuid != null && !tags.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
1144                                         conn.getTagTable().updateTagGuid(oldGuid, tags.get(i).getGuid());\r
1145                                 conn.getTagTable().syncTag(tags.get(i), false);\r
1146                         }\r
1147                 }\r
1148                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteTags");\r
1149         }\r
1150         // Sync remote saved searches\r
1151         private void syncRemoteSavedSearches(List<SavedSearch> searches) {\r
1152                 logger.log(logger.EXTREME, "Entering SyncRunner.syncSavedSearches");\r
1153                 if (searches != null) {\r
1154                         for (int i=0; i<searches.size() && keepRunning; i++) {\r
1155                                 String oldGuid;\r
1156                                 oldGuid = conn.getSavedSearchTable().findSavedSearchByName(searches.get(i).getName());\r
1157                                 if (oldGuid != null && !searches.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
1158                                         conn.getSavedSearchTable().updateSavedSearchGuid(oldGuid, searches.get(i).getGuid());\r
1159                                 conn.getSavedSearchTable().syncSavedSearch(searches.get(i), false);\r
1160                         }\r
1161                 }\r
1162                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncSavedSearches");\r
1163         }\r
1164         // Sync remote linked notebooks\r
1165         private void syncRemoteLinkedNotebooks(List<LinkedNotebook> books) {\r
1166                 logger.log(logger.EXTREME, "Entering SyncRunner.syncLinkedNotebooks");\r
1167                 if (books != null) {\r
1168                         for (int i=0; i<books.size() && keepRunning; i++) {\r
1169                                 conn.getLinkedNotebookTable().updateNotebook(books.get(i), false); \r
1170                         }\r
1171                 }\r
1172                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncLinkedNotebooks");\r
1173         }\r
1174         // Sync remote Notebooks 2\r
1175         private void syncRemoteNotebooks(List<Notebook> notebooks) {\r
1176                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotebooks");\r
1177                 if (notebooks != null) {\r
1178                         for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
1179                                 String oldGuid;\r
1180                                 oldGuid = conn.getNotebookTable().findNotebookByName(notebooks.get(i).getName());\r
1181                                 if (oldGuid != null && !conn.getNotebookTable().isNotebookLocal(oldGuid) && !notebooks.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
1182                                         conn.getNotebookTable().updateNotebookGuid(oldGuid, notebooks.get(i).getGuid());\r
1183                                 conn.getNotebookTable().syncNotebook(notebooks.get(i), false); \r
1184                                 \r
1185                                 // Synchronize shared notebook information\r
1186 //                              if (notebooks.get(i).getSharedNotebookIdsSize() > 0) {\r
1187 //                                      conn.getSharedNotebookTable().expungeNotebookByGuid(notebooks.get(i).getGuid(), false);\r
1188 //                                      for (int j=0; j<notebooks.get(i).getSharedNotebookIdsSize(); j++) {\r
1189 //                                              syncRemoteSharedNotebook(notebooks.get(i).getGuid(), notebooks.get(i).getSharedNotebookIds().get(j), authToken);\r
1190 //                                      }\r
1191 //                              }\r
1192                         }\r
1193                 }                       \r
1194                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotebooks");\r
1195         }\r
1196         // Sync remote shared notebook\r
1197 //      private void syncRemoteSharedNotebook(String guid, Long id, String token) {\r
1198 //              List<SharedNotebook> books = noteStore.getSharedNotebookByAuth(authToken);\r
1199 //      }\r
1200         // Sync remote Resources\r
1201         private void syncRemoteResources(Client noteStore, List<Resource> resource) {\r
1202                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteResources");\r
1203                 if (resource != null) {\r
1204                         for (int i=0; i<resource.size() && keepRunning; i++) {\r
1205                                 syncRemoteResource(noteStore, resource.get(i), authToken);\r
1206                         }\r
1207                 }\r
1208                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteResources");\r
1209         }\r
1210         // Sync remote resource\r
1211         private void syncRemoteResource(Client noteStore, Resource resource, String authToken) {\r
1212                 // This is how the logic for this works.\r
1213                 // 1.) If the resource is not in the local database, we add it.\r
1214                 // 2.) If a copy of the resource is in the local database and the note isn't dirty, we update the local copy\r
1215                 // 3.) If a copy of the resource is in the local databbase and it is dirty and the hash doesn't match, we ignore it because there\r
1216                 //     is a conflict.  The note conflict should get a copy of the resource at that time.\r
1217                 \r
1218                 boolean saveNeeded = false;\r
1219                 /* #1 */                Resource r = getEvernoteResource(noteStore, resource.getGuid(), true,true,true, authToken);\r
1220                                                 Resource l = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), false);\r
1221                                                 if (l == null) {\r
1222                                                         saveNeeded = true;\r
1223                                                 } else {\r
1224                 /* #2 */                        boolean isNoteDirty = conn.getNoteTable().isNoteDirty(r.getNoteGuid());\r
1225                                                         if (!isNoteDirty)\r
1226                                                                 saveNeeded = true;\r
1227                                                         else {\r
1228                 /* #3 */                                String remoteHash = "";\r
1229                                                                 if (r != null && r.getData() != null && r.getData().getBodyHash() != null)\r
1230                                                                         remoteHash = byteArrayToHexString(r.getData().getBodyHash());\r
1231                                                                 String localHash = "";\r
1232                                                                 if (l != null && l.getData() != null && l.getData().getBodyHash() != null)\r
1233                                                                         remoteHash = byteArrayToHexString(l.getData().getBodyHash());\r
1234                                                 \r
1235                                                                 if (localHash.equalsIgnoreCase(remoteHash))\r
1236                                                                         saveNeeded = true;\r
1237                                                         }\r
1238                                                 }\r
1239                                                 \r
1240                                                 if (saveNeeded) \r
1241                                                         conn.getNoteTable().noteResourceTable.updateNoteResource(r, false);\r
1242                                                 if (r.getMime().equalsIgnoreCase("application/vnd.evernote.ink"))\r
1243                                                         downloadInkNoteImage(r.getGuid(), authToken);\r
1244 \r
1245         }\r
1246         // Sync remote notes\r
1247         private void syncRemoteNotes(Client noteStore, List<Note> note, boolean fullSync, String token) {\r
1248                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotes");\r
1249                 if (note != null) {\r
1250                         for (int i=0; i<note.size() && keepRunning; i++) {\r
1251                                 Note n = getEvernoteNote(noteStore, note.get(i).getGuid(), true, fullSync, true,true, token);\r
1252                                 syncRemoteNote(n, fullSync, token);\r
1253                         }\r
1254                 }\r
1255                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotes");\r
1256         }\r
1257         private void syncRemoteNote(Note n, boolean fullSync, String token) {\r
1258                 if (n!=null) {\r
1259                         \r
1260                         // Basically, this is how the sync logic for a note works.\r
1261                         // If the remote note has changed and the local has not, we\r
1262                         // accept the change.\r
1263                         // If both the local & remote have changed but the sequence\r
1264                         // numbers are the same, we don't accept the change.  This\r
1265                         // seems to happen when attachments are indexed by the server.\r
1266                         // If both the local & remote have changed and the sequence numbers\r
1267                         // are different we move the local copy to a local notebook (making sure\r
1268                         // to copy all resources) and we accept the new one.                    \r
1269                         boolean conflictingNote = true;\r
1270                         logger.log(logger.EXTREME, "Checking for duplicate note " +n.getGuid());\r
1271                         if (dirtyNoteGuids != null && dirtyNoteGuids.contains(n.getGuid())) { \r
1272                                 logger.log(logger.EXTREME, "Conflict check beginning");\r
1273                                 conflictingNote = checkForConflict(n);\r
1274                                 logger.log(logger.EXTREME, "Conflict check results " +conflictingNote);\r
1275                                 if (conflictingNote)\r
1276                                         moveConflictingNote(n.getGuid());\r
1277                         }\r
1278                         boolean ignoreNote = false;\r
1279                         if (ignoreNotebooks.contains(n.getNotebookGuid()))\r
1280                                 ignoreNote = true;\r
1281                         for (int i=0; i<n.getTagGuidsSize(); i++) {\r
1282                                 if (ignoreTags.contains(n.getTagGuids().get(i))) {\r
1283                                         ignoreNote = true;\r
1284                                         i=n.getTagGuidsSize();\r
1285                                 }\r
1286                         }\r
1287                                 \r
1288                         if ((conflictingNote || fullSync) && !ignoreNote) {\r
1289                                 logger.log(logger.EXTREME, "Saving Note");\r
1290                                 conn.getNoteTable().syncNote(n);\r
1291                                 // The following was commented out because it caused a race condition on the database where resources \r
1292                                 // may be lost.  We do the same thing elsewhere;.\r
1293 //                              noteSignal.noteChanged.emit(n.getGuid(), null);   // Signal to ivalidate note cache \r
1294                                 noteSignal.noteDownloaded.emit(n, true);                // Signal to add note to index\r
1295                                         logger.log(logger.EXTREME, "Note Saved");\r
1296                                 if (fullSync && n.getResources() != null) {\r
1297                                         for (int q=0; q<n.getResources().size() && keepRunning; q++) {\r
1298                                                 logger.log(logger.EXTREME, "Getting note resources.");\r
1299                                                 conn.getNoteTable().noteResourceTable.updateNoteResource(n.getResources().get(q), false);\r
1300                                                 if (n.getResources().get(q).getMime().equalsIgnoreCase("application/vnd.evernote.ink"))\r
1301                                                         downloadInkNoteImage(n.getResources().get(q).getGuid(), token);\r
1302                                         }\r
1303                                 }\r
1304                         }\r
1305                 }\r
1306         }\r
1307         private Note getEvernoteNote(Client noteStore, String guid, boolean withContent, boolean withResourceData, boolean withResourceRecognition, boolean withResourceAlternateData, String token) { \r
1308                 Note n = null;\r
1309                 try {\r
1310                         logger.log(logger.EXTREME, "Retrieving note " +guid);\r
1311                         n = noteStore.getNote(token, guid, withContent, withResourceData, withResourceRecognition, withResourceAlternateData);\r
1312                         logger.log(logger.EXTREME, "Note " +guid +" has been retrieved.");\r
1313                 } catch (EDAMUserException e) {\r
1314                         logger.log(logger.LOW, "*** EDAM User Excepton getEvernoteNote");\r
1315                         logger.log(logger.LOW, e.toString());   \r
1316                         error = true;\r
1317                         e.printStackTrace();\r
1318                 } catch (EDAMSystemException e) {\r
1319                         logger.log(logger.LOW, "*** EDAM System Excepton getEvernoteNote");\r
1320                         logger.log(logger.LOW, e.toString());   \r
1321                         error = true;\r
1322                         e.printStackTrace();\r
1323                 } catch (EDAMNotFoundException e) {\r
1324                         logger.log(logger.LOW, "*** EDAM Not Found Excepton getEvernoteNote");\r
1325                         logger.log(logger.LOW, e.toString());   \r
1326                         error = true;\r
1327                         e.printStackTrace();\r
1328                 } catch (TException e) {\r
1329                         logger.log(logger.LOW, "*** EDAM TExcepton getEvernoteNote");\r
1330                         logger.log(logger.LOW, e.toString());   \r
1331                         error = true;\r
1332                         e.printStackTrace();\r
1333                 }\r
1334                 return n;\r
1335         }\r
1336         private Resource getEvernoteResource(Client noteStore, String guid, boolean withData, boolean withRecognition, boolean withAttributes, String token) { \r
1337                 Resource n = null;\r
1338                 try {\r
1339                         logger.log(logger.EXTREME, "Retrieving resource " +guid);\r
1340                         n = noteStore.getResource(token, guid, withData, withRecognition, withAttributes, withAttributes);\r
1341                         logger.log(logger.EXTREME, "Resource " +guid +" has been retrieved.");\r
1342                 } catch (EDAMUserException e) {\r
1343                         logger.log(logger.LOW, "*** EDAM User Excepton getEvernoteNote");\r
1344                         logger.log(logger.LOW, e.toString());   \r
1345                         error = true;\r
1346                         e.printStackTrace();\r
1347                 } catch (EDAMSystemException e) {\r
1348                         logger.log(logger.LOW, "*** EDAM System Excepton getEvernoteNote");\r
1349                         logger.log(logger.LOW, e.toString());   \r
1350                         error = true;\r
1351                         e.printStackTrace();\r
1352                 } catch (EDAMNotFoundException e) {\r
1353                         logger.log(logger.LOW, "*** EDAM Not Found Excepton getEvernoteNote");\r
1354                         logger.log(logger.LOW, e.toString());   \r
1355                         error = true;\r
1356                         e.printStackTrace();\r
1357                 } catch (TException e) {\r
1358                         logger.log(logger.LOW, "*** EDAM TExcepton getEvernoteNote");\r
1359                         logger.log(logger.LOW, e.toString());   \r
1360                         error = true;\r
1361                         e.printStackTrace();\r
1362                 }\r
1363                 return n;\r
1364         }\r
1365 \r
1366         \r
1367         private boolean checkForConflict(Note n) {\r
1368                 logger.log(logger.EXTREME, "Checking note sequence number  " +n.getGuid());\r
1369                 Note oldNote = conn.getNoteTable().getNote(n.getGuid(), false, false, false, false, false);\r
1370                 logger.log(logger.EXTREME, "Local/Remote sequence numbers: " +oldNote.getUpdateSequenceNum()+"/"+n.getUpdateSequenceNum());\r
1371                 if (oldNote.getUpdateSequenceNum() == n.getUpdateSequenceNum())\r
1372                         return false;\r
1373                 return true;\r
1374         }\r
1375         \r
1376         private void moveConflictingNote(String guid) {\r
1377                 logger.log(logger.EXTREME, "Conflicting change found for note " +guid);\r
1378                 List<Notebook> books = conn.getNotebookTable().getAllLocal();\r
1379                 String notebookGuid = null;\r
1380                 for (int i=0; i<books.size() && keepRunning; i++) {\r
1381                         if (books.get(i).getName().equalsIgnoreCase("Conflicting Changes (local)") ||\r
1382                                         books.get(i).getName().equalsIgnoreCase("Conflicting Changes")) {\r
1383                                 notebookGuid = books.get(i).getGuid();\r
1384                                 i=books.size();\r
1385                         }\r
1386                 }\r
1387                 \r
1388                 if (notebookGuid == null) {\r
1389                         logger.log(logger.EXTREME, "Building conflicting change notebook " +guid);\r
1390                         Calendar currentTime = new GregorianCalendar();\r
1391                         Long l = new Long(currentTime.getTimeInMillis());\r
1392                         long prevTime = l;\r
1393                         while (prevTime==l) {\r
1394                                 currentTime = new GregorianCalendar();\r
1395                                 l=currentTime.getTimeInMillis();\r
1396                         }\r
1397                         String randint = new String(Long.toString(l));\r
1398                 \r
1399                         Notebook newBook = new Notebook();\r
1400                         newBook.setUpdateSequenceNum(0);\r
1401                         newBook.setGuid(randint);\r
1402                         newBook.setName("Conflicting Changes");\r
1403                         newBook.setServiceCreated(new Date().getTime());\r
1404                         newBook.setServiceUpdated(new Date().getTime());\r
1405                         newBook.setDefaultNotebook(false);\r
1406                         newBook.setPublished(false);\r
1407                         \r
1408                         conn.getNotebookTable().addNotebook(newBook, false, true);\r
1409                         notebookSignal.listChanged.emit();\r
1410                         notebookGuid = newBook.getGuid();\r
1411                         refreshNeeded = true;\r
1412                 }\r
1413                 \r
1414                 // Now that we have a good notebook guid, we need to move the conflicting note\r
1415                 // to the local notebook\r
1416                 logger.log(logger.EXTREME, "Moving conflicting note " +guid);\r
1417                 Calendar currentTime = new GregorianCalendar();\r
1418                 Long l = new Long(currentTime.getTimeInMillis());\r
1419                 long prevTime = l;\r
1420                 while (prevTime==l) {\r
1421                         currentTime = new GregorianCalendar();\r
1422                         l = currentTime.getTimeInMillis();\r
1423                 }\r
1424                 String newGuid = new String(Long.toString(l));\r
1425                                         \r
1426                 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);\r
1427                 for (int i=0; i<oldNote.getResources().size() && keepRunning; i++) {\r
1428                         l = new Long(currentTime.getTimeInMillis());\r
1429                         String newResG = new String(Long.toString(l));\r
1430                         String oldResG = oldNote.getResources().get(i).getGuid();\r
1431                         conn.getNoteTable().noteResourceTable.resetUpdateSequenceNumber(oldResG, true);\r
1432                         conn.getNoteTable().noteResourceTable.updateNoteResourceGuid(oldResG, newResG, true);\r
1433                 }\r
1434                 \r
1435                 conn.getNoteTable().resetNoteSequence(guid);\r
1436                 conn.getNoteTable().updateNoteGuid(guid, newGuid);\r
1437                 conn.getNoteTable().updateNoteNotebook(newGuid, notebookGuid, true);\r
1438                 \r
1439                 noteSignal.notebookChanged.emit(newGuid, notebookGuid);\r
1440                 refreshNeeded = true;\r
1441                 noteSignal.guidChanged.emit(guid,newGuid);\r
1442         }\r
1443         \r
1444 \r
1445 \r
1446         \r
1447         //******************************************************\r
1448         //******************************************************\r
1449         //** Utility Functions\r
1450         //******************************************************\r
1451         //******************************************************\r
1452         // Convert a byte array to a hex string\r
1453         private static String byteArrayToHexString(byte data[]) {\r
1454                 StringBuffer buf = new StringBuffer();\r
1455             for (byte element : data) {\r
1456                 int halfbyte = (element >>> 4) & 0x0F;\r
1457                 int two_halfs = 0;\r
1458                 do {\r
1459                         if ((0 <= halfbyte) && (halfbyte <= 9))\r
1460                                buf.append((char) ('0' + halfbyte));\r
1461                            else\r
1462                                 buf.append((char) ('a' + (halfbyte - 10)));\r
1463                         halfbyte = element & 0x0F;\r
1464                 } while(two_halfs++ < 1);\r
1465             }\r
1466             return buf.toString();              \r
1467         }\r
1468 \r
1469         \r
1470         \r
1471         //*******************************************************\r
1472         //* Find dirty tags, which do not have newly created parents\r
1473         //*******************************************************\r
1474         private Tag findNextTag() {\r
1475                 logger.log(logger.HIGH, "Entering SyncRunner.findNextTag");\r
1476                 Tag nextTag = null;\r
1477                 List<Tag> tags = conn.getTagTable().getDirty();\r
1478                 \r
1479                 // Find the parent.  If the parent has a sequence > 0 then it is a good\r
1480                 // parent.\r
1481                 for (int i=0; i<tags.size() && keepRunning; i++) {\r
1482                         if (!badTagSync.containsKey(tags.get(i).getGuid())) {\r
1483                                 if (tags.get(i).getParentGuid() == null) {\r
1484                                         logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - tag found without parent");\r
1485                                         return tags.get(i);\r
1486                                 }\r
1487                                 Tag parentTag = conn.getTagTable().getTag(tags.get(i).getParentGuid());\r
1488                                 if (parentTag.getUpdateSequenceNum() > 0) {\r
1489                                         logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - tag found");\r
1490                                         return tags.get(i);\r
1491                                 }\r
1492                         }\r
1493                 }\r
1494                 \r
1495                 logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - no tags returned");\r
1496                 return nextTag;\r
1497         }\r
1498         \r
1499         \r
1500            // Connect to Evernote\r
1501     public boolean enConnect()  {\r
1502         try {\r
1503                         userStoreTrans = new THttpClient(userStoreUrl);\r
1504                         userStoreTrans.setCustomHeader("User-Agent", userAgent);\r
1505                 } catch (TTransportException e) {\r
1506                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1507                         mb.exec();\r
1508                         e.printStackTrace();\r
1509                 }\r
1510                 userStoreProt = new TBinaryProtocol(userStoreTrans);\r
1511             userStore = new UserStore.Client(userStoreProt, userStoreProt);\r
1512             syncSignal.saveUserStore.emit(userStore);\r
1513             try {\r
1514                         //authResult = userStore.authenticate(username, password, consumerKey, consumerSecret);\r
1515                 user = userStore.getUser(authToken);\r
1516                 } catch (EDAMUserException e) {\r
1517                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Error", "Invalid Authorization");\r
1518                         mb.exec();\r
1519                         isConnected = false;\r
1520                         return false;\r
1521                 } catch (EDAMSystemException e) {\r
1522                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "EDAM System Excepton", e.getLocalizedMessage());\r
1523                         mb.exec();\r
1524                         e.printStackTrace();\r
1525                         isConnected = false;\r
1526                 } catch (TException e) {\r
1527                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1528                         mb.exec();\r
1529                         e.printStackTrace();\r
1530                         isConnected = false;\r
1531                 }\r
1532                 \r
1533             boolean versionOk = false;\r
1534                 try {\r
1535                         versionOk = userStore.checkVersion("NixNote", \r
1536                     com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR, \r
1537                       com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR);\r
1538                 } catch (TException e) {\r
1539                         e.printStackTrace();\r
1540                         isConnected = false;\r
1541                 } \r
1542             if (!versionOk) { \r
1543                 System.err.println("Incomatible EDAM client protocol version"); \r
1544                 isConnected = false;\r
1545             }\r
1546             //if (authResult != null) {\r
1547                 //user = authResult.getUser(); \r
1548                 //authToken = authResult.getAuthenticationToken(); \r
1549                 noteStoreUrl = noteStoreUrlBase + user.getShardId();\r
1550                 syncSignal.saveAuthToken.emit(authToken);\r
1551                 syncSignal.saveNoteStore.emit(localNoteStore);\r
1552                 \r
1553          \r
1554                 try {\r
1555                         noteStoreTrans = new THttpClient(noteStoreUrl);\r
1556                         noteStoreTrans.setCustomHeader("User-Agent", userAgent);\r
1557                 } catch (TTransportException e) {\r
1558                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1559                         mb.exec();\r
1560                         e.printStackTrace();\r
1561                         isConnected = false;\r
1562                 } \r
1563                 noteStoreProt = new TBinaryProtocol(noteStoreTrans);\r
1564                 localNoteStore = \r
1565                         new NoteStore.Client(noteStoreProt, noteStoreProt); \r
1566                 isConnected = true;\r
1567                 //authTimeRemaining = authResult.getExpiration() - authResult.getCurrentTime();\r
1568                 //authRefreshTime = authTimeRemaining / 2;\r
1569             //}\r
1570             \r
1571                 // Get user information\r
1572                 try {\r
1573                         User user = userStore.getUser(authToken);\r
1574                         syncSignal.saveUserInformation.emit(user);\r
1575                 } catch (EDAMUserException e1) {\r
1576                         e1.printStackTrace();\r
1577                 } catch (EDAMSystemException e1) {\r
1578                         e1.printStackTrace();\r
1579                 } catch (TException e1) {\r
1580                         e1.printStackTrace();\r
1581                 }\r
1582             \r
1583             return isConnected;\r
1584     }\r
1585         // Disconnect from the database                         \r
1586     public void enDisconnect() {\r
1587         isConnected = false;\r
1588     }\r
1589     \r
1590     /*\r
1591     // Refresh the connection\r
1592     private synchronized boolean refreshConnection() {\r
1593         \r
1594                 logger.log(logger.EXTREME, "Entering SyncRunner.refreshConnection()");\r
1595 //        Calendar cal = Calendar.getInstance();\r
1596                 \r
1597         // If we are not connected let's get out of here\r
1598         if (!isConnected)\r
1599                 return false;\r
1600         \r
1601                 // If we fail too many times, then let's give up.\r
1602                 if (failedRefreshes >=5) {\r
1603                         logger.log(logger.EXTREME, "Refresh attempts have failed.  Disconnecting.");\r
1604                         isConnected = false;\r
1605                         status.message.emit(tr("Unable to synchronize - Authentication failed"));\r
1606                         return false;\r
1607                 }\r
1608         \r
1609                 // If this is the first time through, then we need to set this\r
1610 //              if (authRefreshTime == 0 || cal.getTimeInMillis() > authRefreshTime) \r
1611 //                      authRefreshTime = cal.getTimeInMillis();\r
1612                 \r
1613  //             // Default to checking again in 5 min.  This in case we fail.\r
1614  //             authRefreshTime = authRefreshTime +(5*60*1000);     \r
1615 \r
1616                 // Try to get a new token\r
1617                 AuthenticationResult newAuth = null; \r
1618                 logger.log(logger.EXTREME, "Beginning to try authentication refresh");\r
1619         try {\r
1620                 if (userStore != null && authToken != null) \r
1621                         newAuth = userStore.refreshAuthentication(authToken); \r
1622                 else\r
1623                         return false;\r
1624                 logger.log(logger.EXTREME, "UserStore.refreshAuthentication has succeeded.");\r
1625                 } catch (EDAMUserException e) {\r
1626                         e.printStackTrace();\r
1627                         syncSignal.authRefreshComplete.emit(false);\r
1628                         failedRefreshes++;\r
1629                         return false;\r
1630                 } catch (EDAMSystemException e) {\r
1631                         e.printStackTrace();\r
1632                         syncSignal.authRefreshComplete.emit(false);\r
1633                         failedRefreshes++;\r
1634                         return false;           \r
1635                 } catch (TException e) { \r
1636                         e.printStackTrace();\r
1637                         syncSignal.authRefreshComplete.emit(false);\r
1638                         failedRefreshes++;\r
1639                         return false;\r
1640                 }\r
1641                 \r
1642                 // If we didn't get a good auth, then we've failed\r
1643                 if (newAuth == null) {\r
1644                         failedRefreshes++;\r
1645                         status.message.emit(tr("Unable to synchronize - Authentication failed"));\r
1646                         logger.log(logger.EXTREME, "Authentication failure #" +failedRefreshes);\r
1647                         status.message.emit(tr("Unable to synchronize - Authentication failed"));\r
1648                         syncSignal.authRefreshComplete.emit(false);\r
1649                         return false;\r
1650                 }\r
1651                 \r
1652                 // We got a good token.  Now we need to setup the time to renew it.\r
1653                 logger.log(logger.EXTREME, "Saving authentication tokens");\r
1654                 authResult = newAuth;\r
1655                 authToken = new String(newAuth.getAuthenticationToken());\r
1656 //              authTimeRemaining = authResult.getExpiration() - authResult.getCurrentTime();\r
1657 //              authRefreshTime = cal.getTimeInMillis() + (authTimeRemaining/4);        \r
1658                 failedRefreshes=0;\r
1659                 syncSignal.authRefreshComplete.emit(true);\r
1660                 authRefreshNeeded = false;\r
1661                         \r
1662                 // This should never happen, but if it does we consider this a faild attempt.\r
1663 //              if (authTimeRemaining <= 0) {\r
1664 //                      failedRefreshes++;\r
1665 //                      syncSignal.authRefreshComplete.emit(false);\r
1666 //              }\r
1667                 \r
1668                 return true;\r
1669     }\r
1670     \r
1671     */\r
1672     \r
1673         public synchronized boolean addWork(String request) {\r
1674                 if (workQueue.offer(request))\r
1675                         return true;\r
1676                 return false;\r
1677         }\r
1678     \r
1679     private Note getNoteContent(Note n) {\r
1680                 QTextCodec codec = QTextCodec.codecForLocale();\r
1681                 codec = QTextCodec.codecForName("UTF-8");\r
1682         n.setContent(codec.toUnicode(new QByteArray(n.getContent())));\r
1683         return n;\r
1684     }\r
1685 \r
1686 \r
1687 \r
1688     //*********************************************************\r
1689     //* Special download instructions.  Used for DB upgrades\r
1690     //*********************************************************\r
1691     private void downloadAllSharedNotebooks(Client noteStore) {\r
1692         try {\r
1693                         List<SharedNotebook> books = noteStore.listSharedNotebooks(authToken);\r
1694                         logger.log(logger.LOW, "Shared notebooks found = " +books.size());\r
1695                         for (int i=0; i<books.size(); i++) {\r
1696                                 conn.getSharedNotebookTable().updateNotebook(books.get(i), false);\r
1697                         }\r
1698                         conn.getSyncTable().deleteRecord("FullSharedNotebookSync");\r
1699                 } catch (EDAMUserException e1) {\r
1700                         e1.printStackTrace();\r
1701                         status.message.emit(tr("User exception Listing shared notebooks."));\r
1702                         logger.log(logger.LOW, e1.getMessage());\r
1703                         return;\r
1704                 } catch (EDAMSystemException e1) {\r
1705                         e1.printStackTrace();\r
1706                         status.message.emit(tr("System exception Listing shared notebooks."));\r
1707                         logger.log(logger.LOW, e1.getMessage());\r
1708                         return;\r
1709                 } catch (TException e1) {\r
1710                         e1.printStackTrace();\r
1711                         status.message.emit(tr("Transaction exception Listing shared notebooks."));\r
1712                         logger.log(logger.LOW, e1.getMessage());\r
1713                         return;\r
1714                 } catch (EDAMNotFoundException e1) {\r
1715                         e1.printStackTrace();\r
1716                         status.message.emit(tr("EDAM Not Found exception Listing shared notebooks."));\r
1717                         logger.log(logger.LOW, e1.getMessage());\r
1718                 }\r
1719     }\r
1720     private void downloadAllNotebooks(Client noteStore) {\r
1721         try {\r
1722                         List<Notebook> books = noteStore.listNotebooks(authToken);\r
1723                         logger.log(logger.LOW, "Shared notebooks found = " +books.size());\r
1724                         for (int i=0; i<books.size(); i++) {\r
1725                                 conn.getNotebookTable().updateNotebook(books.get(i), false);\r
1726                         }\r
1727                         conn.getSyncTable().deleteRecord("FullNotebookSync");\r
1728                 } catch (EDAMUserException e1) {\r
1729                         e1.printStackTrace();\r
1730                         status.message.emit(tr("User exception Listing notebooks."));\r
1731                         logger.log(logger.LOW, e1.getMessage());\r
1732                         return;\r
1733                 } catch (EDAMSystemException e1) {\r
1734                         e1.printStackTrace();\r
1735                         status.message.emit(tr("System exception Listing notebooks."));\r
1736                         logger.log(logger.LOW, e1.getMessage());\r
1737                         return;\r
1738                 } catch (TException e1) {\r
1739                         e1.printStackTrace();\r
1740                         status.message.emit(tr("Transaction exception Listing notebooks."));\r
1741                         logger.log(logger.LOW, e1.getMessage());\r
1742                         return;\r
1743                 }\r
1744     }\r
1745     private void downloadAllLinkedNotebooks(Client noteStore) {\r
1746         try {\r
1747                         List<LinkedNotebook> books = noteStore.listLinkedNotebooks(authToken);\r
1748                         logger.log(logger.LOW, "Linked notebooks found = " +books.size());\r
1749                         for (int i=0; i<books.size(); i++) {\r
1750                                 conn.getLinkedNotebookTable().updateNotebook(books.get(i), false);\r
1751                         }\r
1752                         conn.getSyncTable().deleteRecord("FullLinkedNotebookSync");\r
1753                 } catch (EDAMUserException e1) {\r
1754                         e1.printStackTrace();\r
1755                         status.message.emit(tr("User exception Listing linked notebooks."));\r
1756                         logger.log(logger.LOW, e1.getMessage());\r
1757                         return;\r
1758                 } catch (EDAMSystemException e1) {\r
1759                         e1.printStackTrace();\r
1760                         status.message.emit(tr("System exception Listing linked notebooks."));\r
1761                         logger.log(logger.LOW, e1.getMessage());\r
1762                         return;\r
1763                 } catch (TException e1) {\r
1764                         e1.printStackTrace();\r
1765                         status.message.emit(tr("Transaction exception Listing lineked notebooks."));\r
1766                         logger.log(logger.LOW, e1.getMessage());\r
1767                         return;\r
1768                 } catch (EDAMNotFoundException e1) {\r
1769                         e1.printStackTrace();\r
1770                         status.message.emit(tr("EDAM Not Found exception Listing linked notebooks."));\r
1771                         logger.log(logger.LOW, e1.getMessage());\r
1772                 }\r
1773     }\r
1774 \r
1775     \r
1776     private void downloadInkNoteImage(String guid, String authToken) {\r
1777                 String urlBase = noteStoreUrl.replace("/edam/note/", "/shard/") + "/res/"+guid+".ink?slice=";\r
1778 //              urlBase = "https://www.evernote.com/shard/s1/res/52b567a9-54ae-4a08-afc5-d5bae275b2a8.ink?slice=";\r
1779                 Integer slice = 1;\r
1780                 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, false);\r
1781                 conn.getInkImagesTable().expungeImage(r.getGuid());\r
1782                 int sliceCount = 1+((r.getHeight()-1)/480);\r
1783                 HttpClient http = new DefaultHttpClient();\r
1784         for (int i=0; i<sliceCount; i++) {\r
1785                 String url = urlBase + slice.toString();\r
1786                 HttpPost post = new HttpPost(url);\r
1787                 post.getParams().setParameter("auth", authToken);\r
1788                 List <NameValuePair> nvps = new ArrayList <NameValuePair>();\r
1789             nvps.add(new BasicNameValuePair("auth", authToken));\r
1790 \r
1791             try {\r
1792                                 post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));\r
1793                         } catch (UnsupportedEncodingException e1) {\r
1794                                 e1.printStackTrace();\r
1795                         }\r
1796                 try {\r
1797                         HttpResponse response = http.execute(post);\r
1798                         HttpEntity resEntity = response.getEntity();\r
1799                         InputStream is = resEntity.getContent();\r
1800                         QByteArray data = writeToFile(is);\r
1801                         conn.getInkImagesTable().saveImage(guid, slice, data);\r
1802                         } catch (ClientProtocolException e) {\r
1803                                 e.printStackTrace();\r
1804                         } catch (IOException e) {\r
1805                                 e.printStackTrace();\r
1806                         }\r
1807 \r
1808                         slice++;\r
1809         }\r
1810         http.getConnectionManager().shutdown(); \r
1811                 noteSignal.noteChanged.emit(r.getNoteGuid(), null);   // Signal to ivalidate note cache\r
1812     }\r
1813     \r
1814     \r
1815     public QByteArray writeToFile(InputStream iStream) throws IOException {\r
1816 \r
1817             File temp = File.createTempFile("nn-inknote-temp", ".png");\r
1818 \r
1819             // Save InputStream to the file.\r
1820             BufferedOutputStream fOut = null;\r
1821             try {\r
1822               fOut = new BufferedOutputStream(new FileOutputStream(temp));\r
1823               byte[] buffer = new byte[32 * 1024];\r
1824               int bytesRead = 0;\r
1825               while ((bytesRead = iStream.read(buffer)) != -1) {\r
1826                 fOut.write(buffer, 0, bytesRead);\r
1827               }\r
1828             }\r
1829             finally {\r
1830                 iStream.close();\r
1831                 fOut.close();\r
1832             }\r
1833             QFile tempFile = new QFile(temp.getAbsoluteFile().toString());\r
1834             tempFile.open(OpenModeFlag.ReadOnly);\r
1835             QByteArray data = tempFile.readAll();\r
1836             tempFile.close();\r
1837             tempFile.remove();\r
1838             return data;\r
1839     }\r
1840     \r
1841     \r
1842         //******************************************\r
1843         //* Begin syncing shared notebooks \r
1844         //******************************************\r
1845     private void syncLinkedNotebooks() {\r
1846         logger.log(logger.MEDIUM, "Authenticating linked Notebooks");\r
1847         status.message.emit(tr("Synchronizing shared notebooks."));\r
1848         List<LinkedNotebook> books = conn.getLinkedNotebookTable().getAll();\r
1849         \r
1850         errorSharedNotebooks.clear();\r
1851                 \r
1852         for (int i=0; i<books.size(); i++) {\r
1853                 if (errorSharedNotebooksIgnored.containsKey(books.get(i).getGuid()))\r
1854                         break;\r
1855                 try {\r
1856                         logger.log(logger.EXTREME, "Checking notebook: " +books.get(i).getShareName());\r
1857                                 long lastSyncDate = conn.getLinkedNotebookTable().getLastSequenceDate(books.get(i).getGuid());\r
1858                                 int lastSequenceNumber = conn.getLinkedNotebookTable().getLastSequenceNumber(books.get(i).getGuid());\r
1859 \r
1860                                 logger.log(logger.EXTREME, "Last Sequence Number on file: " +lastSequenceNumber);\r
1861                                 \r
1862                                 // Authenticate to the owner's shard\r
1863                                 String linkedNoteStoreUrl       = noteStoreUrlBase + books.get(i).getShardId();\r
1864                                 logger.log(logger.EXTREME, "linkedNoteStoreURL: " +linkedNoteStoreUrl);\r
1865                                 THttpClient linkedNoteStoreTrans        = new THttpClient(linkedNoteStoreUrl);\r
1866                                 TBinaryProtocol linkedNoteStoreProt     = new TBinaryProtocol(linkedNoteStoreTrans);\r
1867                                 Client linkedNoteStore = new NoteStore.Client(linkedNoteStoreProt, linkedNoteStoreProt);        \r
1868 \r
1869                                 linkedAuthResult = null;\r
1870                                 if (books.get(i).getShareKey() != null) {\r
1871                                         logger.log(logger.EXTREME, "Share Key Not Null: " +books.get(i).getShareKey());\r
1872                                         linkedAuthResult = linkedNoteStore.authenticateToSharedNotebook(books.get(i).getShareKey(), authToken);\r
1873                                         logger.log(logger.EXTREME, "Authentication Token" +linkedAuthResult.getAuthenticationToken());\r
1874                                 } else {\r
1875                                         logger.log(logger.EXTREME, "Share key is null");\r
1876                                         linkedAuthResult = new AuthenticationResult();\r
1877                                         linkedAuthResult.setAuthenticationToken("");\r
1878                                 }\r
1879                                 SyncState linkedSyncState = \r
1880                                         linkedNoteStore.getLinkedNotebookSyncState(linkedAuthResult.getAuthenticationToken(), books.get(i));\r
1881                                 if (linkedSyncState.getUpdateCount() > lastSequenceNumber) {\r
1882                                         logger.log(logger.EXTREME, "Remote changes found");\r
1883                                         if (lastSyncDate < linkedSyncState.getFullSyncBefore()) {\r
1884                                                 lastSequenceNumber = 0;\r
1885                                         } \r
1886                                         logger.log(logger.EXTREME, "Calling syncLinkedNotebook for " +books.get(i).getShareName());\r
1887                                         syncLinkedNotebook(linkedNoteStore, books.get(i), \r
1888                                                         lastSequenceNumber, linkedSyncState.getUpdateCount(), authToken);\r
1889                                 }\r
1890                         \r
1891                         // Synchronize local changes\r
1892                         syncLocalLinkedNoteChanges(linkedNoteStore, books.get(i));\r
1893                                 \r
1894                 } catch (EDAMUserException e) {\r
1895                         e.printStackTrace();\r
1896                 } catch (EDAMNotFoundException e) {\r
1897                         status.message.emit(tr("Error synchronizing \" " +\r
1898                                         books.get(i).getShareName()+"\". Please verify you still have access to that shared notebook."));\r
1899                         errorSharedNotebooks.add(books.get(i).getGuid());\r
1900                         errorSharedNotebooksIgnored.put(books.get(i).getGuid(), books.get(i).getGuid());\r
1901                         logger.log(logger.LOW, "Error synchronizing shared notebook.  EDAMNotFound: "+e.getMessage());\r
1902                         logger.log(logger.LOW, e.getStackTrace());\r
1903                         error = true;\r
1904                         e.printStackTrace();\r
1905                 } catch (EDAMSystemException e) {\r
1906                         error = true;\r
1907                         logger.log(logger.LOW, "System error authenticating against shared notebook. "+\r
1908                                         "Key: "+books.get(i).getShareKey() +" Error:" +e.getMessage());\r
1909                         e.printStackTrace();\r
1910                 } catch (TException e) {\r
1911                         error = true;\r
1912                         e.printStackTrace();\r
1913                 }\r
1914         }\r
1915         \r
1916         // Cleanup tags\r
1917         conn.getTagTable().removeUnusedLinkedTags();\r
1918         conn.getTagTable().cleanupTags();\r
1919         tagSignal.listChanged.emit();\r
1920         return;\r
1921         }\r
1922 \r
1923     \r
1924     //**************************************************************\r
1925     //* Linked notebook contents (from someone else's account)\r
1926     //*************************************************************\r
1927         private void syncLinkedNotebook(Client linkedNoteStore, LinkedNotebook book, int usn, int highSequence, String token) {\r
1928                 logger.log(logger.EXTREME, "Entering syncLinkedNotebook");\r
1929                 if (ignoreLinkedNotebooks.contains(book.getGuid()))\r
1930                         return;\r
1931                 List<Note> dirtyNotes = conn.getNoteTable().getDirtyLinkedNotes();\r
1932                 if (dirtyNoteGuids == null) \r
1933                         dirtyNoteGuids = new Vector<String>();\r
1934 \r
1935                 for (int i=0; i<dirtyNotes.size() && keepRunning; i++) {\r
1936                         dirtyNoteGuids.add(dirtyNotes.get(i).getGuid());\r
1937                 }\r
1938                 boolean fullSync = false;\r
1939                 if (usn == 0)\r
1940                         fullSync = true;\r
1941                 boolean syncError = false;\r
1942                 while (usn < highSequence && !syncError) {\r
1943                         refreshNeeded = true;\r
1944                         try {\r
1945                                 SyncChunk chunk = \r
1946                                         linkedNoteStore.getLinkedNotebookSyncChunk(token, book, usn, 10, fullSync);\r
1947                                 \r
1948                                 // Expunge notes\r
1949                                 syncExpungedNotes(chunk);\r
1950 \r
1951                                 logger.log(logger.EXTREME, "Syncing remote notes: " +chunk.getNotesSize());\r
1952                                 syncRemoteNotes(linkedNoteStore, chunk.getNotes(), fullSync, linkedAuthResult.getAuthenticationToken());\r
1953                                 logger.log(logger.EXTREME, "Finding new linked tags");\r
1954                                 findNewLinkedTags(linkedNoteStore, chunk.getNotes(), linkedAuthResult.getAuthenticationToken());\r
1955                                 // Sync resources\r
1956                                 logger.log(logger.EXTREME, "Synchronizing tags: " +chunk.getTagsSize());\r
1957                                 for (int i=0; i<chunk.getResourcesSize(); i++) {\r
1958                                         syncRemoteResource(linkedNoteStore, chunk.getResources().get(i), linkedAuthResult.getAuthenticationToken());\r
1959                                 }\r
1960                                 logger.log(logger.EXTREME, "Synchronizing linked notebooks: " +chunk.getNotebooksSize());\r
1961                                 syncRemoteLinkedNotebooks(linkedNoteStore, chunk.getNotebooks(), false, book);\r
1962                                 syncLinkedTags(chunk.getTags(), book.getGuid());\r
1963                                 \r
1964                                 // Go through & signal any notes that have changed so we can refresh the user's view\r
1965                                 for (int i=0; i<chunk.getNotesSize(); i++) \r
1966                                         noteSignal.noteChanged.emit(chunk.getNotes().get(i).getGuid(), null);\r
1967 \r
1968                                 // Expunge Notebook records\r
1969                                 logger.log(logger.EXTREME, "Expunging linked notebooks: " +chunk.getExpungedLinkedNotebooksSize());\r
1970                                 for (int i=0; i<chunk.getExpungedLinkedNotebooksSize(); i++) {\r
1971                                         conn.getLinkedNotebookTable().expungeNotebook(chunk.getExpungedLinkedNotebooks().get(i), false);\r
1972                                 }\r
1973                                 usn = chunk.getChunkHighUSN();\r
1974                                 conn.getLinkedNotebookTable().setLastSequenceDate(book.getGuid(),chunk.getCurrentTime());\r
1975                                 conn.getLinkedNotebookTable().setLastSequenceNumber(book.getGuid(),chunk.getChunkHighUSN());\r
1976                         } catch (EDAMUserException e) {\r
1977                                 syncError = true;\r
1978                                 status.message.emit(tr("EDAM UserException synchronizing linked notbook.  See the log for datails."));\r
1979                                 e.printStackTrace();\r
1980                                 logger.log(logger.LOW, tr("EDAM UserException synchronizing linked notbook ")+ e.getMessage());\r
1981                         } catch (EDAMSystemException e) {\r
1982                                 syncError = true;\r
1983                                 status.message.emit(tr("EDAM SystemException synchronizing linked notbook.  See the log for datails."));\r
1984                                 e.printStackTrace();\r
1985                                 logger.log(logger.LOW, tr("EDAM SystemException synchronizing linked notbook.  See the log for datails") +e.getMessage());\r
1986                         } catch (EDAMNotFoundException e) {\r
1987                                 syncError = true;\r
1988                                 status.message.emit(tr("Notebook URL not found. Removing notobook ") +book.getShareName());\r
1989                                 conn.getNotebookTable().deleteLinkedTags(book.getGuid());\r
1990                                 conn.getLinkedNotebookTable().expungeNotebook(book.getGuid(), false);\r
1991                                 logger.log(logger.LOW, tr("Notebook URL not found. Removing notobook ") +e.getMessage());\r
1992                         } catch (TException e) {\r
1993                                 syncError = true;\r
1994                                 status.message.emit(tr("EDAM TException synchronizing linked notbook.  See the log for datails."));\r
1995                                 e.printStackTrace();\r
1996                                 logger.log(logger.LOW, tr("EDAM TException synchronizing linked notbook.  See the log for datails." )+e.getMessage());\r
1997                         }\r
1998                 }\r
1999                 logger.log(logger.EXTREME, "leaving syncLinkedNotebook");\r
2000         }\r
2001         // Sync remote tags\r
2002         private void syncLinkedTags(List<Tag> tags, String notebookGuid) {\r
2003                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteTags");\r
2004                 if (tags != null) {\r
2005                         for (int i=0; i<tags.size() && keepRunning; i++) {\r
2006                                 conn.getTagTable().syncLinkedTag(tags.get(i), notebookGuid, false);\r
2007                         }\r
2008                 }\r
2009                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteTags");\r
2010         }\r
2011         \r
2012         // Sync notebooks from a linked notebook\r
2013         private void syncRemoteLinkedNotebooks(Client noteStore, List<Notebook> notebooks, boolean readOnly, LinkedNotebook linked) {\r
2014                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotebooks");\r
2015                 if (notebooks != null) {\r
2016                         for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
2017                                 try {\r
2018                                         logger.log(logger.EXTREME, "auth token:" +linkedAuthResult.getAuthenticationToken());\r
2019                                         if (!linkedAuthResult.getAuthenticationToken().equals("")) {\r
2020                                                 SharedNotebook s = noteStore.getSharedNotebookByAuth(linkedAuthResult.getAuthenticationToken());\r
2021                                                 logger.log(logger.EXTREME, "share key:"+s.getShareKey() +" notebookGuid" +s.getNotebookGuid());\r
2022                                                 conn.getLinkedNotebookTable().setNotebookGuid(s.getShareKey(), s.getNotebookGuid());\r
2023                                                 readOnly = !s.isNotebookModifiable();\r
2024                                         } else {\r
2025                                                 readOnly = true;\r
2026                                         }\r
2027                                         notebooks.get(i).setName(linked.getShareName());\r
2028                                         notebooks.get(i).setDefaultNotebook(false);\r
2029                                         conn.getNotebookTable().syncLinkedNotebook(notebooks.get(i), false, readOnly); \r
2030                                 } catch (EDAMUserException e) {\r
2031                                         readOnly = true;\r
2032                                         e.printStackTrace();\r
2033                                 } catch (EDAMNotFoundException e) {\r
2034                                         readOnly = true;\r
2035                                         e.printStackTrace();\r
2036                                 } catch (EDAMSystemException e) {\r
2037                                         readOnly = true;\r
2038                                         e.printStackTrace();\r
2039                                 } catch (TException e) {\r
2040                                         readOnly = true;\r
2041                                         e.printStackTrace();\r
2042                                 }\r
2043 \r
2044                         }\r
2045                 }                       \r
2046                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotebooks");\r
2047         }\r
2048 \r
2049         private void findNewLinkedTags(Client noteStore, List<Note> newNotes, String token) {\r
2050                 if (newNotes == null)\r
2051                         return;\r
2052                 for (int i=0; i<newNotes.size(); i++) {\r
2053                         Note n = newNotes.get(i);\r
2054                         for (int j=0; j<n.getTagGuidsSize(); j++) {\r
2055                                 String tag = n.getTagGuids().get(j);\r
2056                                 if (!conn.getTagTable().exists(tag)) {\r
2057                                         Tag newTag;\r
2058                                         try {\r
2059                                                 newTag = noteStore.getTag(token, tag);\r
2060                                                 conn.getTagTable().addTag(newTag, false);\r
2061                                         } catch (EDAMUserException e) {\r
2062                                                 e.printStackTrace();\r
2063                                         } catch (EDAMSystemException e) {\r
2064                                                 e.printStackTrace();\r
2065                                         } catch (EDAMNotFoundException e) {\r
2066                                                 e.printStackTrace();\r
2067                                         } catch (TException e) {\r
2068                                                 e.printStackTrace();\r
2069                                         }\r
2070                                         \r
2071                                 }\r
2072                         }\r
2073                 }\r
2074         }\r
2075 \r
2076         // Synchronize changes locally done to linked notes\r
2077         private void syncLocalLinkedNoteChanges(Client noteStore, LinkedNotebook book) {\r
2078                 logger.log(logger.EXTREME, "Entering SyncRunner.synclocalLinkedNoteChanges");\r
2079                 String notebookGuid = conn.getLinkedNotebookTable().getNotebookGuid(book.getGuid());\r
2080                 logger.log(logger.EXTREME, "Finding changes for " +book.getShareName() +":" +book.getGuid() + ":" +notebookGuid);\r
2081                 List<Note> notes = conn.getNoteTable().getDirtyLinked(notebookGuid);\r
2082                 logger.log(logger.EXTREME, "Number of changes found: " +notes.size());\r
2083                 for (int i=0; i<notes.size(); i++) {\r
2084                         logger.log(logger.EXTREME, "Calling syncLocalNote with key " +linkedAuthResult.getAuthenticationToken());\r
2085                         syncLocalNote(noteStore, notes.get(i), linkedAuthResult.getAuthenticationToken());\r
2086                 }\r
2087                 logger.log(logger.EXTREME, "Leaving SyncRunner.synclocalLinkedNoteChanges");\r
2088         }\r
2089 \r
2090 }\r