OSDN Git Service

Update merge with local branch. Changes:
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / threads / SyncRunner.java
1 /*\r
2  * This file is part of NeverNote \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.net.UnknownHostException;\r
22 import java.util.ArrayList;\r
23 import java.util.Calendar;\r
24 import java.util.Date;\r
25 import java.util.GregorianCalendar;\r
26 import java.util.List;\r
27 import java.util.Vector;\r
28 import java.util.concurrent.LinkedBlockingQueue;\r
29 \r
30 import org.apache.thrift.TException;\r
31 import org.apache.thrift.protocol.TBinaryProtocol;\r
32 import org.apache.thrift.transport.THttpClient;\r
33 import org.apache.thrift.transport.TTransportException;\r
34 \r
35 import com.evernote.edam.error.EDAMNotFoundException;\r
36 import com.evernote.edam.error.EDAMSystemException;\r
37 import com.evernote.edam.error.EDAMUserException;\r
38 import com.evernote.edam.notestore.NoteStore;\r
39 import com.evernote.edam.notestore.SyncChunk;\r
40 import com.evernote.edam.notestore.SyncState;\r
41 import com.evernote.edam.type.Data;\r
42 import com.evernote.edam.type.Note;\r
43 import com.evernote.edam.type.Notebook;\r
44 import com.evernote.edam.type.Resource;\r
45 import com.evernote.edam.type.SavedSearch;\r
46 import com.evernote.edam.type.Tag;\r
47 import com.evernote.edam.type.User;\r
48 import com.evernote.edam.userstore.AuthenticationResult;\r
49 import com.evernote.edam.userstore.UserStore;\r
50 import com.trolltech.qt.core.QObject;\r
51 import com.trolltech.qt.gui.QMessageBox;\r
52 \r
53 import cx.fbn.nevernote.signals.NoteIndexSignal;\r
54 import cx.fbn.nevernote.signals.NoteResourceSignal;\r
55 import cx.fbn.nevernote.signals.NoteSignal;\r
56 import cx.fbn.nevernote.signals.NotebookSignal;\r
57 import cx.fbn.nevernote.signals.SavedSearchSignal;\r
58 import cx.fbn.nevernote.signals.StatusSignal;\r
59 import cx.fbn.nevernote.signals.SyncSignal;\r
60 import cx.fbn.nevernote.signals.TagSignal;\r
61 import cx.fbn.nevernote.sql.DatabaseConnection;\r
62 import cx.fbn.nevernote.sql.DeletedItemRecord;\r
63 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
64 \r
65 public class SyncRunner extends QObject implements Runnable {\r
66         \r
67         private final ApplicationLogger logger;\r
68                 private DatabaseConnection              conn;\r
69                 private boolean                                 idle;\r
70                 public boolean                                  error;\r
71                 public volatile boolean                 isConnected;\r
72                 public volatile boolean                 keepRunning;\r
73                 public volatile String                  authToken;\r
74                 private long                                    evernoteUpdateCount;\r
75                 \r
76                 public volatile NoteStore.Client                noteStore;\r
77                 private UserStore.Client                                userStore;\r
78                 \r
79                 public volatile StatusSignal                    status;\r
80                 public volatile TagSignal                               tagSignal;\r
81                 public volatile NotebookSignal                  notebookSignal;\r
82                 public volatile NoteIndexSignal                 noteIndexSignal;\r
83                 public volatile NoteSignal                              noteSignal;\r
84                 public volatile SavedSearchSignal               searchSignal;\r
85                 public volatile NoteResourceSignal              resourceSignal;\r
86                 public volatile SyncSignal                              syncSignal;\r
87                 public volatile boolean                                 authRefreshNeeded;\r
88                 public volatile boolean                                 syncNeeded;\r
89                 public volatile boolean                                 disableUploads;\r
90                 public volatile boolean                                 syncDeletedContent;\r
91                 private volatile Vector<String>                 dirtyNoteGuids;\r
92                 \r
93             public volatile String username = ""; \r
94             public volatile String password = ""; \r
95                 public volatile String userStoreUrl;\r
96             private final static String consumerKey = "baumgarte"; \r
97             private final static String consumerSecret = "eb8b5740e17cb55f";\r
98             public String noteStoreUrlBase;\r
99             private THttpClient userStoreTrans;\r
100             private TBinaryProtocol userStoreProt;\r
101             private AuthenticationResult authResult;\r
102             private User user; \r
103             private long authTimeRemaining;\r
104             public long authRefreshTime;\r
105             public long failedRefreshes = 0;\r
106             public  THttpClient noteStoreTrans;\r
107             public TBinaryProtocol noteStoreProt;\r
108             public String noteStoreUrl;\r
109             public long sequenceDate;\r
110             public int updateSequenceNumber;\r
111             private boolean refreshNeeded;\r
112             private volatile LinkedBlockingQueue<String> workQueue;\r
113 //              private static int MAX_EMPTY_QUEUE_COUNT = 1;\r
114                 private static int MAX_QUEUED_WAITING = 1000;\r
115                 String dbuid;\r
116                 String dburl;\r
117                 String dbpswd;\r
118                 String dbcpswd;\r
119         \r
120                 \r
121                 \r
122         public SyncRunner(String logname, String u, String uid, String pswd, String cpswd) {\r
123                 logger = new ApplicationLogger(logname);\r
124                 \r
125                 noteSignal = new NoteSignal();\r
126                 status = new StatusSignal();\r
127                 tagSignal = new TagSignal();\r
128                 notebookSignal = new NotebookSignal();\r
129                 noteIndexSignal = new NoteIndexSignal();\r
130                 noteSignal = new NoteSignal();\r
131                 searchSignal = new SavedSearchSignal();\r
132                 syncSignal = new SyncSignal();\r
133                 resourceSignal = new NoteResourceSignal();\r
134                 dbuid = uid;\r
135                 dburl = u;\r
136                 dbpswd = pswd;\r
137                 dbcpswd = cpswd;\r
138 //              this.setAutoDelete(false);\r
139                 \r
140                 isConnected = false;\r
141                 syncNeeded = false;\r
142                 authRefreshNeeded = false;\r
143                 keepRunning = true;\r
144                 idle = true;\r
145                 noteStore = null;\r
146                 userStore = null;\r
147                 authToken = null;\r
148                 disableUploads = false;\r
149 //              setAutoDelete(false);\r
150                 workQueue=new LinkedBlockingQueue<String>(MAX_QUEUED_WAITING);\r
151         }\r
152         @Override\r
153         public void run() {\r
154                 try {\r
155                         logger.log(logger.EXTREME, "Starting thread");\r
156                         conn = new DatabaseConnection(logger, dburl, dbuid, dbpswd, dbcpswd);\r
157                         while(keepRunning) {\r
158                                 String work = workQueue.take();\r
159                                 logger.log(logger.EXTREME, "Work found: " +work);\r
160                                 if (work.equalsIgnoreCase("stop"))\r
161                                         return;\r
162                                 idle=false;\r
163                                 error=false;\r
164                                 if (authRefreshNeeded == true) {\r
165                                         logger.log(logger.EXTREME, "Refreshing connection");\r
166                                         refreshConnection();\r
167                                 }\r
168                                 if (syncNeeded) {\r
169                                         logger.log(logger.EXTREME, "SyncNeeded is true");\r
170                                         refreshNeeded=false;\r
171                                         sequenceDate = conn.getSyncTable().getLastSequenceDate();\r
172                                         updateSequenceNumber = conn.getSyncTable().getUpdateSequenceNumber();\r
173                                         try {\r
174                                                 logger.log(logger.EXTREME, "Beginning sync");\r
175                                                 evernoteSync();\r
176                                                 logger.log(logger.EXTREME, "Sync finished");\r
177                                         } catch (UnknownHostException e) {\r
178                                                 status.message.emit(e.getMessage());\r
179                                         }\r
180                                 }\r
181                                 dirtyNoteGuids = null;\r
182                                 idle=true;\r
183                                 logger.log(logger.EXTREME, "Signaling refresh finished.  refreshNeeded=" +refreshNeeded);\r
184                                 syncSignal.finished.emit(refreshNeeded);\r
185                         }\r
186                 }       \r
187                 catch (InterruptedException e1) {\r
188                         e1.printStackTrace();\r
189                 }\r
190                 conn.dbShutdown();\r
191         }\r
192 \r
193         \r
194         public DatabaseConnection getConnection() {\r
195                 return conn;\r
196         }\r
197 \r
198         public boolean isIdle() {\r
199                 return idle;\r
200         }\r
201 \r
202 \r
203         public void setConnected(boolean c) {\r
204                 isConnected = c;\r
205         }\r
206         public void setKeepRunning(boolean r) {\r
207                 logger.log(logger.EXTREME, "Setting keepRunning=" +r);\r
208                 keepRunning = r;\r
209         }\r
210         public void setNoteStore(NoteStore.Client c) {\r
211                 logger.log(logger.EXTREME, "Setting NoteStore in sync thread");\r
212                 noteStore = c;\r
213         }\r
214         public void setUserStore(UserStore.Client c) {\r
215                 logger.log(logger.EXTREME, "Setting UserStore in sync thread");\r
216                 userStore = c;\r
217         }\r
218 \r
219         public void setEvernoteUpdateCount(long s) {\r
220                 logger.log(logger.EXTREME, "Setting Update Count in sync thread");\r
221                 evernoteUpdateCount = s;\r
222         }\r
223         \r
224         //***************************************************************\r
225     //***************************************************************\r
226     //** These functions deal with Evernote communications\r
227     //***************************************************************\r
228     //***************************************************************\r
229         // Synchronize changes with Evernote\r
230         @SuppressWarnings("unused")\r
231         private void evernoteSync() throws java.net.UnknownHostException {\r
232                 logger.log(logger.HIGH, "Entering SyncRunner.evernoteSync");\r
233 \r
234                 if (isConnected && keepRunning) {\r
235                         error = false;\r
236                         logger.log(logger.EXTREME, "Synchronizing with Evernote");\r
237                         status.message.emit(tr("Synchronizing with Evernote"));\r
238                         \r
239                         // Get user information\r
240                         try {\r
241                                 logger.log(logger.EXTREME, "getting user from userstore");\r
242                                 User user = userStore.getUser(authToken);\r
243                                 logger.log(logger.EXTREME, "Saving user information");\r
244                                 syncSignal.saveUserInformation.emit(user);\r
245                         } catch (EDAMUserException e1) {\r
246                                 e1.printStackTrace();\r
247                                 status.message.emit(tr("User exception getting user account information.  Aborting sync and disconnecting"));\r
248                                 syncSignal.errorDisconnect.emit();\r
249                                 enDisconnect();\r
250                                 return;\r
251                         } catch (EDAMSystemException e1) {\r
252                                 e1.printStackTrace();\r
253                                 status.message.emit(tr("System error user account information.  Aborting sync and disconnecting!"));\r
254                                 syncSignal.errorDisconnect.emit();\r
255                                 enDisconnect();\r
256                                 return;\r
257                         } catch (TException e1) {\r
258                                 e1.printStackTrace();\r
259                                 syncSignal.errorDisconnect.emit();\r
260                                 status.message.emit(tr("Transaction error getting user account information.  Aborting sync and disconnecting!"));\r
261                                 enDisconnect();\r
262                                 return;\r
263                         }\r
264                         \r
265                         // Get sync state\r
266                         SyncState syncState = null;\r
267                         try {   \r
268                                 logger.log(logger.EXTREME, "Getting sync state");\r
269                                 syncState = noteStore.getSyncState(authToken);  \r
270                                 syncSignal.saveUploadAmount.emit(syncState.getUploaded());\r
271                                 syncSignal.saveEvernoteUpdateCount.emit(syncState.getUpdateCount());\r
272                                 evernoteUpdateCount = syncState.getUpdateCount();\r
273                         } catch (EDAMUserException e) {\r
274                                 e.printStackTrace();\r
275                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
276                                 syncSignal.errorDisconnect.emit();\r
277                                 enDisconnect();\r
278                                 return;\r
279                         } catch (EDAMSystemException e) {\r
280                                 e.printStackTrace();\r
281                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
282                                 syncSignal.errorDisconnect.emit();\r
283                                 enDisconnect();\r
284                                 return;\r
285                         } catch (TException e) {\r
286                                 e.printStackTrace();\r
287                                 status.message.emit(tr("Error getting sync state! Aborting sync and disconnecting!"));\r
288                                 syncSignal.errorDisconnect.emit();\r
289                                 enDisconnect();\r
290                                 return;\r
291                         }\r
292                         \r
293                         if (syncState == null) {\r
294                                 logger.log(logger.EXTREME, "Sync State is null");\r
295                                 status.message.emit(tr("Syncronization Error!"));\r
296                                 return;\r
297                         }\r
298 \r
299                         // Determine what to do. \r
300                         // If we need to do a full sync.\r
301                         logger.log(logger.LOW, "Full Sequence Before: " +syncState.getFullSyncBefore());\r
302                         logger.log(logger.LOW, "Last Sequence Date: " +sequenceDate);\r
303                         if (syncState.getFullSyncBefore() > sequenceDate) {\r
304                                 logger.log(logger.EXTREME, "Full sequence date has expired");\r
305                                 sequenceDate = 0;\r
306                                 conn.getSyncTable().setLastSequenceDate(0);\r
307                                 updateSequenceNumber = 0;\r
308                                 conn.getSyncTable().setUpdateSequenceNumber(0);\r
309                         }\r
310 \r
311                         // If there are remote changes\r
312                         logger.log(logger.LOW, "Update Count: " +syncState.getUpdateCount());\r
313                         logger.log(logger.LOW, "Last Update Count: " +updateSequenceNumber);\r
314                         \r
315                         if (syncState.getUpdateCount() > updateSequenceNumber) {\r
316                                 logger.log(logger.EXTREME, "Refresh needed is true");\r
317                                 refreshNeeded = true;\r
318                                 logger.log(logger.EXTREME, "Downloading changes");\r
319                                 syncRemoteToLocal();\r
320                         }\r
321                         \r
322                         if (!disableUploads) {\r
323                                 logger.log(logger.EXTREME, "Uploading changes");\r
324                                 // Synchronize remote changes\r
325                                 if (!error)\r
326                                         syncExpunged();\r
327                                 if (!error)\r
328                                         syncLocalTags();\r
329                                 if (!error)\r
330                                         syncLocalNotebooks();\r
331                                 if (!error) \r
332                                         syncDeletedNotes();\r
333                                 if (!error)\r
334                                         syncLocalNotes();\r
335                                 if (!error)\r
336                                         syncLocalSavedSearches();\r
337                         }\r
338                         if (refreshNeeded)\r
339                                 syncSignal.refreshLists.emit();\r
340                         if (!error) {\r
341                                 logger.log(logger.EXTREME, "Sync completed.  Errors=" +error);\r
342                                 if (!disableUploads) \r
343                                         status.message.emit(tr("Synchronizing complete"));\r
344                                 else\r
345                                         status.message.emit(tr("Download syncronization complete.  Uploads have been disabled."));\r
346                                 \r
347                                 logger.log(logger.EXTREME, "Saving sync time");\r
348                                 if (syncState.getCurrentTime() > sequenceDate)\r
349                                         sequenceDate = syncState.getCurrentTime();\r
350                                 if (syncState.getUpdateCount() > updateSequenceNumber)\r
351                                         updateSequenceNumber = syncState.getUpdateCount();\r
352                                 conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
353                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
354                         }\r
355                 }\r
356                 logger.log(logger.HIGH, "Leaving SyncRunner.evernoteSync");\r
357         }\r
358         // Sync deleted items with Evernote\r
359         private void syncExpunged() {\r
360                 logger.log(logger.HIGH, "Entering SyncRunner.syncExpunged");\r
361                 \r
362                 List<DeletedItemRecord> expunged = conn.getDeletedTable().getAllDeleted();\r
363                 boolean error = false;\r
364                 for (int i=0; i<expunged.size() && keepRunning; i++) {\r
365                         \r
366                         if (authRefreshNeeded)\r
367                                 refreshConnection();\r
368 \r
369                         try {\r
370                                 if (expunged.get(i).type.equalsIgnoreCase("TAG")) {\r
371                                         logger.log(logger.EXTREME, "Tag expunged");\r
372                                         updateSequenceNumber = noteStore.expungeTag(authToken, expunged.get(i).guid);\r
373                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
374                                         \r
375                                 }\r
376                                 if      (expunged.get(i).type.equalsIgnoreCase("NOTEBOOK")) {\r
377                                         logger.log(logger.EXTREME, "Notebook expunged");\r
378                                         updateSequenceNumber = noteStore.expungeNotebook(authToken, expunged.get(i).guid);\r
379                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
380                                 }\r
381                                 if (expunged.get(i).type.equalsIgnoreCase("NOTE")) {\r
382                                         logger.log(logger.EXTREME, "Note expunged");\r
383                                         updateSequenceNumber = noteStore.deleteNote(authToken, expunged.get(i).guid);\r
384                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
385                                 }\r
386                                 if (expunged.get(i).type.equalsIgnoreCase("SAVEDSEARCH")) {\r
387                                         logger.log(logger.EXTREME, "saved search expunged");\r
388                                         updateSequenceNumber = noteStore.expungeSearch(authToken, expunged.get(i).guid);\r
389                                         conn.getSyncTable().setLastSequenceDate(sequenceDate);\r
390                                 }\r
391                         } catch (EDAMUserException e) {\r
392                                 logger.log(logger.LOW, "EDAM User Excepton in syncExpunged: " +expunged.get(i).guid);\r
393                                 logger.log(logger.LOW, e.getStackTrace());\r
394                                 error = true;\r
395                         } catch (EDAMSystemException e) {\r
396                                 logger.log(logger.LOW, "EDAM System Excepton in syncExpunged: "+expunged.get(i).guid);\r
397                                 logger.log(logger.LOW, e.getStackTrace());\r
398                                 error=true;\r
399                         } catch (EDAMNotFoundException e) {\r
400                                 logger.log(logger.LOW, "EDAM Not Found Excepton in syncExpunged: "+expunged.get(i).guid);\r
401 //                              logger.log(logger.LOW, e.getStackTrace());\r
402                                 //error=true;\r
403                         } catch (TException e) {\r
404                                 logger.log(logger.LOW, "EDAM TExcepton in syncExpunged: "+expunged.get(i).guid);\r
405                                 logger.log(logger.LOW, e.getStackTrace());\r
406                                 error=true;\r
407                         }\r
408                 }\r
409                 if (!error)\r
410                         conn.getDeletedTable().expungeAllDeletedRecords();\r
411                 \r
412                 logger.log(logger.HIGH, "Leaving SyncRunner.syncExpunged");\r
413 \r
414         }\r
415         private void syncDeletedNotes() {\r
416                 if (syncDeletedContent)\r
417                         return;\r
418                 logger.log(logger.HIGH, "Entering SyncRunner.syncDeletedNotes");\r
419                 status.message.emit(tr("Synchronizing deleted notes."));\r
420 \r
421                 List<Note> notes = conn.getNoteTable().getDirty();\r
422                 // Sync the local notebooks with Evernote's\r
423                 for (int i=0; i<notes.size() && keepRunning; i++) {\r
424                         \r
425                         if (authRefreshNeeded)\r
426                                 refreshConnection();\r
427                         \r
428                         Note enNote = notes.get(i);\r
429                         try {\r
430                                 if (enNote.getUpdateSequenceNum() > 0 && (enNote.isActive() == false || enNote.getDeleted() > 0)) {\r
431                                         if (syncDeletedContent) {\r
432                                                 logger.log(logger.EXTREME, "Deleted note found & synch content selected");\r
433                                                 Note delNote = conn.getNoteTable().getNote(enNote.getGuid(), true, true, true, true, true);\r
434                                                 delNote = getNoteContent(delNote);\r
435                                                 delNote = noteStore.updateNote(authToken, delNote);\r
436                                                 enNote.setUpdateSequenceNum(delNote.getUpdateSequenceNum());\r
437                                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());\r
438                                         } else {\r
439                                                 logger.log(logger.EXTREME, "Deleted note found & sync content not selected");\r
440                                                 int usn = noteStore.deleteNote(authToken, enNote.getGuid());\r
441                                                 enNote.setUpdateSequenceNum(usn);\r
442                                                 conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());                                                \r
443                                         }\r
444                                         logger.log(logger.EXTREME, "Resetting deleted dirty flag");\r
445                                         conn.getNoteTable().resetDirtyFlag(enNote.getGuid());\r
446                                         updateSequenceNumber = enNote.getUpdateSequenceNum();\r
447                                         logger.log(logger.EXTREME, "Saving sequence number");\r
448                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
449                                 }                               \r
450                         } catch (EDAMUserException e) {\r
451                                 //logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotes "+e);\r
452                                 //status.message.emit("Error sending local note: " +e.getParameter());\r
453                                 //logger.log(logger.LOW, e.toString()); \r
454                                 //error = true;\r
455                         } catch (EDAMSystemException e) {\r
456                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotes "+e);\r
457                                 status.message.emit(tr("Error: ") +e);\r
458                                 logger.log(logger.LOW, e.toString());           \r
459                                 error = true;\r
460                         } catch (EDAMNotFoundException e) {\r
461                                 //logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotes " +e);\r
462                                 //status.message.emit("Error deleting local note: " +e +" - Continuing");\r
463                                 //logger.log(logger.LOW, e.toString());         \r
464                                 //error = true;\r
465                         } catch (TException e) {\r
466                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotes "+e);\r
467                                 status.message.emit(tr("Error sending local note: ") +e);\r
468                                 logger.log(logger.LOW, e.toString());   \r
469                                 error = true;\r
470                         }               \r
471                 }\r
472         }\r
473         // Sync notes with Evernote\r
474         private void syncLocalNotes() {\r
475                 logger.log(logger.HIGH, "Entering SyncRunner.syncNotes");\r
476                 status.message.emit(tr("Sending local notes."));\r
477 \r
478                 List<Note> notes = conn.getNoteTable().getDirty();\r
479                 // Sync the local notebooks with Evernote's\r
480                 for (int i=0; i<notes.size() && keepRunning; i++) {\r
481                         \r
482                         if (authRefreshNeeded)\r
483                                 refreshConnection();\r
484                         \r
485                         Note enNote = notes.get(i);\r
486                         if (enNote.isActive()) {\r
487                                 try {\r
488                                         logger.log(logger.EXTREME, "Active dirty note found - non new");\r
489                                         if (enNote.getUpdateSequenceNum() > 0) {\r
490                                                 enNote = getNoteContent(enNote);\r
491                                                 logger.log(logger.MEDIUM, "Updating note : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
492                                                 enNote = noteStore.updateNote(authToken, enNote);\r
493                                         } else { \r
494                                                 logger.log(logger.EXTREME, "Active dirty found - new note");\r
495                                                 logger.log(logger.MEDIUM, "Creating note : "+ enNote.getGuid() +" <title>" +enNote.getTitle()+"</title>");\r
496                                                 String oldGuid = enNote.getGuid();\r
497                                                 enNote = getNoteContent(enNote);\r
498                                                 enNote = noteStore.createNote(authToken, enNote);\r
499                                                 noteSignal.guidChanged.emit(oldGuid, enNote.getGuid());\r
500                                                 conn.getNoteTable().updateNoteGuid(oldGuid, enNote.getGuid());\r
501                                         }\r
502                                         updateSequenceNumber = enNote.getUpdateSequenceNum();\r
503                                         logger.log(logger.EXTREME, "Saving note");\r
504                                         conn.getNoteTable().updateNoteSequence(enNote.getGuid(), enNote.getUpdateSequenceNum());\r
505                                         List<Resource> rl = enNote.getResources();\r
506                                         logger.log(logger.EXTREME, "Getting note resources");\r
507                                         for (int j=0; j<enNote.getResourcesSize() && keepRunning; j++) {\r
508                                                 Resource newRes = rl.get(j);\r
509                                                 Data d = newRes.getData();\r
510                                                 if (d!=null) {  \r
511                                                         logger.log(logger.EXTREME, "Calculating resource hash");\r
512                                                         String hash = byteArrayToHexString(d.getBodyHash());\r
513                                                         logger.log(logger.EXTREME, "updating resources by hash");\r
514                                                         String oldGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(enNote.getGuid(), hash);\r
515                                                         conn.getNoteTable().updateNoteResourceGuidbyHash(enNote.getGuid(), newRes.getGuid(), hash);\r
516                                                         resourceSignal.resourceGuidChanged.emit(enNote.getGuid(), oldGuid, newRes.getGuid());\r
517                                                 }\r
518                                         }\r
519                                         logger.log(logger.EXTREME, "Resetting note dirty flag");\r
520                                         conn.getNoteTable().resetDirtyFlag(enNote.getGuid());\r
521                                         updateSequenceNumber = enNote.getUpdateSequenceNum();\r
522                                         logger.log(logger.EXTREME, "Emitting note sequence number change");\r
523                                         conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
524 \r
525                                 } catch (EDAMUserException e) {\r
526                                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotes "+e);\r
527                                         status.message.emit(tr("Error sending local note: ")     +e.getParameter());\r
528                                         logger.log(logger.LOW, e.toString());   \r
529                                         error = true;\r
530                                 } catch (EDAMSystemException e) {\r
531                                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotes "+e);\r
532                                         status.message.emit(tr("Error: ") +e);\r
533                                         logger.log(logger.LOW, e.toString());           \r
534                                         error = true;\r
535                                 } catch (EDAMNotFoundException e) {\r
536                                         logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotes " +e);\r
537                                         status.message.emit(tr("Error sending local note: ") +e);\r
538                                         logger.log(logger.LOW, e.toString());   \r
539                                         error = true;\r
540                                 } catch (TException e) {\r
541                                         logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotes "+e);\r
542                                         status.message.emit(tr("Error sending local note: ") +e);\r
543                                         logger.log(logger.LOW, e.toString());   \r
544                                         error = true;\r
545                                 }\r
546                         }\r
547                 }\r
548                 logger.log(logger.HIGH, "Entering SyncRunner.syncNotes");\r
549 \r
550         }\r
551         // Sync Notebooks with Evernote\r
552         private void syncLocalNotebooks() {\r
553                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalNotebooks");\r
554                 \r
555                 status.message.emit(tr("Sending local notebooks."));\r
556                 List<Notebook> remoteList = new ArrayList<Notebook>();\r
557                 try {\r
558                         logger.log(logger.EXTREME, "Getting remote notebooks to compare with local");\r
559                         remoteList = noteStore.listNotebooks(authToken);\r
560                 } catch (EDAMUserException e1) {\r
561                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotebooks getting remote Notebook List");\r
562                         status.message.emit(tr("Error: ") +e1);\r
563                         logger.log(logger.LOW, e1.toString());          \r
564                         error = true;\r
565                 } catch (EDAMSystemException e1) {\r
566                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotebooks getting remote Notebook List");\r
567                         status.message.emit(tr("Error: ") +e1);\r
568                         logger.log(logger.LOW, e1.toString());  \r
569                         error = true;\r
570                 } catch (TException e1) {\r
571                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalNotebooks getting remote Notebook List");\r
572                         status.message.emit(tr("Error: ") +e1);\r
573                         logger.log(logger.LOW, e1.toString());  \r
574                         error = true;\r
575                 }\r
576                 logger.log(logger.EXTREME, "Getting local dirty notebooks");\r
577                 List<Notebook> notebooks = conn.getNotebookTable().getDirty();\r
578                 int sequence;\r
579                 // Sync the local notebooks with Evernote's\r
580                 for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
581                         \r
582                         if (authRefreshNeeded)\r
583                                 refreshConnection();\r
584                         \r
585                         Notebook enNotebook = notebooks.get(i);\r
586                         try {\r
587                                 if (enNotebook.getUpdateSequenceNum() > 0) {\r
588                                         logger.log(logger.EXTREME, "Existing notebook is dirty");\r
589                                         sequence = noteStore.updateNotebook(authToken, enNotebook);\r
590                                 } else {\r
591                                         logger.log(logger.EXTREME, "New dirty notebook found");\r
592                                         String oldGuid = enNotebook.getGuid();\r
593                                         boolean found = false;\r
594                                         \r
595                                         // Look for a notebook with the same name.  If one is found, we don't need \r
596                                         // to create another one\r
597                                         logger.log(logger.EXTREME, "Looking for matching notebook name");\r
598                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
599                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enNotebook.getName())) {\r
600                                                         enNotebook = remoteList.get(k);\r
601                                                         logger.log(logger.EXTREME, "Matching notebook found");\r
602                                                         found = true;\r
603                                                 }\r
604                                         }\r
605                                         if (!found)\r
606                                                 enNotebook = noteStore.createNotebook(authToken, enNotebook);\r
607                                         \r
608                                         logger.log(logger.EXTREME, "Updating notebook in database");\r
609                                         conn.getNotebookTable().updateNotebookGuid(oldGuid, enNotebook.getGuid());\r
610                                         sequence = enNotebook.getUpdateSequenceNum();\r
611                                 }\r
612                                 logger.log(logger.EXTREME, "Updating notebook sequence in database");\r
613                                 conn.getNotebookTable().updateNotebookSequence(enNotebook.getGuid(), sequence);\r
614                                 logger.log(logger.EXTREME, "Resetting dirty flag in notebook");\r
615                                 conn.getNotebookTable().resetDirtyFlag(enNotebook.getGuid());\r
616                                 updateSequenceNumber = sequence;\r
617                                 logger.log(logger.EXTREME, "Emitting sequence number to main thread");\r
618                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
619                         } catch (EDAMUserException e) {\r
620                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalNotebooks");\r
621                                 logger.log(logger.LOW, e.toString());   \r
622                                 error = true;\r
623                         } catch (EDAMSystemException e) {\r
624                                 logger.log(logger.LOW, "*** EDAM System Excepton syncLocalNotebooks");\r
625                                 logger.log(logger.LOW, e.toString());           \r
626                                 error = true;\r
627                         } catch (EDAMNotFoundException e) {\r
628                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalNotebooks");\r
629                                 logger.log(logger.LOW, e.toString());           \r
630                                 error = true;\r
631                         } catch (TException e) {\r
632                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalNotebooks");\r
633                                 logger.log(logger.LOW, e.toString());   \r
634                                 error = true;\r
635                         }               \r
636                 }\r
637                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalNotebooks");\r
638 \r
639         }\r
640         // Sync Tags with Evernote\r
641         private void syncLocalTags() {\r
642                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalTags");\r
643                 List<Tag> remoteList = new ArrayList<Tag>();\r
644                 status.message.emit(tr("Sending local tags."));\r
645                 \r
646                 try {\r
647                         logger.log(logger.EXTREME, "Getting remote tags to compare names with the local tags");\r
648                         remoteList = noteStore.listTags(authToken);\r
649                 } catch (EDAMUserException e1) {\r
650                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags getting remote Tag List");\r
651                         status.message.emit(tr("Error: ") +e1);\r
652                         logger.log(logger.LOW, e1.toString());  \r
653                         error = true;\r
654                 } catch (EDAMSystemException e1) {\r
655                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalTags getting remote Tag List");\r
656                         status.message.emit(tr("Error: ") +e1);\r
657                         logger.log(logger.LOW, e1.toString());          \r
658                         error = true;\r
659                 } catch (TException e1) {\r
660                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalTags getting remote Tag List");\r
661                         status.message.emit(tr("Error: ") +e1);\r
662                         logger.log(logger.LOW, e1.toString());  \r
663                         error = true;\r
664                 }               \r
665                 \r
666                 int sequence;\r
667                 \r
668                 Tag enTag = findNextTag();\r
669                 while(enTag!=null) {\r
670                         if (authRefreshNeeded)\r
671                                 refreshConnection();\r
672 \r
673                         try {\r
674                                 if (enTag.getUpdateSequenceNum() > 0) {\r
675                                         logger.log(logger.EXTREME, "Updating tag");\r
676                                         sequence = noteStore.updateTag(authToken, enTag);\r
677                                 } else {\r
678                                         \r
679                                         // Look for a tag with the same name.  If one is found, we don't need \r
680                                         // to create another one\r
681                                         logger.log(logger.EXTREME, "New tag.  Comparing with remote names");\r
682                                         boolean found = false;\r
683                                         String oldGuid = enTag.getGuid();\r
684                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
685                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enTag.getName())) {\r
686                                                         conn.getTagTable().updateTagGuid(enTag.getGuid(), remoteList.get(k).getGuid());\r
687                                                         enTag = remoteList.get(k);\r
688                                                         logger.log(logger.EXTREME, "Matching tag name found");\r
689                                                         found = true;\r
690                                                 }\r
691                                         }\r
692                                         if (!found)\r
693                                                 enTag = noteStore.createTag(authToken, enTag);\r
694                                         else\r
695                                                 enTag.setUpdateSequenceNum(noteStore.updateTag(authToken,enTag));\r
696                                         sequence = enTag.getUpdateSequenceNum();\r
697                                         if (!oldGuid.equals(enTag.getGuid())) {\r
698                                                 logger.log(logger.EXTREME, "Updating tag guid");\r
699                                                 conn.getTagTable().updateTagGuid(oldGuid, enTag.getGuid());\r
700                                         }\r
701                                 }\r
702                                 logger.log(logger.EXTREME, "Updating tag sequence number");\r
703                                 conn.getTagTable().updateTagSequence(enTag.getGuid(), sequence);\r
704                                 logger.log(logger.EXTREME, "Resetting tag dirty flag");\r
705                                 conn.getTagTable().resetDirtyFlag(enTag.getGuid());\r
706                                 logger.log(logger.EXTREME, "Emitting sequence number to the main thread.");\r
707                                 updateSequenceNumber = sequence;\r
708                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
709                         } catch (EDAMUserException e) {\r
710                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags");\r
711                                 logger.log(logger.LOW, e.toString());           \r
712                                 error = true;\r
713                         } catch (EDAMSystemException e) {\r
714                                 logger.log(logger.LOW, "** EDAM System Excepton syncLocalTags");\r
715                                 logger.log(logger.LOW, e.toString());   \r
716                                 error = true;\r
717                         } catch (EDAMNotFoundException e) {\r
718                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalTags");\r
719                                 logger.log(logger.LOW, e.toString());   \r
720                                 error = true;\r
721                         } catch (TException e) {\r
722                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalTags");\r
723                                 logger.log(logger.LOW, e.toString());           \r
724                                 error = true;\r
725                         }       \r
726                         \r
727                         // Find the next tag\r
728                         logger.log(logger.EXTREME, "Finding next tag");\r
729                         enTag = findNextTag();\r
730                 }\r
731                 logger.log(logger.HIGH, "Leaving SyncRunner.syncLocalTags");\r
732         }\r
733         // Sync Tags with Evernote\r
734         private void syncLocalSavedSearches() {\r
735                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalSavedSearches");\r
736                 List<SavedSearch> remoteList = new ArrayList<SavedSearch>();\r
737                 status.message.emit(tr("Sending saved searches."));\r
738         \r
739                 logger.log(logger.EXTREME, "Getting saved searches to compare with local");\r
740                 try {\r
741                         remoteList = noteStore.listSearches(authToken);\r
742                 } catch (EDAMUserException e1) {\r
743                         logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags getting remote saved search List");\r
744                         status.message.emit(tr("Error: ") +e1);\r
745                         logger.log(logger.LOW, e1.toString());  \r
746                         error = true;\r
747                 } catch (EDAMSystemException e1) {\r
748                         logger.log(logger.LOW, "*** EDAM System Excepton syncLocalTags getting remote saved search List");\r
749                         status.message.emit(tr("Error: ") +e1);\r
750                         logger.log(logger.LOW, e1.toString());          \r
751                         error = true;\r
752                 } catch (TException e1) {\r
753                         logger.log(logger.LOW, "*** EDAM Transaction Excepton syncLocalTags getting remote saved search List");\r
754                         status.message.emit(tr("Error: ") +e1);\r
755                         logger.log(logger.LOW, e1.toString());  \r
756                         error = true;\r
757                 }               \r
758                 \r
759                 List<SavedSearch> searches = conn.getSavedSearchTable().getDirty();\r
760                 int sequence;\r
761                 // Sync the local notebooks with Evernote's\r
762                 logger.log(logger.EXTREME, "Beginning to send saved searches");\r
763                 for (int i=0; i<searches.size() &&  keepRunning; i++) {\r
764                         \r
765                         if (authRefreshNeeded)\r
766                                 refreshConnection();\r
767                         \r
768                         SavedSearch enSearch = searches.get(i);\r
769                         try {\r
770                                 if (enSearch.getUpdateSequenceNum() > 0) \r
771                                         sequence = noteStore.updateSearch(authToken, enSearch);\r
772                                 else {\r
773                                         logger.log(logger.EXTREME, "New saved search found.");\r
774                                         // Look for a tag with the same name.  If one is found, we don't need \r
775                                         // to create another one\r
776                                         boolean found = false;\r
777                                         logger.log(logger.EXTREME, "Matching remote saved search names with local");\r
778                                         for (int k=0; k<remoteList.size() && !found && keepRunning; k++) {\r
779                                                 if (remoteList.get(k).getName().equalsIgnoreCase(enSearch.getName())) {\r
780                                                         enSearch = remoteList.get(k);\r
781                                                         found = true;\r
782                                                         logger.log(logger.EXTREME, "Matching saved search found");\r
783                                                         sequence = enSearch.getUpdateSequenceNum();\r
784                                                 }\r
785                                         }\r
786 \r
787                                         String oldGuid = enSearch.getGuid();\r
788                                         if (!found)\r
789                                                 enSearch = noteStore.createSearch(authToken, enSearch);\r
790                                         sequence = enSearch.getUpdateSequenceNum();\r
791                                         logger.log(logger.EXTREME, "Updating tag guid in local database");\r
792                                         conn.getTagTable().updateTagGuid(oldGuid, enSearch.getGuid());\r
793                                 }\r
794                                 logger.log(logger.EXTREME, "Updating tag sequence in local database");\r
795                                 conn.getSavedSearchTable().updateSavedSearchSequence(enSearch.getGuid(), sequence);\r
796                                 logger.log(logger.EXTREME, "Resetting tag dirty flag");\r
797                                 conn.getSavedSearchTable().resetDirtyFlag(enSearch.getGuid());\r
798                                 logger.log(logger.EXTREME, "Emitting sequence number to the main thread.");\r
799                                 updateSequenceNumber = sequence;\r
800                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
801                         } catch (EDAMUserException e) {\r
802                                 logger.log(logger.LOW, "*** EDAM User Excepton syncLocalTags");\r
803                                 logger.log(logger.LOW, e.toString());   \r
804                                 error = true;\r
805                         } catch (EDAMSystemException e) {\r
806                                 logger.log(logger.LOW, "** EDAM System Excepton syncLocalTags");\r
807                                 logger.log(logger.LOW, e.toString());   \r
808                                 error = true;\r
809                         } catch (EDAMNotFoundException e) {\r
810                                 logger.log(logger.LOW, "*** EDAM Not Found Excepton syncLocalTags");\r
811                                 logger.log(logger.LOW, e.toString());   \r
812                                 error = true;\r
813                         } catch (TException e) {\r
814                                 logger.log(logger.LOW, "*** EDAM TExcepton syncLocalTags");\r
815                                 logger.log(logger.LOW, e.toString());   \r
816                                 error = true;\r
817                         }               \r
818                 }\r
819                 logger.log(logger.HIGH, "Entering SyncRunner.syncLocalSavedSearches");\r
820         }       \r
821 \r
822         // Sync evernote changes with local database\r
823         private void syncRemoteToLocal() {\r
824                 logger.log(logger.HIGH, "Entering SyncRunner.syncRemoteToLocal");\r
825 \r
826                 List<Note> dirtyNotes = conn.getNoteTable().getDirty();\r
827                 dirtyNoteGuids = new Vector<String>();\r
828                 for (int i=0; i<dirtyNotes.size() && keepRunning; i++) {\r
829                         dirtyNoteGuids.add(dirtyNotes.get(i).getGuid());\r
830                 }\r
831                 \r
832                 int chunkSize = 10;\r
833                 SyncChunk chunk = null;\r
834                 boolean fullSync = false;\r
835                 boolean more = true;\r
836                 \r
837                 if (updateSequenceNumber == 0)\r
838                         fullSync = true;\r
839                 \r
840                 status.message.emit(tr("Downloading 0% complete."));\r
841                 \r
842                 while(more &&  keepRunning) {\r
843                         \r
844                         if (authRefreshNeeded)\r
845                                 refreshConnection();\r
846                         \r
847                         chunk = null;\r
848                         int sequence = updateSequenceNumber;\r
849                         try {\r
850                                 logger.log(logger.EXTREME, "Getting chunk from Evernote");\r
851                                 chunk = noteStore.getSyncChunk(authToken, sequence, chunkSize, fullSync);\r
852                         } catch (EDAMUserException e) {\r
853                                 error = true;\r
854                                 e.printStackTrace();\r
855                                 status.message.emit(e.getMessage());\r
856                         } catch (EDAMSystemException e) {\r
857                                 error = true;\r
858                                 e.printStackTrace();\r
859                                 status.message.emit(e.getMessage());\r
860                         } catch (TException e) {\r
861                                 error = true;\r
862                                 e.printStackTrace();\r
863                                 status.message.emit(e.getMessage());\r
864                         } \r
865                         if (error || chunk == null) \r
866                                 return;\r
867                                 \r
868                 \r
869                         \r
870                         syncRemoteTags(chunk.getTags());\r
871                         syncRemoteSavedSearches(chunk.getSearches());\r
872                         syncRemoteNotebooks(chunk.getNotebooks());\r
873                         syncRemoteNotes(chunk.getNotes(), fullSync);\r
874                         syncRemoteResources(chunk.getResources());\r
875                         \r
876                         // Do the local deletes\r
877                         logger.log(logger.EXTREME, "Doing local deletes");\r
878                         List<String> guid = chunk.getExpungedNotes();\r
879                         if (guid != null) {\r
880                                 for (int i=0; i<guid.size() && keepRunning; i++) {\r
881                                         String notebookGuid = "";\r
882                                         Note localNote = conn.getNoteTable().getNote(guid.get(i), false, false, false, false, false);\r
883                                         if (localNote != null) {\r
884                                                 conn.getNoteTable().updateNoteSequence(guid.get(i), 0);\r
885                                                 notebookGuid = localNote.getNotebookGuid();\r
886                                         }\r
887                                         if (!conn.getNotebookTable().isNotebookLocal(notebookGuid)) {\r
888                                                 logger.log(logger.EXTREME, "Expunging local note from database");\r
889                                                 conn.getNoteTable().expungeNote(guid.get(i), true, false);\r
890                                         }\r
891                                 }\r
892                         }\r
893                         guid = chunk.getExpungedNotebooks();\r
894                         if (guid != null)\r
895                                 for (int i=0; i<guid.size() && keepRunning; i++) {\r
896                                         logger.log(logger.EXTREME, "Expunging local notebook from database");\r
897                                         conn.getNotebookTable().expungeNotebook(guid.get(i), false);\r
898                                 }\r
899                         guid = chunk.getExpungedTags();\r
900                         if (guid != null)\r
901                                 for (int i=0; i<guid.size() && keepRunning; i++) {\r
902                                         logger.log(logger.EXTREME, "Expunging tags from local database");\r
903                                         conn.getTagTable().expungeTag(guid.get(i), false);\r
904                                 }\r
905                         guid = chunk.getExpungedSearches();\r
906                         if (guid != null) \r
907                                 for (int i=0; i<guid.size() && keepRunning; i++) {\r
908                                         logger.log(logger.EXTREME, "Expunging saved search from local database");\r
909                                         conn.getSavedSearchTable().expungeSavedSearch(guid.get(i), false);\r
910                                 }\r
911 \r
912                         \r
913                         // Check for more notes\r
914                         if (chunk.getChunkHighUSN() <= updateSequenceNumber) \r
915                                 more = false;\r
916                         if (error)\r
917                                 more = false;\r
918                         logger.log(logger.EXTREME, "More notes? " +more);\r
919 \r
920                         \r
921                         // Save the chunk sequence number\r
922                         if (!error && chunk.getChunkHighUSN() > 0) {\r
923                                 logger.log(logger.EXTREME, "emitting sequence number to main thread");\r
924                                 updateSequenceNumber = chunk.getChunkHighUSN();\r
925                                 conn.getSyncTable().setLastSequenceDate(chunk.getCurrentTime());\r
926                                 conn.getSyncTable().setUpdateSequenceNumber(updateSequenceNumber);\r
927                         }\r
928                         \r
929                         \r
930                         if (more) {\r
931                                 long pct = chunk.getChunkHighUSN() * 100;\r
932                                 conn.getSyncTable().setLastSequenceDate(chunk.getCurrentTime());\r
933                                 pct = pct/evernoteUpdateCount;\r
934                                 status.message.emit(tr("Downloading ") +new Long(pct).toString()+tr("% complete."));\r
935                         }\r
936                 }\r
937 \r
938                 logger.log(logger.HIGH, "Leaving SyncRunner.syncRemoteToLocal");\r
939         }\r
940         // Sync remote tags\r
941         private void syncRemoteTags(List<Tag> tags) {\r
942                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteTags");\r
943                 if (tags != null) {\r
944                         for (int i=0; i<tags.size() && keepRunning; i++) {\r
945                                 String oldGuid;\r
946                                 oldGuid = conn.getTagTable().findTagByName(tags.get(i).getName());\r
947                                 if (oldGuid != null && !tags.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
948                                         conn.getTagTable().updateTagGuid(oldGuid, tags.get(i).getGuid());\r
949                                 conn.getTagTable().syncTag(tags.get(i), false);\r
950                         }\r
951                 }\r
952                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteTags");\r
953         }\r
954         // Sync remote tags\r
955         private void syncRemoteSavedSearches(List<SavedSearch> searches) {\r
956                 logger.log(logger.EXTREME, "Entering SyncRunner.syncSavedSearches");\r
957                 if (searches != null) {\r
958                         for (int i=0; i<searches.size() && keepRunning; i++) {\r
959                                 String oldGuid;\r
960                                 oldGuid = conn.getSavedSearchTable().findSavedSearchByName(searches.get(i).getName());\r
961                                 if (oldGuid != null && !searches.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
962                                         conn.getSavedSearchTable().updateSavedSearchGuid(oldGuid, searches.get(i).getGuid());\r
963                                 conn.getSavedSearchTable().syncSavedSearch(searches.get(i), false);\r
964                         }\r
965                 }\r
966                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncSavedSearches");\r
967         }\r
968         // Sync remote Notebooks 2\r
969         private void syncRemoteNotebooks(List<Notebook> notebooks) {\r
970                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotebooks");\r
971                 if (notebooks != null) {\r
972                         for (int i=0; i<notebooks.size() && keepRunning; i++) {\r
973                                 String oldGuid;\r
974                                 oldGuid = conn.getNotebookTable().findNotebookByName(notebooks.get(i).getName());\r
975                                 if (oldGuid != null && !conn.getNotebookTable().isNotebookLocal(oldGuid) && !notebooks.get(i).getGuid().equalsIgnoreCase(oldGuid))\r
976                                         conn.getNotebookTable().updateNotebookGuid(oldGuid, notebooks.get(i).getGuid());\r
977                                 conn.getNotebookTable().syncNotebook(notebooks.get(i), false); \r
978                         }\r
979                 }                       \r
980                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotebooks");\r
981         }\r
982         // Sync remote Resources\r
983         private void syncRemoteResources(List<Resource> resource) {\r
984                 // This is how the logic for this works.\r
985                 // 1.) If the resource is not in the local database, we add it.\r
986                 // 2.) If a copy of the resource is in the local database and the note isn't dirty, we update the local copy\r
987                 // 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
988                 //     is a conflict.  The note conflict should get a copy of the resource at that time.\r
989                 \r
990                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteResources");\r
991                 if (resource != null) {\r
992                         for (int i=0; i<resource.size() && keepRunning; i++) {\r
993                                 boolean saveNeeded = false;\r
994 /* #1 */                Resource r = getEvernoteResource(resource.get(i).getGuid(), true,true,true);\r
995                                 Resource l = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), false);\r
996                                 if (l == null) {\r
997                                         saveNeeded = true;\r
998                                 } else {\r
999 /* #2 */                        boolean isNoteDirty = conn.getNoteTable().isNoteDirty(r.getNoteGuid());\r
1000                                         if (!isNoteDirty)\r
1001                                                 saveNeeded = true;\r
1002                                         else {\r
1003 /* #3 */                                String remoteHash = "";\r
1004                                                 if (r != null && r.getData() != null && r.getData().getBodyHash() != null)\r
1005                                                         remoteHash = byteArrayToHexString(r.getData().getBodyHash());\r
1006                                                 String localHash = "";\r
1007                                                 if (l != null && l.getData() != null && l.getData().getBodyHash() != null)\r
1008                                                         remoteHash = byteArrayToHexString(l.getData().getBodyHash());\r
1009                                 \r
1010                                                 if (localHash.equalsIgnoreCase(remoteHash))\r
1011                                                         saveNeeded = true;\r
1012                                         }\r
1013                                 }\r
1014                                 \r
1015                                 if (saveNeeded) \r
1016                                         conn.getNoteTable().noteResourceTable.updateNoteResource(r, false);\r
1017 \r
1018                         }\r
1019                 }\r
1020                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteResources");\r
1021         }\r
1022         // Sync remote notebooks\r
1023         private void syncRemoteNotes(List<Note> note, boolean fullSync) {\r
1024                 logger.log(logger.EXTREME, "Entering SyncRunner.syncRemoteNotes");\r
1025                 if (note != null) {\r
1026                         for (int i=0; i<note.size() && keepRunning; i++) {\r
1027                                 Note n = getEvernoteNote(note.get(i).getGuid(), true, fullSync, true,true);\r
1028                                 if (n!=null) {\r
1029                                         \r
1030                                         // Basically, this is how the sync logic for a note works.\r
1031                                         // If the remote note has changed and the local has not, we\r
1032                                         // accept the change.\r
1033                                         // If both the local & remote have changed but the sequence\r
1034                                         // numbers are the same, we don't accept the change.  This\r
1035                                         // seems to happen when attachments are indexed by the server.\r
1036                                         // If both the local & remote have changed and the sequence numbers\r
1037                                         // are different we move the local copy to a local notebook (making sure\r
1038                                         // to copy all resources) and we accept the new one.                    \r
1039                                         boolean conflictingNote = true;\r
1040                                         logger.log(logger.EXTREME, "Checking for duplicate note " +n.getGuid());\r
1041                                         if (dirtyNoteGuids.contains(n.getGuid())) { \r
1042                                                 logger.log(logger.EXTREME, "Conflict check beginning");\r
1043                                                 conflictingNote = checkForConflict(n);\r
1044                                                 logger.log(logger.EXTREME, "Conflict check results " +conflictingNote);\r
1045                                                 if (conflictingNote)\r
1046                                                         moveConflictingNote(n.getGuid());\r
1047                                         }\r
1048                                         if (conflictingNote || fullSync) {\r
1049                                                 logger.log(logger.EXTREME, "Saving Note");\r
1050                                                 conn.getNoteTable().syncNote(n, false);\r
1051                                                 noteSignal.noteChanged.emit(n.getGuid(), null);   // Signal to ivalidate note cache\r
1052                                                 noteSignal.noteDownloaded.emit(n, true);                // Signal to add note to index\r
1053                                                 logger.log(logger.EXTREME, "Note Saved");\r
1054                                                 if (fullSync && n.getResources() != null) {\r
1055                                                         for (int q=0; q<n.getResources().size() && keepRunning; q++) {\r
1056                                                                 logger.log(logger.EXTREME, "Getting note resources.");\r
1057                                                                 conn.getNoteTable().noteResourceTable.updateNoteResource(n.getResources().get(q), false);\r
1058                                                         }\r
1059                                                 }\r
1060                                         }\r
1061                                 }\r
1062                         }\r
1063                 }\r
1064                 logger.log(logger.EXTREME, "Leaving SyncRunner.syncRemoteNotes");\r
1065         }\r
1066         private Note getEvernoteNote(String guid, boolean withContent, boolean withResourceData, boolean withResourceRecognition, boolean withResourceAlternateData) { \r
1067                 Note n = null;\r
1068                 try {\r
1069                         logger.log(logger.EXTREME, "Retrieving note " +guid);\r
1070                         n = noteStore.getNote(authToken, guid, withContent, withResourceData, withResourceRecognition, withResourceAlternateData);\r
1071                         logger.log(logger.EXTREME, "Note " +guid +" has been retrieved.");\r
1072                 } catch (EDAMUserException e) {\r
1073                         logger.log(logger.LOW, "*** EDAM User Excepton getEvernoteNote");\r
1074                         logger.log(logger.LOW, e.toString());   \r
1075                         error = true;\r
1076                         e.printStackTrace();\r
1077                 } catch (EDAMSystemException e) {\r
1078                         logger.log(logger.LOW, "*** EDAM System Excepton getEvernoteNote");\r
1079                         logger.log(logger.LOW, e.toString());   \r
1080                         error = true;\r
1081                         e.printStackTrace();\r
1082                 } catch (EDAMNotFoundException e) {\r
1083                         logger.log(logger.LOW, "*** EDAM Not Found Excepton getEvernoteNote");\r
1084                         logger.log(logger.LOW, e.toString());   \r
1085                         error = true;\r
1086                         e.printStackTrace();\r
1087                 } catch (TException e) {\r
1088                         logger.log(logger.LOW, "*** EDAM TExcepton getEvernoteNote");\r
1089                         logger.log(logger.LOW, e.toString());   \r
1090                         error = true;\r
1091                         e.printStackTrace();\r
1092                 }\r
1093                 return n;\r
1094         }\r
1095         private Resource getEvernoteResource(String guid, boolean withData, boolean withRecognition, boolean withAttributes) { \r
1096                 Resource n = null;\r
1097                 try {\r
1098                         logger.log(logger.EXTREME, "Retrieving resource " +guid);\r
1099                         n = noteStore.getResource(authToken, guid, withData, withRecognition, withAttributes, withAttributes);\r
1100                         logger.log(logger.EXTREME, "Resource " +guid +" has been retrieved.");\r
1101                 } catch (EDAMUserException e) {\r
1102                         logger.log(logger.LOW, "*** EDAM User Excepton getEvernoteNote");\r
1103                         logger.log(logger.LOW, e.toString());   \r
1104                         error = true;\r
1105                         e.printStackTrace();\r
1106                 } catch (EDAMSystemException e) {\r
1107                         logger.log(logger.LOW, "*** EDAM System Excepton getEvernoteNote");\r
1108                         logger.log(logger.LOW, e.toString());   \r
1109                         error = true;\r
1110                         e.printStackTrace();\r
1111                 } catch (EDAMNotFoundException e) {\r
1112                         logger.log(logger.LOW, "*** EDAM Not Found Excepton getEvernoteNote");\r
1113                         logger.log(logger.LOW, e.toString());   \r
1114                         error = true;\r
1115                         e.printStackTrace();\r
1116                 } catch (TException e) {\r
1117                         logger.log(logger.LOW, "*** EDAM TExcepton getEvernoteNote");\r
1118                         logger.log(logger.LOW, e.toString());   \r
1119                         error = true;\r
1120                         e.printStackTrace();\r
1121                 }\r
1122                 return n;\r
1123         }\r
1124 \r
1125         \r
1126         private boolean checkForConflict(Note n) {\r
1127                 logger.log(logger.EXTREME, "Checking note sequence number  " +n.getGuid());\r
1128                 Note oldNote = conn.getNoteTable().getNote(n.getGuid(), false, false, false, false, false);\r
1129                 logger.log(logger.EXTREME, "Local/Remote sequence numbers: " +oldNote.getUpdateSequenceNum()+"/"+n.getUpdateSequenceNum());\r
1130                 if (oldNote.getUpdateSequenceNum() == n.getUpdateSequenceNum())\r
1131                         return false;\r
1132                 return true;\r
1133         }\r
1134         \r
1135         private void moveConflictingNote(String guid) {\r
1136                 logger.log(logger.EXTREME, "Conflicting change found for note " +guid);\r
1137                 List<Notebook> books = conn.getNotebookTable().getAllLocal();\r
1138                 String notebookGuid = null;\r
1139                 for (int i=0; i<books.size() && keepRunning; i++) {\r
1140                         if (books.get(i).getName().equalsIgnoreCase("Conflicting Changes (local)") ||\r
1141                                         books.get(i).getName().equalsIgnoreCase("Conflicting Changes")) {\r
1142                                 notebookGuid = books.get(i).getGuid();\r
1143                                 i=books.size();\r
1144                         }\r
1145                 }\r
1146                 \r
1147                 if (notebookGuid == null) {\r
1148                         logger.log(logger.EXTREME, "Building conflicting change notebook " +guid);\r
1149                         Calendar currentTime = new GregorianCalendar();\r
1150                         Long l = new Long(currentTime.getTimeInMillis());\r
1151                         long prevTime = l;\r
1152                         while (prevTime==l) {\r
1153                                 currentTime = new GregorianCalendar();\r
1154                                 l=currentTime.getTimeInMillis();\r
1155                         }\r
1156                         String randint = new String(Long.toString(l));\r
1157                 \r
1158                         Notebook newBook = new Notebook();\r
1159                         newBook.setUpdateSequenceNum(0);\r
1160                         newBook.setGuid(randint);\r
1161                         newBook.setName("Conflicting Changes");\r
1162                         newBook.setServiceCreated(new Date().getTime());\r
1163                         newBook.setServiceUpdated(new Date().getTime());\r
1164                         newBook.setDefaultNotebook(false);\r
1165                         newBook.setPublished(false);\r
1166                         \r
1167                         conn.getNotebookTable().addNotebook(newBook, false, true);\r
1168                         notebookGuid = newBook.getGuid();\r
1169                 }\r
1170                 \r
1171                 // Now that we have a good notebook guid, we need to move the conflicting note\r
1172                 // to the local notebook\r
1173                 logger.log(logger.EXTREME, "Moving conflicting note " +guid);\r
1174                 Calendar currentTime = new GregorianCalendar();\r
1175                 Long l = new Long(currentTime.getTimeInMillis());\r
1176                 long prevTime = l;\r
1177                 while (prevTime==l) {\r
1178                         currentTime = new GregorianCalendar();\r
1179                         l = currentTime.getTimeInMillis();\r
1180                 }\r
1181                 String newGuid = new String(Long.toString(l));\r
1182                                         \r
1183                 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);\r
1184                 for (int i=0; i<oldNote.getResources().size() && keepRunning; i++) {\r
1185                         l = new Long(currentTime.getTimeInMillis());\r
1186                         String newResG = new String(Long.toString(l));\r
1187                         String oldResG = oldNote.getResources().get(i).getGuid();\r
1188                         conn.getNoteTable().noteResourceTable.resetUpdateSequenceNumber(oldResG, true);\r
1189                         conn.getNoteTable().noteResourceTable.updateNoteResourceGuid(oldResG, newResG, true);\r
1190                 }\r
1191                 \r
1192                 conn.getNoteTable().resetNoteSequence(guid);\r
1193                 conn.getNoteTable().updateNoteGuid(guid, newGuid);\r
1194                 conn.getNoteTable().updateNoteNotebook(newGuid, notebookGuid, true);\r
1195                 \r
1196                 \r
1197                 noteSignal.guidChanged.emit(guid,newGuid);\r
1198         }\r
1199         \r
1200         \r
1201 \r
1202         \r
1203         //******************************************************\r
1204         //******************************************************\r
1205         //** Utility Functions\r
1206         //******************************************************\r
1207         //******************************************************\r
1208         // Convert a byte array to a hex string\r
1209         private static String byteArrayToHexString(byte data[]) {\r
1210                 StringBuffer buf = new StringBuffer();\r
1211             for (byte element : data) {\r
1212                 int halfbyte = (element >>> 4) & 0x0F;\r
1213                 int two_halfs = 0;\r
1214                 do {\r
1215                         if ((0 <= halfbyte) && (halfbyte <= 9))\r
1216                                buf.append((char) ('0' + halfbyte));\r
1217                            else\r
1218                                 buf.append((char) ('a' + (halfbyte - 10)));\r
1219                         halfbyte = element & 0x0F;\r
1220                 } while(two_halfs++ < 1);\r
1221             }\r
1222             return buf.toString();              \r
1223         }\r
1224 \r
1225         \r
1226         \r
1227         //*******************************************************\r
1228         //* Find dirty tags, which do not have newly created parents\r
1229         //*******************************************************\r
1230         private Tag findNextTag() {\r
1231                 logger.log(logger.HIGH, "Entering SyncRunner.findNextTag");\r
1232                 Tag nextTag = null;\r
1233                 List<Tag> tags = conn.getTagTable().getDirty();\r
1234                 \r
1235                 // Find the parent.  If the parent has a sequence > 0 then it is a good\r
1236                 // parent.\r
1237                 for (int i=0; i<tags.size() && keepRunning; i++) {\r
1238                         if (tags.get(i).getParentGuid() == null) {\r
1239                                 logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - tag found without parent");\r
1240                                 return tags.get(i);\r
1241                         }\r
1242                         Tag parentTag = conn.getTagTable().getTag(tags.get(i).getParentGuid());\r
1243                         if (parentTag.getUpdateSequenceNum() > 0) {\r
1244                                 logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - tag found");\r
1245                                 return tags.get(i);\r
1246                         }\r
1247                 }\r
1248                 \r
1249                 logger.log(logger.HIGH, "Leaving SyncRunner.findNextTag - no tags returned");\r
1250                 return nextTag;\r
1251         }\r
1252         \r
1253         \r
1254            // Connect to Evernote\r
1255     public boolean enConnect()  {\r
1256         try {\r
1257                         userStoreTrans = new THttpClient(userStoreUrl);\r
1258                 } catch (TTransportException e) {\r
1259                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1260                         mb.exec();\r
1261                         e.printStackTrace();\r
1262                 }\r
1263                 userStoreProt = new TBinaryProtocol(userStoreTrans);\r
1264             userStore = new UserStore.Client(userStoreProt, userStoreProt);\r
1265             syncSignal.saveUserStore.emit(userStore);\r
1266             try {\r
1267                         authResult = userStore.authenticate(username, password, consumerKey, consumerSecret);\r
1268                 } catch (EDAMUserException e) {\r
1269                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Error", "Incorrect username/password");\r
1270                         mb.exec();\r
1271                         isConnected = false;\r
1272                         return false;\r
1273                 } catch (EDAMSystemException e) {\r
1274                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "EDAM System Excepton", e.getLocalizedMessage());\r
1275                         mb.exec();\r
1276                         e.printStackTrace();\r
1277                         isConnected = false;\r
1278                 } catch (TException e) {\r
1279                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1280                         mb.exec();\r
1281                         e.printStackTrace();\r
1282                         isConnected = false;\r
1283                 }\r
1284                 \r
1285             boolean versionOk = false;\r
1286                 try {\r
1287 //                      versionOk = userStore.checkVersion("Dave's EDAMDemo (Java)", \r
1288                         versionOk = userStore.checkVersion("NeverNote", \r
1289                     com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR, \r
1290                       com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR);\r
1291                 } catch (TException e) {\r
1292                         e.printStackTrace();\r
1293                         isConnected = false;\r
1294                 } \r
1295             if (!versionOk) { \r
1296                 System.err.println("Incomatible EDAM client protocol version"); \r
1297                 isConnected = false;\r
1298             }\r
1299             if (authResult != null) {\r
1300                 user = authResult.getUser(); \r
1301                 authToken = authResult.getAuthenticationToken(); \r
1302                 noteStoreUrl = noteStoreUrlBase + user.getShardId();\r
1303                 syncSignal.saveAuthToken.emit(authToken);\r
1304                 syncSignal.saveNoteStore.emit(noteStore);\r
1305                 \r
1306          \r
1307                 try {\r
1308                         noteStoreTrans = new THttpClient(noteStoreUrl);\r
1309                 } catch (TTransportException e) {\r
1310                         QMessageBox mb = new QMessageBox(QMessageBox.Icon.Critical, "Transport Excepton", e.getLocalizedMessage());\r
1311                         mb.exec();\r
1312                         e.printStackTrace();\r
1313                         isConnected = false;\r
1314                 } \r
1315                 noteStoreProt = new TBinaryProtocol(noteStoreTrans);\r
1316                 noteStore = \r
1317                         new NoteStore.Client(noteStoreProt, noteStoreProt); \r
1318                 isConnected = true;\r
1319                 authTimeRemaining = authResult.getExpiration() - authResult.getCurrentTime();\r
1320                 authRefreshTime = authTimeRemaining / 2;\r
1321             }\r
1322             \r
1323                 // Get user information\r
1324                 try {\r
1325                         User user = userStore.getUser(authToken);\r
1326                         syncSignal.saveUserInformation.emit(user);\r
1327                 } catch (EDAMUserException e1) {\r
1328                         e1.printStackTrace();\r
1329                 } catch (EDAMSystemException e1) {\r
1330                         e1.printStackTrace();\r
1331                 } catch (TException e1) {\r
1332                         e1.printStackTrace();\r
1333                 }\r
1334             \r
1335             return isConnected;\r
1336     }\r
1337         // Disconnect from the database                         \r
1338     public void enDisconnect() {\r
1339         isConnected = false;\r
1340     }\r
1341     // Refresh the connection\r
1342     private synchronized void refreshConnection() {\r
1343                 logger.log(logger.EXTREME, "Entering SyncRunner.refreshConnection()");\r
1344 //        Calendar cal = Calendar.getInstance();\r
1345                 \r
1346         // If we are not connected let's get out of here\r
1347         if (!isConnected)\r
1348                 return;\r
1349         \r
1350                 // If we fail too many times, then let's give up.\r
1351                 if (failedRefreshes >=5) {\r
1352                         logger.log(logger.EXTREME, "Refresh attempts have failed.  Disconnecting.");\r
1353                         isConnected = false;\r
1354                         return;\r
1355                 }\r
1356         \r
1357                 // If this is the first time through, then we need to set this\r
1358 //              if (authRefreshTime == 0 || cal.getTimeInMillis() > authRefreshTime) \r
1359 //                      authRefreshTime = cal.getTimeInMillis();\r
1360                 \r
1361  //             // Default to checking again in 5 min.  This in case we fail.\r
1362  //             authRefreshTime = authRefreshTime +(5*60*1000);     \r
1363 \r
1364                 // Try to get a new token\r
1365                 AuthenticationResult newAuth = null; \r
1366                 logger.log(logger.EXTREME, "Beginning to try authentication refresh");\r
1367         try {\r
1368                 if (userStore != null && authToken != null) \r
1369                         newAuth = userStore.refreshAuthentication(authToken); \r
1370                 else\r
1371                         return;\r
1372                 logger.log(logger.EXTREME, "UserStore.refreshAuthentication has succeeded.");\r
1373                 } catch (EDAMUserException e) {\r
1374                         e.printStackTrace();\r
1375                         syncSignal.authRefreshComplete.emit(false);\r
1376                         failedRefreshes++;\r
1377                         return;\r
1378                 } catch (EDAMSystemException e) {\r
1379                         e.printStackTrace();\r
1380                         syncSignal.authRefreshComplete.emit(false);\r
1381                         failedRefreshes++;\r
1382                         return;         \r
1383                 } catch (TException e) { \r
1384                         e.printStackTrace();\r
1385                         syncSignal.authRefreshComplete.emit(false);\r
1386                         failedRefreshes++;\r
1387                         return;\r
1388                 }\r
1389                 \r
1390                 // If we didn't get a good auth, then we've failed\r
1391                 if (newAuth == null) {\r
1392                         failedRefreshes++;\r
1393                         logger.log(logger.EXTREME, "Authentication failure #" +failedRefreshes);\r
1394                         syncSignal.authRefreshComplete.emit(false);\r
1395                         return;\r
1396                 }\r
1397                 \r
1398                 // We got a good token.  Now we need to setup the time to renew it.\r
1399                 logger.log(logger.EXTREME, "Saving authentication tokens");\r
1400                 authResult = newAuth;\r
1401                 authToken = new String(newAuth.getAuthenticationToken());\r
1402 //              authTimeRemaining = authResult.getExpiration() - authResult.getCurrentTime();\r
1403 //              authRefreshTime = cal.getTimeInMillis() + (authTimeRemaining/4);        \r
1404                 failedRefreshes=0;\r
1405                 syncSignal.authRefreshComplete.emit(true);\r
1406                 authRefreshNeeded = false;\r
1407                         \r
1408                 // This should never happen, but if it does we consider this a faild attempt.\r
1409 //              if (authTimeRemaining <= 0) {\r
1410 //                      failedRefreshes++;\r
1411 //                      syncSignal.authRefreshComplete.emit(false);\r
1412 //              }\r
1413     }\r
1414     \r
1415         public synchronized boolean addWork(String request) {\r
1416                 if (workQueue.offer(request))\r
1417                         return true;\r
1418                 return false;\r
1419         }\r
1420     \r
1421     private Note getNoteContent(Note n) {\r
1422         n.setContent(conn.getNoteTable().getNoteContentBinary(n.getGuid()));\r
1423         return n;\r
1424     }\r
1425 }\r