OSDN Git Service

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