OSDN Git Service

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